text:
Q: I can't update Ubuntu 18.04 I can't update, install or even remove program without getting this error message:
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
libpython3.7-stdlib : Depends:
libpython3.7-minimal (= 3.7.0-
1+xenial2) but 3.7.1-1~18.04 is installed
 python3.7 : Depends:
 libpython3.7-stdlib (= 3.7.1-1~18.04) but 3.7.0-1+xenial2 is installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Number of ways so that at least one soldier find that soldier next to him is also selected. 20 soldiers are standing in a row and their captain want to send 7 out of them for a mission. In how many ways can captain select them such that at least one soldier find that soldier next to him is also selected.
How to approach this question? Could someone give me some hint?

A: Let us ask the related question: how many ways can seven be chosen from a row such that none of them are adjacent.
To count this, consider two cases: either the last person is selected or he isn't.
In the first case (last person is selected), among the first 19 people, think of it as sequences of six $Xo$'s and 7 $o$'s.  For example $Xo~o~o~o~Xo~o~Xo~Xo~o~o~o~Xo~Xo$ corresponds to the outcome that the first, sixth, ninth, sixteenth, eighteenth, (and twentieth) soldiers are all selected.
Convince yourself that the number of outcomes in the first case are equal to the number of sequences of $6$ $A$'s and $7$ $B$'s.  How many such sequences are there?

 $\binom{13}{6}$

For the second case (the last person is not selected), then among the first $20$ people, consider sequences of $\underline{~~~~~~~}$ $Xo$'s and $\underline{~~~~~~~}$ $o$'s

$7$ copies of $Xo$ and $6$ copies of $o$.

Similarly convince yourself that you can count the number of outcomes in the second case by counting number of sequences of $A$'s and $B$'s.  There are then $\underline{~~~~~~~}$ outcomes in the second case

$\binom{13}{7}$

Combining this information together, we have the total number of ways in which all selected soldiers not adjacent to any other soldier.
How many ways can we select seven soldiers if we don't care if any are standing together or not?

 $\binom{20}{7}$

How do you combine these two ideas to find the number of outcomes that you are interested in, counting how many ways we can select soldiers such that at least one selected soldier is standing next to another selected soldier?
(what is the opposite of no selected soldier standing next to another selected soldier?)

A: Hint $1$:

 Ans $=$ (Total ways of selecting) $-$ (Ways of selecting with no two  adjacent)

Hint $2$:

 (Ways of selecting with no two  adjacent) $=$ (Ways of reinserting selections with no two adjacent)

Hint $3$:

 Reinsertions between the $13$ unchosen can be done at any $7$ of the uparrows

$\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow\bullet\uparrow$


text:
Q: I can't install python modules on Apple Silicon I have macbook air m1 and I can't install python modules like numpy, matplotlib.
I install python3.8 with homebrew then install virtaulenv. In venv, when I run 'pip install numpy' the error shows up:
'...  ERROR: Failed building wheel for numpy
Failed to build numpy
ERROR: Could not build wheels for numpy which use PEP 517 and cannot be installed directly'
I tried 'pip install --upgrade pip setuptools wheel' doesn't work. Please help.

A: Install python 3.9.1 from python.org (ARM version)
Then, for Numpy:
python3 -m pip install cython
python3 -m pip install --no-binary :all: --no-use-pep517 numpy==1.20rc1
Then, for matplotlib:
brew install libjpeg
python3 -m pip install matplotlib
This works for me on a Mac min with Apple Silicon.
No luck for SciPy yet, though.


text:
Q: Jpanels inside JLayeredPanel I'm using JLayeredPanel to put two panels on top of each other. The first panel would act like a background and the second panel which uses JFileChooser to get the user's image to print on the panel then that panel will lay on top of the first panel with a button click.
I've sucessfully get the image to print onto the second panel fron JFileChooser but unable to get the second panel to lay on top of the first panel.
Here's the outline.
http://s8.postimg.org/ofblrk179/outline.png
Here's my code.
...
    public class DesignerUI extends JFrame {
    public DesignerUI() {

   public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                DesignerUI frame = new DesignerUI();
                frame.setVisible(true);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
    card2 = new JPanel();
    cards.add(card2, "Design");
    card2.setLayout(null);

    JButton btnGraphic = new JButton("Add Graphic");
    btnGraphic.setBounds(0, 0, 400, 53);
    panel.add(btnGraphic);
    btnGraphic.addActionListener(new chooseGraphic());

    JLayeredPane lp = new JLayeredPane();
    lp.setPreferredSize(new Dimension(300,400));
    lp.setBounds(400,0,382,406);
    card2.add(lp);

    panel_1 = new JPanel();
    panel_1.setBounds(0, 0, 383, 406);

    picPanel = new JPanel();
    picPanel.setBounds(105, 115, 213, 200);

    lp.add(picPanel, new Integer(2));
    lp.add(panel_1, new Integer(3));

private class chooseGraphic implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        JFrame graphicInputWindow = new JFrame();
        new graphicInputWindow();
    }
}

public class graphicInputWindow extends JFrame {
    JButton button;
    JButton select;
    JLabel label;
    JPanel picPanel;
    Image image;

    public graphicInputWindow() {
        super("Select Your Image");
        setResizable(false);
        button = new JButton("Browse");
        button.setBounds(300, 300, 100, 40);
        select = new JButton("Select");
        select.setBounds(400, 300, 100, 40);
        picPanel = new JPanel();
        label = new JLabel();

        label.setBounds(10, 10, 670, 250);
        add(button);
        add(select);
        add(picPanel);
        add(label);

        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                JFileChooser file = new JFileChooser();
                file.setCurrentDirectory(new File(System
                        .getProperty("user.home")));

                // filter the files
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "*.Images", "jpg", "gif", "png");
                file.addChoosableFileFilter(filter);
                int result = file.showSaveDialog(null);

                // if the user click on save
                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = file.getSelectedFile();
                    String path = selectedFile.getAbsolutePath();
                    label.setIcon(ResizeImage(path));

                }

                // if the user click on cancel
                else if (result == JFileChooser.CANCEL_OPTION) {
                    System.out.println("No File Select");

                }
            }
        });

        select.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // if user click select
                JPanel picPanel = new JPanel(new BorderLayout());
                picPanel.add(label);
                lp.add(picPanel);
                lp.setVisible(true);
                //close window returns to card2
                setVisible(false);

            }
        });

        setSize(700, 400);
        setVisible(true);
        revalidate();
        contentPane.revalidate();
        contentPane.repaint();
    }

    public ImageIcon ResizeImage(String ImagePath) {
        ImageIcon MyImage = new ImageIcon(ImagePath);
        Image img = MyImage.getImage();
        Image newImg = img.getScaledInstance(panel_1.getWidth(),
                panel_1.getHeight(), Image.SCALE_SMOOTH);
        ImageIcon image = new ImageIcon(newImg);
        return image;
    }

    /*protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    }*/
}
}


text:
Q: OpenCL - How to declare a private array and dynamically initialise it I would like to have an array variable in private address space and dynamically initialise it with values.
Lets say I have the following code:
__kernel
void sample(__constant float * A){
    __private float temp[2]; // Lets assume I know the size upfront.
    for(int i = 0; i < 2; i++){
       temp[i] = A[i];
       printf("%.2f",temp[i]); // This works
    }
    printf("%.2f",temp[0]); // This does not work
 }

What do you think the last printf statement should print assuming vector A contains [1,2,3,4]. I guess it would be reasonable to expect to have [1] printed, but it always returns 0. In my opinion though, after a bit of experiment, I guess the code in some manner associate the actual var 'i' with the value A[i] in array rather than the value (i.e., index) of the var 'i' contains.
Any idea on what I might be missing ?


text:
Q: Python: Generalized input transformation decorator Writing a decorator to transform inputs of a function: Basic.
Writing a function that makes an input-transforming decorator for any single-input-transformer: Easy
Here is one way:
def input_wrap_decorator(preprocess):
    def decorator(func):
        def func_wrapper(*args, **kwargs):
            return func(preprocess(*args, **kwargs))
        return func_wrapper
    return decorator

Consider the following function:
def red_riding_hood(adj, noun='eyes'):
    return 'What {adj} {noun} you have!'.format(adj=adj, noun=noun)

Example of use:
assert red_riding_hood('big') == 'What big eyes you have!'
assert red_riding_hood('long', 'ears') == 'What long ears you have!'

Our input_wrap_decorator allows us to easily transform the first argument of red_riding_hood at will:
wrapped_func = input_wrap_decorator(lambda x: x.upper())(red_riding_hood)
assert wrapped_func('big') == 'What BIG eyes you have!'

wrapped_func = input_wrap_decorator(lambda x: 'very ' + x)(red_riding_hood)
assert wrapped_func('big') == 'What very big eyes you have!'

But if what if we want to transform other, or all, inputs of a function? Again, writing a specific decorator is basic, but there doesn't seem to be a single natural way to write a (parametrized) wrapper for the general case.
Any ideas?

A: Here are some answers to my own question. I intend to select someone else's answer to be THE answer if I find it to be more complete.
It seems there's no avoiding of imposing a protocol on the preprocess function, unless there's an obscure way to handle the args/kwargs conundrum gracefully. (Obscure only because I don't know of it.)
Here are several choices.
preprocess returns (transformed) args tuple
def wrap_args_deco(preprocess):
    """Preprocess needs to return the tuple of args (non-keyworded arguments)
    that should be passed on to the decorated func."""
    def decorator(func):
        def func_wrapper(*args, **kwargs):
            # NOTE: the only difference with input_wrap_decorator is the * before the preprocess
            return func(*preprocess(*args, **kwargs))
        return func_wrapper
    return decorator

Example of use:
def trans_args(adj, noun):
    '''adj is capitalized and noun is quoted'''
    return adj.upper(), '"{}"'.format(noun)
wrapped_func = wrap_args_deco(trans_args)(red_riding_hood)
assert wrapped_func('big', 'eyes') == 'What BIG "eyes" you have!'

There are some limitations here. For instance, you need to specify transformations for all arguments that don't have defaults, no matter if you want to transform them or not.
preprocess returns (transformed) kwargs dict
def wrap_kwargs_deco(preprocess):
    """Preprocess needs to return the dict of kwargs (keyworded, or named arguments)
    that should be passed on to the decorated func."""
    def decorator(func):
        def func_wrapper(*args, **kwargs):
            # NOTE: the only difference with input_wrap_decorator is the ** before the preprocess
            return func(**preprocess(*args, **kwargs))
        return func_wrapper
    return decorator

Example:
def trans_kwargs(adj, noun):
    '''adj is capitalized and noun is quoted'''
    return {'adj': adj.upper(), 'noun': '"{}"'.format(noun)}
wrapped_func = wrap_kwargs_deco(trans_kwargs)(red_riding_hood)
assert wrapped_func('big', 'eyes') == 'What BIG "eyes" you have!'

preprocess returns a (transformed) (args, kwargs) tuple
You could get (sorta) the best of both worlds by having the preprocess function return a transformed args (tuple) and kwargs (dict).
def wrap_args_and_kwargs_deco(preprocess):
    """Preprocess needs to return a the tuple (arg, kwargs) where
    arg is the list/tuple of (transformed) non-keyworded arguments and
    kwargs is the dict of (transformed) keyworded (a.k.a. "named") arguments
    that should be passed on to the decorated func."""
    def decorator(func):
        def func_wrapper(*args, **kwargs):
            args, kwargs = preprocess(*args, **kwargs)
            return func(*args, **kwargs)
        return func_wrapper
    return decorator

Example:
def trans_kwargs(adj, noun):
    return (adj.upper(),), {'noun': '"{}"'.format(noun)}
wrapped_func = wrap_args_and_kwargs_deco(trans_kwargs)(red_riding_hood)
assert wrapped_func('big', 'eyes') == 'What BIG "eyes" you have!'

specifying transformers for individual (keyworded) arguments
The options proposed above are more general than the following in the sense that they can base their transformation logic on a global view of all argument values. But in most cases you'll probably only need to transform an argument based on its name only. In that case, here's a solution to that problem offering a nicer interface.
from functools import wraps

def transform_args(**trans_func_for_arg):
    """
    Make a decorator that transforms function arguments before calling the function.
    Works with plain functions and bounded methods.
    """
    def transform_args_decorator(func):
        if len(trans_func_for_arg) == 0:  # if no transformations were specified...
            return func  # just return the function itself
        else:
            @wraps(func)
            def transform_args_wrapper(*args, **kwargs):
                # get a {argname: argval, ...} dict from *args and **kwargs
                # Note: Didn't really need an if/else here but I am assuming that...
                # Note: ... getcallargs gives us an overhead that can be avoided if there's only keyword args.
                if len(args) > 0:
                    val_of_argname = inspect.signature(func).bind_partial(*args, **kwargs).arguments
                else:
                    val_of_argname = kwargs
                for argname, trans_func in trans_func_for_arg.items():
                    val_of_argname[argname] = trans_func(val_of_argname[argname])
                # apply transform functions to argument values
                return func(**val_of_argname)

            return transform_args_wrapper

    return transform_args_decorator

Here is an example with more functionality coverage than the others:
# Example with a plain function
def f(a, b, c='default c'):
    return "a={a}, b={b}, c={c}".format(a=a, b=b, c=c)
def prepend_root(x):
    return 'ROOT/' + x

def test(f):
    assert f('foo', 'bar', 3) == 'a=foo, b=bar, c=3'
    ff = transform_args()(f)  # no transformation specification, so function is unchanged
    assert ff('foo', 'bar', 3) == 'a=foo, b=bar, c=3'
    ff = transform_args(a=prepend_root)(f)  # prepend root to a
    assert ff('foo', 'bar', 3) == 'a=ROOT/foo, b=bar, c=3'
    ff = transform_args(b=prepend_root)(f)  # prepend root to b
    assert ff('foo', 'bar', 3) == 'a=foo, b=ROOT/bar, c=3'
    ff = transform_args(a=prepend_root, b=prepend_root)(f)  # prepend root to a and b
    assert ff('foo', 'bar', 3) == 'a=ROOT/foo, b=ROOT/bar, c=3'

test(f)

# Example with a bounded method
class A:
    def __init__(self, sep=''):
        self.sep = sep
    def f(self, a, b, c):
        return f"a={a}{self.sep} b={b}{self.sep} c={c}"

a = A(sep=',')
test(a.f)

# Example of decorating the method on the class itself
A.f = transform_args(a=prepend_root, b=prepend_root)(A.f)
a = A(sep=',')
assert a.f('foo', 'bar', 3) == 'a=ROOT/foo, b=ROOT/bar, c=3'


text:
Q: Definition of a list in Scheme Finally taking the plunge to learn a Lisp dialect (Scheme), I have encountered two definitions of a list -

"Either the empty list or a pair whose cdr is a list".
"A collection of S-Expressions enclosed by parentheses".

Are these definitions equivalent?

A: They're as equivalent as {'a','b','c'} and "abc"
The former is the machine's logical representation of a list, the latter is how you represent it in your code.
And in scheme, you can pretty much treat everything as a list :) (Someone's going to downvote me for that, but I found it to be true when trying to think scheme-esque.)

A: I'm going to bring out my favourite dog-and-pony show!

(source: hedgee.com)
This corresponds to the following:
(let ((s5 (sqrt 5)))
  (/ (- (expt (/ (1+ s5) 2) n)
        (expt (/ (- 1 s5) 2) n)) s5))

The diagram illustrates your first statement (the empty-list object is denoted as a black box). The code snippet illustrates your second. :-)


text:
Q: Why is this Azure DevOps pipeline release failing? This is an ASP.NET Core 3.0 project that builds with no errors, but when it triggers the pipeline to release to Azure App Service, it fails with the following error:

2019-11-10T23:09:23.8008460Z ##[error]Error: No package found with specified pattern: D:\a\r1\a***.zip

What needs to be done to fix the release pipeline? The pipeline release is pulling the latest build as its artifact.

A: Assumptions
The following info assumes that you are appropriately publishing your build artifact from your Build pipeline, and that you have added the correct build artifact into you release pipeline.

In your release pipeline you have specified a build artifact in the Artifacts area

When adding your build artifact to your release pipeline, you chose to give it an alias of Build Artifact. This means that at the very lease (with default settings) your .zip file will be in some sub-directory of $(system.DefaultWorkingDirectory)/Build Artifact/

A new unique folder in the agent is created for every release pipeline when you initiate a release, and the artifacts are downloaded into that folder. The $(System.DefaultWorkingDirectory) variable maps to this folder.

To ensure the uniqueness of every artifact download, each artifact source linked to a release pipeline is automatically provided with a specific download location known as the source alias. This location can be accessed through the variable:
$(System.DefaultWorkingDirectory)\[source alias]
This uniqueness also ensures that, if you later rename a linked artifact source in its original location (for example, rename a build pipeline in Azure Pipelines or a project in Jenkins), you don't need to edit the task properties because the download location defined in the agent does not change.
The source alias is, by default, the name of the source selected when you linked the artifact source, prefixed with an underscore; depending on the type of the artifact source this will be the name of the build pipeline, job, project, or repository. You can edit the source alias from the artifacts tab of a release pipeline; for example, when you change the name of the build pipeline and you want to use a source alias that reflects the name of the build pipeline.

(from some of the abundant documentation
Instead of searching for your package using ***.zip (which isn't proper wildcard syntax) use Build Artifact/**/*.zip

*

*** is for recursively searching into directories

*

*(I don't know what folder)

** is for searching a part of a given level of the path

*

*any file/folder that

*

*starts with (SomeFile.*)

*ends with (*File.zip)

*and i think contains (*meFi*)

A: The pipeline YAML was missing the following tasks. Not sure why this isn't included in the ASP.NET Core template, very confusing for developers new to Azure DevOps.
- task: DotNetCoreCLI@2
  inputs:
    command: 'publish'
    publishWebProjects: true

- task: CopyFiles@2
  inputs:
    targetFolder: '$(Build.ArtifactStagingDirectory)'

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'drop'
    publishLocation: 'Container'

A: When adding an Artifact of Source type "Build", select "Default version" as "Latest from the build pipeline default branch with tags", as follows:


text:
Q: C# casting with generics that use interfaces I have some generic interfaces and classes that implement those intefaces like so:
    interface A<M, N>
        where M : X<N>
        where N : Y
    {
    }
    class B<M, N> : A<M, N>
        where M : X<N>
        where N : Y
    {

    }

    interface X<M> where M : Y
    {

    }
    interface Y
    {

    }
    class X1<M> : X<M> where M : Y
    {

    }
    class Y1 : Y
    {

    }

I know it seems like a very messy way of doing things, but I sort of need it for my application. My question is how come I can't do this:
A<X<Y>, Y> variable = new B<X1<Y1>, Y1>();

A: Variance needs to be explicit (and requires C# 4.0); for example, this makes it compile as covariant (note the out modifiers in the interface):
interface A<out M, out N>
    where M : X<N>
    where N : Y
{
}
interface X<out M> where M : Y
{

}

Note, however, that this also limits your interface to ... covariance! You couldn't have an Add(M) method, for example - as that would need to be contavariant (aka in).

A: Marc is right; just to give you some more background on why this cannot work. Consider the following re-naming of your code:
    interface IZoo<TCage, TAnimal>
        where TCage : ICage<TAnimal>
        where TAnimal : IAnimal
    {
    }

    class Zoo<TCage, TAnimal> : IZoo<TCage, TAnimal>
        where TCage : ICage<TAnimal>
        where TAnimal : IAnimal
    {
    }

    interface ICage<TAnimal> where TAnimal : IAnimal
    {
    }

    interface IAnimal
    {
    }

    class FishTank<TAnimal> : ICage<TAnimal> where TAnimal : IAnimal
    {
    }

    class Fish : IAnimal
    {
    }

And now your question is, why is this not legal:
Zoo<FishTank<Fish>, Fish> aquarium = new Zoo<FishTank<Fish>, Fish>();
IZoo<ICage<IAnimal>, IAnimal> zoo = aquarium;

?
Because suppose now there is a method on IZoo:
    interface IZoo<TCage, TAnimal>
        where TCage : ICage<TAnimal>
        where TAnimal : IAnimal
    {
        void PutAnimalInCage(TCage cage, TAnimal animal);
    }

And you then say:
zoo.PutAnimalInCage(giraffePaddock, giraffe);

And you just put a giraffe paddock into an aquarium! We cannot maintain type safety in a world where the conversion you want is legal and IZoo can have any method you choose on it.
Now, this is only dangerous because IZoo has such a method. If it doesn't have such a method then you are right, that could be perfectly safe. In C# 4.0 we added a feature to the language so that you can ask the compiler "check whether this interface can be made safely variant", by annotating the type parameters you want to be covariant with "out", and the ones you want to be contravariant with "in".  If you do that then the compiler will check for you whether the variance you want can be made to be typesafe.  If it cannot, then it will not allow the declaration of the type.
The way this question usually comes up on StackOverflow is people asking why is this illegal:
List<Giraffe> giraffes = new List<Giraffe>();
List<Mammal> mammals = giraffes; // illegal

Same reason. Because then nothing stops you from later
mammals.Add(new Tiger());

and you've just added a tiger to a list of giraffes.  Same reasoning, just a much simpler case.


text:
Q: Как получить размер char без 0? Не могу сообразить как получить размер массива char после ввода пользователем строчки. Хочется получить фактический размер того что введет пользователь и записать это в переменную
char data[50] = { 0 };
cout << "Введите строку: ";
cin >> data;

A: int len = strlen(data);

(Тело сообщения должно содержать не менее 30 символов; вы ввели 23.)


text:
Q: How can I call an array as a function? I have an array with hexadecimal values representing assembly instructions.
I want to push the HelloWorld array as parameter for printf.
Is (int)&HelloWorld the right way to get the address of my array or is there a better solution?
And how can I call Code[] as a function?
I tried with a function pointer but the program jumps somewhere else in memory and ends up crashing at an invalid instruction.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <errno.h>

int main()
{
    int HelloWorld[15] =
    {
        // Hello World
        0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x00
    };

    int Code[50] =
    {
        // PUSH [DWORD PTR] DS:<address of array HelloWorld>
        0xFF, 0x35, (int)&HelloWorld,
        // CALL <address of function printf>
        0xE8, (int)&printf,
        // ADD esp, 4
        0x83, 0xC4, 0x04,
        // RET
        0xC3
    };

    long unsigned int ProtectionCode = 0;

    // Change protection to read, write, execute
    int ChangeProtect = VirtualProtect(Code, 50, PAGE_EXECUTE_READWRITE,
                                       &ProtectionCode);

    if(ChangeProtect == 0)
    {
        printf("Error: %s\n", strerror(errno));
        return 1;
    }

    void (*CodePtr)() = &Code;
    (*CodePtr)();

    return 0;
}

Thanks for your help.

A: This version works fine on my windows:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <errno.h>

char HelloWorld[15] =
{
    // Hello World
    0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x00
};

void  __attribute__((used)) foo(void)
{
    int (*p)(const char *, ...) = printf;
    p(HelloWorld);
}

int main()
{

    unsigned char Code[] ={

        0x55,
        0x89, 0xe5,
        0x83, 0xec, 0x28,
        0xc7, 0x45,  0xf4,  0x78,  0x8c,  0x40, 0x00,
        0xc7, 0x04, 0x24, 0x04, 0xa0, 0x40, 0x00,
        0x8b, 0x45, 0xf4,
        0xff, 0xd0,
        0x90,
        0xc9,
        0xc3,
    };

    long unsigned int ProtectionCode = 0;

    // Change protection to read, write, execute
    int ChangeProtect = VirtualProtect(Code, 50, PAGE_EXECUTE_READWRITE,
                                       &ProtectionCode);

    if(ChangeProtect == 0)
    {
        printf("Error: %s\n", strerror(errno));
        return 1;
    }

    void (*CodePtr)() = &Code;
    (*CodePtr)();

    return 0;
}

the foo is just to take the code from :)


text: Q: Android - Stuck on create new application screen I cant go beyond the create new project screen, showing message of choose theme even when all possible theme options are selected. How to get along it and continue?


text:
Q: What is the difference between linear perceptron regression and LS linear regression? Recently, a project I'm involved in made use of a linear perceptron for multiple (21 predictor) regression. It used stochastic GD. How is this different from OLS linear regression?

A: scikit-learn's Perceptron class (equivalent to SGDClassifier(loss="perceptron", penalty=None, learning_rate="constant", eta0=1)) uses the following objective function:
$$\frac{1}{N} \sum_{i=1}^N \max(0, - y_i w^T x_i).$$
In this case, $y_i \in \{-1, 1\}$. If $w^T x_i$ has the right sign, it doesn't incur any loss; otherwise, it gives linear loss. The perceptron in particular uses a fixed learning rate which can lead to some optimization weirdness as well.
Least squares regression, by contrast, uses
$$\frac{1}{N} \sum_{i=1}^N (y_i - w^T x_i)^2.$$
Here $y_i$ can be any real; you can give it classification targets in $\{-1, 1\}$ if you want, but it's not going to give you a very good model.
You can optimize this with SGDRegressor(loss="squared_loss", penalty=None) if you'd like.
The two define fundamentally different models: the perceptron predicts a binary class label with $\mathrm{sign}(w^T x_i)$, whereas linear regression predicts a real value with $w^T x_i$. This answer talks some about why trying to solve a classification problem with a regression algorithm can be problematic.


text:
Q: USART not entering ISR STM32F030C8 I'm working on UART using interrupts on Stm32F030 controller.
I have done the following init.
void fnUart_Init(void)
{
 USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;

/* USART1 For Debug */
/* Enable GPIO clock */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA , ENABLE);
/* Enable USART clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

/* USART1 Pins configuration */

    GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_1);
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_1);

/* Configure pins as AF pushpull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);

/* USARTx configured as follow:
- BaudRate = 115200 baud
- Word Length = 8 Bits
- Stop Bit = 1 Stop Bit
- Parity = No Parity
- Hardware flow control disabled (RTS and CTS signals)
- Receive and transmit enabled
*/
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl =
USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);

/* NVIC configuration */
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);

USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
/* Enable USART */
USART_Cmd(USART1, ENABLE);
}

UART2 Init

 void fnUart2_Init(void)
{
 USART_InitTypeDef USART_InitStructure;
 NVIC_InitTypeDef NVIC_InitStructure;
 GPIO_InitTypeDef GPIO_InitStructure;

 /* USART1 For Debug */
 /* Enable GPIO clock */
 RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA , ENABLE);
/* Enable USART clock */
 RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);

 /* USART1 Pins configuration
 /* Connect pin to Periph */
 GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_1);
 GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_1);

 /* Configure pins as AF pushpull */
 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
 GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
 GPIO_Init(GPIOA, &GPIO_InitStructure);

 /* USARTx configured as follow:
 -  BaudRate = 115200 baud
 - Word Length = 8 Bits
 - Stop Bit = 1 Stop Bit
 - Parity = No Parity
 - Hardware flow control disabled (RTS and CTS signals)
 - Receive and transmit enabled
 */
  USART_InitStructure.USART_BaudRate = 115200;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl =
  USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_Init(USART2, &USART_InitStructure);

/* NVIC configuration */
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
 NVIC_Init(&NVIC_InitStructure);

USART_ITConfig(USART2,USART_IT_RXNE,ENABLE);
/* Enable USART */
USART_Cmd(USART2, ENABLE);
  }

The IrqHandler is as follows
void USART1_IRQHandler(void)
{
  printf("\n\r Inside ISR1");
}

I have the following printf function which prints data on UART2 when printf is called.
#define PUTCHAR_PROTOTYPE int std::fputc(int ch, FILE *f)
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the USART */
USART_SendData(USART2, (uint8_t) ch);

/* Loop until transmit data register is empty */
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET)
{}
return ch;
}

While loop has nothing running in it as of now.
Both the UART's are Initialized properly. This is verified by using  printf for both UART1 and UART2. Now wrote this minimal code to test the interrupts. I'm sending any data via UART1 via Realterm software and USB-TTL converter and checking on UART2 whether USART1_IRQHandler() is getting called or not. No response.
Also i was reading about the status and the interrupt flags. They are a bit confusing. When to use and clear those flags?
But first i'm not getting why the execution is not entering the ISR?
Did i miss something in the init?
I do not have a debugger with me so using breakpoints and checking the execution is not applicable in my case.
My goal is to send data received on UART1 to UART2 and data from UART2 to UART1.
I'm using the standard periph libraries and not HAL libraries.
Any suggestions?

A: I am strongly guessing it comes in the USART1_ISR just once,
you need to clear the relevant USART1 pending Receive not empty (RXNE) bit by calling this USART_ClearITPendingBit(USART1, USART_IT_RXNE); inside the ISR.


text:
Q: $_SERVER["REQUEST_URI"] with nginx proxy server --> get rewritten page urls I am using nginx as reverse proxy server (front-end server) + apache as back-end server.
I notice I could NOT get the rewritten url output in php (like www.example.com/something/page/) with $SERVER["HTTPHOST"].$SERVER["REQUESTURI"] in nginx but it works in apache.
Note: The nginx rewrite works fine in the url but the problem is the output in php code.
I am getting such un-rewritten urls like www.example.com/index.php?a=something&b=page with $SERVER["HTTPHOST"].$SERVER["REQUESTURI"]
Can someone please help if I am doing something wrong?
This is the proxy part of my nginx
location ~ \.php$ {
     proxy_pass http://127.0.0.1:8080;
     proxy_set_header Host $http_host;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header X-Forwarded-Proto $scheme;
}


text:
Q: Javascript tipping calculator I'm very new to Javascript, here's my problem
I can't seem to get the last two boxes right and sorry for my messed up coding as i said i'm still very new to this.

function FigureIt() {
  DinCost = document.tip.dinCost.value;
  Tip15 = (DinCost * .15)
  Tip25 = (DinCost * .25)
  Din15 = (DinCost * .15) + (DinCost)
  Din25 = (DinCost * .25) + (DinCost)

  document.tip.tip15.value = Tip15;
  document.tip.tip25.value = Tip25;
  document.tip.dinner15.value = Din15;
  document.tip.dinner25.value = Din25;
}
<form name="tip">
  How much did you pay for dinner?   $<input type="text" name="dinCost" id="dinCost">

  <input type="button" value="Calculate Tips" onclick="FigureIt()">

 Amount of 15% tip:   $<input type="text" name="tip15" id="tip15">
 Amount of 25% tip:   $<input type="text" name="tip25" id="tip25">

 Cost of dinner +
  15% tip:   <input type="text" name="dinner15" id="dinner15">
 Cost of dinner + 25% tip:   <input type="text" name="dinner25" id="dinner25">

  <input type="reset" value="Erase">
</form>

A: your input field has string value, you need numbers.
try this:

function FigureIt() {
 DinCost = parseFloat(document.tip.dinCost.value);
 Tip15 = (DinCost * .15)
 Tip25 = (DinCost * .25)
 Din15 = (DinCost * .15) + (DinCost)
 Din25 = (DinCost * .25) + (DinCost)

  document.tip.tip15.value = Tip15;
  document.tip.tip25.value = Tip25;
  document.tip.dinner15.value = Din15;
  document.tip.dinner25.value = Din25;
}
<form name="tip">
  How much did you pay for dinner?   $<input type="text" name="dinCost" id="dinCost">

  <input type="button" value="Calculate Tips" onclick="FigureIt()">

 Amount of 15% tip:   $<input type="text" name="tip15" id="tip15">
 Amount of 25% tip:   $<input type="text" name="tip25" id="tip25">

 Cost of dinner +
  15% tip:   <input type="text" name="dinner15" id="dinner15">
 Cost of dinner + 25% tip:   <input type="text" name="dinner25" id="dinner25">

  <input type="reset" value="Erase">
</form>

A: Convert your dinner cost input to a number:
DinCost = Number(document.tip.dinCost.value);


text:
Q: Java 1.7 HashMap Integer Key I'm using an HashMap<Integer, MyObject> collection to store a list of few couples of values.
Is it safe use Integer as key? the behavior is the same both on put and get method?

A: yes it's safe. Integer is just a wrapper class for int.
i know this from own experience. created a captcha functionality that way. (user requests a random integer. my prog creates a captcha-pic and saves the answer[value] and random integer id[key] in a hashmap. btw if you want to create a "cache" use java's LinkedHashMap. it has a protected boolean method called "removeEldestEntry(Map.Entry eldest)" which is called during a put-event. if you override it with, eg "return size() > MAX_SIZE;" it will delete the oldest entry (or the entry based on oldest access - there's an option in the constructor) if the condition you provided returns true). hope this helped. :/


text:
Q: Samsung Health : solving java.lang.IllegalArgumentException: heart_rate (READ) is invalid what I want to do is developing an app that reads health data that collected by Samsung watch so I tried to use Samsung android health SDK . Moreover reading steps was very easy as there was a sample app doing the same thing . the issue appear when I was trying to read the heart rate value :
here is my code please help me address the issue :
Mainfest :
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.smaunghealth">
    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">

        <meta-data android:name="com.samsung.android.health.permission.read"
                   android:value="com.samsung.health.step_count;com.samsung.health.heart_rate"/>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity
package com.example.smaunghealth;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.samsung.android.sdk.healthdata.*;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    public static final String APP_TAG = "SimpleHealth";

    private static MainActivity mInstance = null;
    private HealthDataStore mStore;
    private HealthConnectionErrorResult mConnError;
    private Set<HealthPermissionManager.PermissionKey> mKeySet;
    private StepCountReporter mReporter;
    private HeartRateReporter mHeartReporter;

    TextView stepCount ;
    TextView heartRate ;

    private final HealthResultHolder.ResultListener<HealthPermissionManager.PermissionResult> mPermissionListener =
            new HealthResultHolder.ResultListener<HealthPermissionManager.PermissionResult>() {

                @Override
                public void onResult(HealthPermissionManager.PermissionResult result) {
                    Log.d(APP_TAG, "Permission callback is received.");
                    Map<HealthPermissionManager.PermissionKey, Boolean> resultMap = result.getResultMap();

                    if (resultMap.containsValue(Boolean.FALSE)) {
                        // Requesting permission fails
                    } else {
                        // Get the current step count and display it
                    }
                }
            };

    private final HealthDataStore.ConnectionListener mConnectionListener = new HealthDataStore.ConnectionListener() {

        @Override
        public void onConnected() {
            Log.d(APP_TAG, "Health data service is connected.");
            HealthPermissionManager pmsManager = new HealthPermissionManager(mStore);

            try {
                // Check whether the permissions that this application needs are acquired
                Map<HealthPermissionManager.PermissionKey, Boolean> resultMap = pmsManager.isPermissionAcquired(mKeySet);

                if (resultMap.containsValue(Boolean.FALSE)) {
                    // Request the permission for reading step counts if it is not acquired
                    pmsManager.requestPermissions(mKeySet, MainActivity.this).setResultListener(mPermissionListener);
                } else {
                    // Get the current step count and display it
                    // ...

                    mReporter = new StepCountReporter(mStore);
                    mReporter.start(mStepCountObserver);

                    mHeartReporter = new HeartRateReporter(mStore);
                    mHeartReporter.start(heartRateObserver);
                }
            } catch (Exception e) {
                Log.e(APP_TAG, e.getClass().getName() + " - " + e.getMessage());
                Log.e(APP_TAG, "Permission setting fails.");
            }
        }

        @Override
        public void onConnectionFailed(HealthConnectionErrorResult error) {
            Log.d(APP_TAG, "Health data service is not available.");
            showConnectionFailureDialog(error);
        }

        @Override
        public void onDisconnected() {
            Log.d(APP_TAG, "Health data service is disconnected.");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mInstance = this;

        stepCount= (TextView) findViewById(R.id.step_count);
        heartRate= (TextView) findViewById(R.id.heart_rate);

        mKeySet = new HashSet<HealthPermissionManager.PermissionKey>();
//        mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, HealthPermissionManager.PermissionType.READ));
        mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.HeartRate.HEART_RATE, HealthPermissionManager.PermissionType.READ));

        HealthDataService healthDataService = new HealthDataService();
        try {
            healthDataService.initialize(this);
        } catch (Exception e) {
            e.printStackTrace();}

        mStore = new HealthDataStore(this, mConnectionListener);
        // Request the connection to the health data store
        mStore.connectService();
    }

    @Override
    public void onDestroy() {
        mStore.disconnectService();
        super.onDestroy();
    }

    private StepCountReporter.StepCountObserver mStepCountObserver = count -> {
        Log.d(APP_TAG, "Step reported : " + count);
        updateStepCountView(String.valueOf(count));
    };

    private HeartRateReporter.HeartRateObserver  heartRateObserver = count -> {
        Log.d(APP_TAG, "Step reported : " + count);
        updateHeartRateView(String.valueOf(count));
    };

    private void updateHeartRateView(String valueOf) {
        Log.d(APP_TAG, "heart rate reported : " + valueOf);
        updateHeartRateView(String.valueOf(valueOf));
    }

    private void updateStepCountView(String count) {
        stepCount.setText(count);

    }

    private void showConnectionFailureDialog(HealthConnectionErrorResult error) {

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        mConnError = error;
        String message = "Connection with Samsung Health is not available";

        if (mConnError.hasResolution()) {
            switch(error.getErrorCode()) {
                case HealthConnectionErrorResult.PLATFORM_NOT_INSTALLED:
                    message = "Please install Samsung Health";
                    break;
                case HealthConnectionErrorResult.OLD_VERSION_PLATFORM:
                    message = "Please upgrade Samsung Health";
                    break;
                case HealthConnectionErrorResult.PLATFORM_DISABLED:
                    message = "Please enable Samsung Health";
                    break;
                case HealthConnectionErrorResult.USER_AGREEMENT_NEEDED:
                    message = "Please agree with Samsung Health policy";
                    break;
                default:
                    message = "Please make Samsung Health available";
                    break;
            }
        }

        alert.setMessage(message);

        alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                if (mConnError.hasResolution()) {
                    mConnError.resolve(mInstance);
                }
            }
        });

        if (error.hasResolution()) {
            alert.setNegativeButton("Cancel", null);
        }

        alert.show();
    }
}

HeartRateReporter
package com.example.smaunghealth;

import android.util.Log;
import com.samsung.android.sdk.healthdata.*;

import java.util.Calendar;
import java.util.TimeZone;

public class HeartRateReporter {

    private final HealthDataStore mStore;
    private HeartRateObserver mHeartRateObserver;
    private static final long ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000L;

    public HeartRateReporter(HealthDataStore store) {
        mStore = store;
    }

    public void start(HeartRateObserver listener) {
        mHeartRateObserver = listener;
        HealthDataObserver.addObserver(mStore, HealthConstants.HeartRate.HEART_RATE, mObserver);
        readHeartRate();
    }

    private void readHeartRate() {
        HealthDataResolver resolver = new HealthDataResolver(mStore, null);

        // Set time range from start time of today to the current time
        long startTime = getStartTimeOfToday();
        long endTime = startTime + ONE_DAY_IN_MILLIS;

        HealthDataResolver.ReadRequest request = new HealthDataResolver.ReadRequest.Builder()
                .setDataType(HealthConstants.HeartRate.HEART_RATE)
                .setProperties(new String[] {HealthConstants.HeartRate.HEART_RATE})
                .setLocalTimeRange(HealthConstants.HeartRate.START_TIME, HealthConstants.HeartRate.TIME_OFFSET,
                        startTime, endTime)
                .build();

        try {
            resolver.read(request).setResultListener(mListener);
        } catch (Exception e) {
            Log.e("*&*&*&", "Getting Heart fails.", e);
        }
    }

    private long getStartTimeOfToday() {
        Calendar today = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        today.set(Calendar.MILLISECOND, 0);

        return today.getTimeInMillis();
    }

    private final HealthResultHolder.ResultListener<HealthDataResolver.ReadResult> mListener = result -> {
        int count = 0;

        try {
            for (HealthData data : result) {
                count += data.getInt(HealthConstants.HeartRate.HEART_RATE);
            }
        } finally {
            result.close();
        }

        if (mHeartRateObserver != null) {
            mHeartRateObserver.onChanged(count);
        }
    };

    private final HealthDataObserver mObserver = new HealthDataObserver(null) {

        @Override
        public void onChange(String dataTypeName) {
            Log.d("*&*&*&", "Observer receives a data changed event");
            readHeartRate();
        }
    };

    public interface HeartRateObserver {
        void onChanged(int count);
    }
}

StepCountReporter
/**
 * Copyright (C) 2014 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Mobile Communication Division,
 * Digital Media & Communications Business, Samsung Electronics Co., Ltd.
 *
 * This software and its documentation are confidential and proprietary
 * information of Samsung Electronics Co., Ltd.  No part of the software and
 * documents may be copied, reproduced, transmitted, translated, or reduced to
 * any electronic medium or machine-readable form without the prior written
 * consent of Samsung Electronics.
 *
 * Samsung Electronics makes no representations with respect to the contents,
 * and assumes no responsibility for any errors that might appear in the
 * software and documents. This publication and the contents hereof are subject
 * to change without notice.
 */

package com.example.smaunghealth;

import android.util.Log;
import com.samsung.android.sdk.healthdata.*;
import com.samsung.android.sdk.healthdata.HealthDataResolver.ReadRequest;
import com.samsung.android.sdk.healthdata.HealthDataResolver.ReadResult;

import java.util.Calendar;
import java.util.TimeZone;

public class StepCountReporter {

    private final HealthDataStore mStore;
    private StepCountObserver mStepCountObserver;
    private static final long ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000L;

    public StepCountReporter(HealthDataStore store) {
        mStore = store;
    }

    public void start(StepCountObserver listener) {
        mStepCountObserver = listener;
        // Register an observer to listen changes of step count and get today step count
        HealthDataObserver.addObserver(mStore, HealthConstants.StepCount.HEALTH_DATA_TYPE, mObserver);
        readTodayStepCount();
    }

    // Read the today's step count on demand
    private void readTodayStepCount() {
        HealthDataResolver resolver = new HealthDataResolver(mStore, null);

        // Set time range from start time of today to the current time
        long startTime = getStartTimeOfToday();
        long endTime = startTime + ONE_DAY_IN_MILLIS;

        HealthDataResolver.ReadRequest request = new ReadRequest.Builder()
                    .setDataType(HealthConstants.StepCount.HEALTH_DATA_TYPE)
                    .setProperties(new String[] {HealthConstants.StepCount.COUNT})
                    .setLocalTimeRange(HealthConstants.StepCount.START_TIME, HealthConstants.StepCount.TIME_OFFSET,
                            startTime, endTime)
                    .build();

        try {
            resolver.read(request).setResultListener(mListener);
        } catch (Exception e) {
            Log.e(MainActivity.APP_TAG, "Getting step count fails.", e);
        }
    }

    private long getStartTimeOfToday() {
        Calendar today = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        today.set(Calendar.MILLISECOND, 0);

        return today.getTimeInMillis();
    }

    private final HealthResultHolder.ResultListener<ReadResult> mListener = result -> {
        int count = 0;

        try {
            for (HealthData data : result) {
                count += data.getInt(HealthConstants.StepCount.COUNT);
            }
        } finally {
            result.close();
        }

        if (mStepCountObserver != null) {
            mStepCountObserver.onChanged(count);
        }
    };

    private final HealthDataObserver mObserver = new HealthDataObserver(null) {

        // Update the step count when a change event is received
        @Override
        public void onChange(String dataTypeName) {
            Log.d(MainActivity.APP_TAG, "Observer receives a data changed event");
            readTodayStepCount();
        }
    };

    public interface StepCountObserver {
        void onChanged(int count);
    }
}

Here is the exception log :

A:         <meta-data android:name="com.samsung.android.health.permission.read"
               android:value="com.samsung.health.step_count;com.samsung.health.heart_rate"/>

I think you should separate this permission into two, not only one。
like:
        <meta-data android:name="com.samsung.android.health.permission.read"
               android:value="com.samsung.health.step_count"/>
         <meta-data android:name="com.samsung.android.health.permission.read"
               android:value="com.samsung.health.heart_rate"/>

A: After long time finally I was able to address the issue :
mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, HealthPermissionManager.PermissionType.READ));
        mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.HeartRate.HEART_RATE, HealthPermissionManager.PermissionType.READ));

this is the write permissionKey :
mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, HealthPermissionManager.PermissionType.READ));
    mKeySet.add(new HealthPermissionManager.PermissionKey(HealthConstants.HeartRate.HEALTH_DATA_TYPE, HealthPermissionManager.PermissionType.READ));


text:
Q: Convert the time to the suitable format using Pandas I have a file whose name is "MCD43A3_Alb_QA_SWIR_2020_061.tif", and I want to split the time "2020_061" and convert to the format "2020-03-01", how can I do that?
Here is my code:
def get_image_time(file_single):

    img_time_day_raw = os.path.basename(file_single).split("_")[5]
    img_time_day = img_time_day_raw.split(".")[0]
    img_time_year = os.path.basename(file_single).split("_")[4]
    img_time_str = img_time_year + "03" +img_time_day
    img_time_pd = pandas.to_datetime(img_time_str, format ='%Y/%m/%d)
    return(img_time_pd)

A: (Your questions is better suited for stackoverflow.com)
But try using pd.to_datetime and pd.DateOffset:
import pandas as pd
import os

filename = r'/home/bera/Downloads/MCD43A3_Alb_QA_SWIR_2020_061.tif'

def fixdate(full_path_and_filename):
    d = os.path.splitext(full_path_and_filename)[0].split('_')[-2:] #['2020', '061']
    d = pd.to_datetime(d[0], format='%Y') + pd.DateOffset(days=int(d[1])-1)
    return d.strftime('%Y-%m-%d')

#fixdate(filename)
#Out[41]: '2020-03-01'


text:
Q: How can I get an xmlnode from xmlnodereader I'm reading the icecat sheets as one giant xml document (1.7g) and i'm using xmlnodereader.
How do I read it node by node. I know, normally, you wouldn't do this but the structure looks like
<file attr=value>...</file>

<file attr=value>...</file>

<file attr=value>...</file>

<file attr=value>...</file>

<file attr=value>...</file>

here is some existing code for reference:
 foreach (BackgroundWorker worker in Pool)
            {
                if (worker.IsBusy)
                    continue;
                //read xmlnode and pass it to the worker

            }

A: I would suggest using LINQ to XML if you can. You can use:
XElement element = XElement.Load(reader);

which will just load a single element from the reader, advancing it appropriate. It's really easy to do, and the LINQ to XML API is much nicer than the old DOM API.


text:
Q: Trying to add the exchnage api to my project I would like to use the open source EXchange api ( a Maven project)
   https://github.com/timmolter/XChange in my project. to talk to bit coin exchnages on a project i'm working on
I followed the steps at getting started https://github.com/timmolter/XChange/wiki/Getting-Started-with-XChange-for-Noobies
This created about 20 projects. It has a project called
exchange-examples where I was able to put in my own class and write code to talk to the Exchange API
I have a project Iv been working on and would like to be able to have the exchnage api in it.  I was assumming I would have to add all the jar files that the exchnage-example project has to my my project,
When I looked at the exchnage-example project java build path for Libraies it had a folder called Maven Dependecies.
I'm assuming all the jar files under that folder I would add to my project??
in the listing of libraies some lines that did not have the name of a jar file, but just a file path. ( xchange-core ) when I clicked on it I would get
    is not module
     access rules-no rules defined
     native libary location -non
I dont know how to add that to my new peoject.

A: To get everything with a Maven project, your pom.xml should include this and will automatically handle the dependencies.  If you want to use the JARs or just drag the packages into your src folder, you will have to download all of the dependencies yourself.  I would only recommend doing this after you have experimented with XChange via Maven first.
<dependencies>

    <dependency>
        <groupId>org.knowm.xchange</groupId>
        <artifactId>xchange-core</artifactId>
        <version>4.3.4</version>
    </dependency>

    <dependency>
        <groupId>org.knowm.xchange</groupId>
        <artifactId>xchange-bittrex</artifactId>
        <version>4.3.4</version>
    </dependency>

    <dependency>
        <groupId>org.knowm.xchange</groupId>
        <artifactId>xchange-bitfinex</artifactId>
        <version>4.3.4</version>
    </dependency>

</dependencies>

The first one (xchange-core) is required, and then you have to add another dependency for each exchange you wish to use.


text:
Q: Parallax Split screen with alternating scroll sides I am looking to create a simple parallax split screen site that allows me to once a new screen is loaded alternate the scrolling. For example, If I scroll down and the content on the left and right appear I want to then lock the right side and have scrolling only happen on the left until that content is finished.
So it should start like this:
http://alvarotrigo.com/blog/multiscroll-js-jquery-plugin-to-create-multi-scrolling-sites-with-two-vertical-layouts/
but once the section loads in I need just the left scrollable like this:
http://www.themealings.com.au/leesa/portfolio/nick-jr-parents-blog/
Once the left side content is complete I want to present a new section.  Any ideas on how this can happen? What is the best JS library to achieve this?

A: There are several plug-ins that can accomplish this quite easily.
Give this a shot -----> http://viget.com/inspire/jquery-stick-em
Demo here: -----> http://davist11.github.io/jQuery-Stickem/
I am currently using this hard code to accomplish something similar, so this might be of use as well:
    var $window = $(window),
    $mainMenuBar = $('#fixed-div'), //This div will scroll until top
    $menuBarOffset = $mainMenuBar.offset().top,
    window_top = 0,
    footer_offset = $("#end-div").offset().top, //this div tells #fixed-div when to start scrolling
    content = $("#unaffected-div"), //This div scrolls like normal
    panel_height = $mainMenuBar.outerHeight()+'px';

$window.scroll(function() {
    window_top = $window.scrollTop();

    if (window_top >= $menuBarOffset) {
        if (window_top >= footer_offset) {
            $mainMenuBar.removeClass('stick');
            content.css('margin-top', 0);
        } else {
            $mainMenuBar.addClass('stick');
            content.css('margin-top', panel_height);
        }
    }
    else {
        $mainMenuBar.removeClass('stick');
        content.css('margin-top', 0);
    }
});

You will also need to add this element to your .css file
.stick {
position: fixed;
top: 0;
}


text:
Q: Bing Ads PHP Example I'm using the Bing Ads php code for downloading Keyword Performance Reports. Here:
http://msdn.microsoft.com/en-us/library/bing-ads-reporting-request-and-download-a-keyword-performance-report-in-php.aspx
Is there any way i can specify multiple CampaignID's in my Keyword Performance Report? As of now, i'm only able to download reports for a single CampaignID and as you can imagine, this is really inefficient since i have more than 10 Campaigns. Any help would be greatly appreciated.

A: Instead of
 $report->Scope->Campaigns = array ();

Just have the line below and it will pull all campaigns. It only pulls on campaign level if they are specified.
$report->Scope->Campaigns = null;


text:
Q: echo json data then sleep In my php script I want to output data to the browser then sleep() for 2 seconds before running a function. The below doesnt seem to output the json before sleeping, anyone got any ideas?
if ($_POST['process'] == '1') {
    // adding stuff to $data here
    }

    echo json_encode($data);
    ob_flush();
    flush();
    sleep(2);
    // Do something else
}

A: Yep, this is how you do it. Basically, you close the connection and return the response to the user while apache continues to process the file...
ignore_user_abort(true);
header('Content-Type: application/json');
header('Connection: close');
header('Content-Length: ' . strlen($YOUR_JSON_RESPONSE));

echo $YOUR_JSON_RESPONSE;
flush();

sleep(2);
your_cool_function_to_run();
die();

Works great for quick ajax calls that need an immediate response and/or take a long time to actually do the work.
I must warn you to use this type of thing sparingly... Each time this happens a new process/thread is opened up to handle the remainder of your request. Do too many too fast and you'll run out of processes. (Depending on your setup)

A: You could try closing STDOUT, to signal to the web server that your script is done sending data to the HTTP client.
fclose( STDOUT);


text:
Q: ViewPager2 переменная на все фрагменты с помощью ViewPager2 вывожу на экран слайдер из нескольких разных фрагментов (точное количество их заранее не известно).
В первом фрагменте мне нужно в переменную внести значение. В остальных фрагментах нужен доступ к значению этой переменной.
Подскажите можно ли как-то объявить такую переменную. Пробовал объявить в FragmentStateAdapter  public Integer ExcelDocID=0;, но в самих фрагментах она не видна. Или нужно смотреть в сторону передачи параметров между фрагментами?
                       ViewPager2 pager = findViewById(R.id.ExcelViewPager2);
                        FragmentStateAdapter pageAdapter = new ZZMyAdapter(this);
                        pager.setAdapter(pageAdapter);
                    }
                }
           }

    private class ZZMyAdapter extends FragmentStateAdapter {
       // public Integer ExcelDocID=0;
public ZZMyAdapter(FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }
        @NonNull
        @Override
        public Fragment createFragment(int position) {
            if (position==0) {
                FragmentExcelDoctor ffff1 = new FragmentExcelDoctor();
                Bundle args = new Bundle();
                String[] row=rowList.get(position);
                args.putString("param1", row[0].trim());
                ffff1.setArguments(args);
                return ffff1;
            }else
            if (position>0&&position<PAGE_COUNT) {
                String[] row=rowList.get(position);
                FragmentExcelPacient ffff2 = new FragmentExcelPacient();
                Bundle args = new Bundle();
                args.putString("param1", row[0]);
                args.putString("param2", row[1]);
                args.putString("param3", row[2]);
                args.putString("param4", row[3]);
                args.putString("param5", row[4]);
                ffff2.setArguments(args);
                return ffff2;
            }else return null;
        }
       @Override
        public int getItemCount() {
            return PAGE_COUNT;
        }
    }


text:
Q: Mac dual boot fail to read ubuntu12.10 usb stick I have a late 2011 macbook pro.
Partitioned off 40 gigs using the disk utility app.
I have the rEFInd Boot manager correctly installed.
Followed ubuntu's usb stick disk image instructions.
Checked the image using md5sum and got the correct hash back, the ubuntu-12.10-desktop-amd64.iso.
When I restart, it brings me to rEFInd's menu. There's a grub and a root usb stick options as well as the osx partition and the empty partition intended for ubuntu. If I go to the empty partition, there are doubles of the root and grub options.
They all bring me to a same grub screen. When I try any of the options my screen goes black. When I'm trying the "install ubuntu" option, I hear the chime after ~20 seconds, but then the screen continues to go black.
Considering that it was a graphics issue, I changed my resolution to 800x600 while in osx then restarted, I'm not sure if those settings would carry over as rEFInd seems to default to the highest resolution possible (1680x1050).
Any theories or tips? Thanks in advance.

A: AFAIK, Macs can't boot from USB sticks.
you should try burning an .ISO to a DVD, you can find instructions at: http://www.ubuntu.com/download/help/burn-a-dvd-on-mac-osx.
Hope this helped, it worked for me!


text:
Q: Question re: Collatz Conjecture Disclaimer: I'm not a mathematician and for the most part I do not understand what, exactly, it takes to mathematically prove anything. That is where this question comes from.
Why can't the Collatz Conjecture be proven by showing that all even numbers less than 11 do "resolve" (via the collatz division and multiplication) to 1. From there, couldn't it be shown that all even numbers have a multiple factor that is less than 10, thus proving the case for starting with an even number? Which just leaves the odd-numbered case. But for odd numbers, mulitplying by 3 and adding one always results in an even number, which can be proven to resolve to 1 via the even numbered part of the proof.
Obviously I'm missing something but i don't have the words and labels to say what it is to investigate further.
I apologize in advance if this question doesn't belong on this SE and thank you in advance for any insight.
EDIT: I haven't actually thought about this in a little while before writing it up here and have obviously goofed in a couple of spots.
One thing to correct is that every even number has a factor that is of the form 2^x and that any number 2^x resolves to 1 in a straight line.

A: If we knew that every Collatz orbit eventually hits a number less than $10$ (is that what you mean?) then we'd be done immediately. So we don't know that! More generally if we knew that every Collatz orbit eventually hits a number less than $N$ for any $N$ then we'd have reduced the Collatz conjecture to checking $N$ cases, and we'd be done as long as $N$ was not enormous; apparently the conjecture has been verified up to $N = 2^{68}$ or so. We don't know this either! This is the entire difficulty of the problem.
In other words, despite having verified the conjecture up to $N = 2^{68}$, for all we know it's possible that some extremely large number has a Collatz orbit that never dips below, say, $2^{100}$, and so would be a counterexample we haven't tested computationally yet.


text:
Q: Google maps Api 3 symbols I would like to display on google maps a marker for my current position that I can rotate depending on the user's heading.
Currently only symbols can be attached to a marker and rotated (more here https://developers.google.com/maps/documentation/javascript/symbols).
My challenge is that I want to use a custom symbol that looks like this (https://drive.google.com/file/d/0B5UD8mTDFqP7UHZ6bGpMeGpFR1U/edit?usp=sharing).
My problem is that the SVG file uses to define the shape a PATH and CIRCLE, but google API supports only path.
This is the SVG markup:
<g>
    <g>
    <path fill-rule="evenodd" clip-rule="evenodd" fill="#ED6C61" d="M8.234,17.247c- .68,0-3.28-0.336-4.744-0.938c1.975,2.701,3.938,4.688,4.744,4.688s2.77-1.986,4.745-4.688C11.516,16.911,9.915,17.247,8.234,17.247z"/>
    </g>
     </g>
    <circle fill="#ED6C61" cx="8.235" cy="8.235" r="8.235"/>
How do I obtain this shape by only using the path?
Thanks

A: Create a single path of both objects.
Workflow(using inkscape):

*

*open the SVG

*select the circle

*convert the circle into a path:
CTRL+SHIFT+C (or menu->path->object to path)

*select both pathes:
CTRL+A

*combine the pathes:
CTRL+K (or menu->path->combine)

Result:
 m 16.469999,8.2349997 c 0,4.5480643 -3.686935,8.2349993 -8.2349993,8.2349993 C 3.6869349,16.469999 0,12.783064 0,8.2349997 0,3.6869349 3.6869349,0 8.2349997,0 12.783064,0 16.469999,3.6869349 16.469999,8.2349997 z M 8.234,17.247 c -1.68,0 -3.28,-0.336 -4.744,-0.938 1.975,2.701 3.938,4.688 4.744,4.688 0.806,0 2.77,-1.986 4.745,-4.688 -1.463,0.602 -3.064,0.938 -4.745,0.938 z

Demo: http://jsfiddle.net/doktormolle/LLH5s/


text:
Q: Calculate regular values Question: The set in $\mathbb R^3$ of solutions of the equation  $z^2=x^2 + y^2$ is the inverse image of a regular value of a function.
My attempt,I thought about taking a function, $f:\mathbb R^3 \to \mathbb R$ such that $f(x,y,z)= x^2 + y^2 -z^2 +1 $.But this is not valid becouse $1$ is not a regular value,to get $f^{-1}(1)=\{z^2=x^2 + y^2\}$ .Could someone give me and idea , please.


text:
Q: TypeError: can't multiply sequence by non-int of type 'float' error I've tried everything Asking for total price, tax and tip. Then adding each other and giving the total price.
from time import sleep
def getprice():
    return input("What's the price of your bill?").lower()

price = getprice()

def gettax():
    return input("What's the restaurant's tax percent?").lower()

tax = gettax()

def gettip():
    return input("How much tip do you want to leave?")

tip = gettip()

percentage = float(tax)/100
total= price*percentage + price + tip

print(total)

It's giving me and error on the total= row, I read many articles but I can't fix it can anyone help me ?

A: The input read is a string, that is a sequence, not multipliable by a float.
int(price)

Solves it.

A: Python3 input function returns a string.
You have tried  float * string + string + string
total= price*percentage + price + tip

TypeError: unsupported operand type(s) for +: 'float' and 'str'

You can fix like this,
from time import sleep
def getprice():
    return float(input("What's the price of your bill?").lower())

price = getprice()

def gettax():
    return float(input("What's the restaurant's tax percent?").lower())

tax = gettax()

def gettip():
    return float(input("How much tip do you want to leave?"))

tip = gettip()

percentage = tax / 100
total= price*percentage + price + tip

print(total)


text:
Q: How to log X-Amzn-Request-id when invoking a lambda? (aws-sdk) I see that when we invoke a lambda, there is an x-amzn-request-id for that execution:
  "resourceType": "lambda",
  "resource": "invoke",
  "output": {
    "ExecutedVersion": "$LATEST",
    "Payload": {
      "recordsReady": false
    },
    "SdkHttpMetadata": {
      "AllHttpHeaders": {
        "X-Amz-Executed-Version": [
          "$LATEST"
        ],
        "x-amzn-Remapped-Content-Length": [
          "0"
        ],
        "Connection": [
          "keep-alive"
        ],
        "x-amzn-RequestId": [ <-------------------
          "0b1198a6-2ed8-485b-b5f6-6c086ff192a1"
        ],

How would we log out that request id from the lambda using aws-sdk? Is it even possible?

A: context object has a couple of useful properties. One of the mis 'aws_request_id' (for python, but other sdks have it too): https://docs.aws.amazon.com/lambda/latest/dg/python-context.html
That's supposed to give you the request id for the invocation request. I would check that and log it out. E.g.:
def lambda_handler(event, context):
    print(context.aws_request_id)

A: you could do this in JS either by

*

*using context object, which is the most common way. context is passed as the second argument in the handler function:

    exports.handler = (event, context, callback) => {
        console.log(`X-Amzn-Request-Id: ${context.awsRequestId}`);
        ...
    }

*

*using process.env
exports.handler = (event, context, callback) => {
    console.log("X-Amzn-Request-Id: " + process.env.AWS_REQUEST_ID);
    // rest of your code
}


text:
Q: create conda environment from an existing interpreter Is it possible to use conda to manage the environment from an existing python installation? I want to use conda with python that comes with an app (the foudry's nuke). The app has a custom python with a bunch of libraries and dlls (precompiled pyside etc) and I would like to copy it as a conda environment to have better control over the packages, and be able to mix it with other python installations (managed by conda).
Ideally, I would love to be able to start a shell with a working python environment and make a conda "snapshot" of it.
From what I googled and tested so far I don't think it is possible but maybe I missed something and there is some half manual way to do it.


text:
Q: Energy integral: how does $p∇^2 p$ become $∇(p∇p)−(∇p)^2$ Given the energy integral:
$E(u) = \frac{1}{2}\int_V (e_t^2) dV$
$e_t = \nabla \cdot(D \nabla e)$
Differentiating this integral w.r.t. time yields the below:
$
 \frac{dE}{dt} = \int_V ee_t dV = \int_V e \nabla \cdot(D\nabla e) dV = \int_V \nabla \cdot(e D\nabla e) dV - \int_V \nabla e \cdot( D\nabla e) dV
$
I don't understand the relation on both sides of the last equal sign on the last line: in other words how does the following general relation hold:
$p \nabla ^2 p  = \nabla (p \nabla p) - (\nabla p)^2$

A: Hint: $$\nabla (fg)=f\nabla g+g\nabla f$$

A: The last equal sign is just the product rule, we have
$$ \def\div{\mathop{\rm div}}\def\grad{\mathop{\rm grad}}\div (eD\grad e)
  = e \div(D\grad e) + \grad e \cdot D\grad e
$$
hence
$$ e\div(D \grad e) = \div(eD\grad e) - \grad e \cdot D \grad e $$

Addendum: For the simplified version with $p$, it's the same, we have
$$ \div(p \grad p) = \grad p \cdot \grad p + p \div\grad p \iff p \div\grad p = \div(p\grad p) - \grad p \cdot \grad p $$


text:
Q: how to import colors in variables.scss ionic2/3 : how to import colors in variables.scss. I have a scss file with some colors; how I can import and use them in variables.scss in ionic angular?
$colors: (
  carscolor:  #C5281C,
  primary:    #387ef5,
  secondary:  #32db64,
  danger:     #f53d3d,
  light:      #f4f4f4,
  dark:       #000,
  popover:    #404040,
  unread:       #808080,
  note:         #666,
  );

A: You need to call your _extra.scss file and import it like this in the beginning of variables.scss:
@import 'extra';


text:
Q: Jupyter notebook slideshow - removing white space on sides I converted my jupyter notebook to slideshow using this command:
jupyter nbconvert Jupyter\ "test.ipynb" --to slides --reveal-prefix "https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.1.0"

Now, I have an html slide file that I can see my slides. How can I remove/reduce white borders on the right and left side of the each slide?
My problem is different from increasing the cell width of the Jupyter/ipython notebook How do I increase the cell width of the Jupyter/ipython notebook in my browser?
I searched a lot and was not able to find an answer to this issue.  I appreciate any help.

A: Add a custom.css file to the same folder you are running the command in and have the contents be something like:
.slides {
  width: 90% !important;
}

Be careful with tweaking too many styles and setting !important flags, as you can quickly get unexpected behavior elsewhere in the converted notebook.


text:
Q: Firebase Functions AppCheck keeps failing my device I have been trying to integrate AppCheck with my Android app, but I can't seem to make a valid request.
As for test purposes, I have been using the following code:
Android Code
class Application : MultiDexApplication() {

    override fun onCreate() {
        FirebaseApp.initializeApp(this)

        val appCheck = FirebaseAppCheck.getInstance()
        if (BuildConfig.DEBUG) appCheck.installAppCheckProviderFactory(DebugAppCheckProviderFactory.getInstance(), true)
        else appCheck.installAppCheckProviderFactory(SafetyNetAppCheckProviderFactory.getInstance(), true)

        super.onCreate()
    }
}

class TestActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        val data = "This is a test!"
        Firebase.functions.getHttpsCallable("test").call(data).addOnCompleteListener {
            if (it.isSuccessful) {
                val result = it.result.data
                print(result)
            }

            else {
                val exception = it.exception
                print(exception)
            }
        }
    }
}

Function Code
const functions = require("firebase-functions")

exports.test = functions.https.onCall((data, context) => {
  if (context.app == undefined) {
    functions.logger.error("Test - Failed validating device integrity!")
    throw new functions.https.HttpsError("failed-precondition", "The function must be called from an App Check verified app")
  }

  return data
})

I have added the DebugAppCheckProviderFactory token to the Firebase console, but no matter what I do, if it is an emulator or physical device, when I call the function, the failed-precondition exception is always thrown.
Checking the function logs, I can see that the app is missing:

I have already read the documentation multiple times and I can't seem to be missing any step. Am I missing something or is there anything I can do to find the root cause for this?
Thank you for your time!
EDIT:
As for Martin suggestion, I created a new OnRequest function and added the X-Firebase-AppCheck header. I received the token correctly and was able to validate it successfully with:
firebaseAdmin.appCheck().verifyToken(appCheckToken)
So, my guess is that Android is not adding the X-Firebase-AppCheck automatically to the OnCall function like it should.
I ran the code and made some breakpoints through the code and noticed the following. The call method from Firebase is adding the Firebase-Instance-ID-Token but I can't seem to find the X-Firebase-AppCheck header anywhere. Maybe I am not supposed to see this value, or maybe I just can't find where it is being added. Or maybe it is not added at all, thus I can't validate my context.app at all.

A: It may be required to obtain an AppCheckToken:
FirebaseAppCheck
        .getInstance()
        .getAppCheckToken(false)
        .addOnSuccessListener(new OnSuccessListener<AppCheckToken>() {
            @Override
            public void onSuccess(@NonNull AppCheckToken tokenResponse) {

                String appCheckToken = tokenResponse.getToken();
                ...
            }
        });

Which has to be passed along, with the HTTP request (the example shows Retrofit, which could also be used instead of HttpsCallable:
@GET("yourExampleEndpoint")
Call<List<String>> exampleData(
    @Header("X-Firebase-AppCheck") String appCheckToken,
    ...
);

Where FirebaseFunctions.getInstance().getHttpsCallable().call() doesn't tell how or if one has to explicitly set that X-Firebase-AppCheck header. Cloud Functions should usually receive an X-Firebase-AppCheck header - with the previously retrieved AppCheck token:
const appCheckToken = req.header('X-Firebase-AppCheck');

if (!appCheckToken) {
    res.status(401);
    return next('Unauthorized');
}

try {
    const appCheckClaims = await firebaseAdmin.appCheck().verifyToken(appCheckToken);
    // If verifyToken() succeeds, continue with the next middleware function in the stack.
    return next();
} catch (err) {
    res.status(401);
    return next('Unauthorized');
}

One can also issue own tokens ...and checking for context-app is also valid.

Update: The Protocol specification for https.onCall reads:

Optional: X-Firebase-AppCheck: <token>
The Firebase App Check token provided by the client app making the request. The backend automatically verifies this token and decodes it, injecting the appId in the handler's context. If the token cannot be verified, the request is rejected.Available for SDK >=3.14.0

To install the minimum required NodeJS dependencies:
npm install firebase-functions@">=3.14.0"
npm install firebase-admin@">=9.8.0"

And last, but not least ...there's even a debug helper for that:
dependencies {
    debugImplementation "com.google.firebase:firebase-appcheck-debug:16.0.0-beta02"
}

A: After testing everything with no success, in a desperate move, I tried to look to unrelated files and found the solution.
In my build.gradle I was importing all the Firebase dependencies with the bom:
implementation platform("com.google.firebase:firebase-bom:27.0.0")
implementation "com.google.firebase:firebase-crashlytics-ktx"
implementation "com.google.firebase:firebase-analytics-ktx"
implementation "com.google.firebase:firebase-firestore-ktx"
implementation "com.google.firebase:firebase-functions-ktx"
implementation "com.google.firebase:firebase-auth-ktx"

So I thought: "Can the firebase-bom be importing an outdated functions-ktx dependency?"
And guess what? As soon as I imported the dependencies without the bom, I started to see the X-Firebase-AppCheck being added and the context.app being valid.
I ended up with the following build.gralde:
implementation "com.google.firebase:firebase-crashlytics-ktx:18.2.1"
implementation "com.google.firebase:firebase-analytics-ktx:19.0.0"
implementation "com.google.firebase:firebase-firestore-ktx:23.0.3"
implementation "com.google.firebase:firebase-functions-ktx:20.0.0"
implementation "com.google.firebase:firebase-auth-ktx:21.0.1"

After a little more investigation, I found out that I was using an outdated firebase-bom version. Android Studio used to let me know if there was a new version for the dependencies, but it did not notice me for the firebase-bom. Turns out, that I just need to update my firebase-bom dependency.
TL;DR
Check your Android Firebase libraries version!


text:
Q: Trying to implement "Like" functionality and "Wishlist" functionality. 1 intermediate table for both? Considering:

*

*A user can like many places, and a place can be liked by many users

*A user can add many places to his wishlist, and a place can be in the
wishlist of many users

Both the "Like" and "Wishlist" functionality will be using many-to-many relationships. For both of these functionalities, I definitely need to link the Users table and the Places table since the users will like/wishlist certain places
Laravel's naming convention for pivot tables is singularized table names in alphabetical order separated by an underscore. So let's give an example with the first example:
My first intermediate table which will be used for storing the likes will be called Place_User. It's all fine and dandy so far.
HOWEVER, my second intermediate table also connects the Users and Places tables, it just doesn't store the liked places but the wishlisted places so that means the second table should also be called Place_User. This will obviously lead to some problems.
I have already finished the like functionality and as soon as I started the wishlist functionality, I realized I already have all the tables I needed beside the intermediate table, however, as I explained by convention, the intermediate table for the wishlists should be called the same as the intermediate table for likes.
What am I meant to do in this case?

A: Just name your pivot tables in a different way, like place_user_like and place_user_wishlist.
Then in your User model you can write this
public function likedPlaces() {
    return $this->belongsToMany('App\Place', 'place_user_like');
}

public function wishlistedPlaces() {
    return $this->belongsToMany('App\Place', 'place_user_wishlist');
}


text:
Q: Определение геолокации. Клиентский JS Как определить геолокацию пользователя? Как я понял это делается через
window.navigator.geolocation

Но пока ничего внятного я не смог извлечь

A: HTML

CSS
#map {
  height: 100%;
}
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

JS

Но нужна апи от гугла (получить достаточно просто)


text:
Q: Class 'Laracon21\Colorcodeconverter\ColorcodeconverterServiceProvider' not found I am trying to run a Laravel project but I am getting the following error:
$ php artisan config:cache

In ProviderRepository.php line 208:

  Class 'Laracon21\Colorcodeconverter\ColorcodeconverterServiceProvider' not found

I tried composer require laracon21/colorcodeconverter to add laracon21, it's added in the vendor folder successfully but the composer does not update perfectly, showing:
Problem 1
     - Conclusion: don't install laravel/framework v6.20.30
     - Conclusion: don't install laravel/framework v6.20.29
     - Conclusion: don't install laravel/framework v6.20.28
     - Conclusion: don't install laravel/framework v6.20.27
       .
       .
       .
     - Conclusion: don't install laravel/framework v6.0.0
     - laracon21/colorcodeconverter 1.1 requires illuminate/support ^7.0 -> satisfiable by laravel/framework[7.x-dev], illuminate/support[7.x-dev, v7.0.0, v7.0.1, v7.0.2, v7.0.3, v7.0.4, v7.0.5, v7.0.6, v7.0.7, v7.0.8, v7.1.0, v7.1.1, v7.1.2, v7.1.3, v7.10.0, v7.10.1, v7.10.2, v7.10.3, v7.11.0, v7.12.0, v7.13.0, v7.14.0, v7.14.1, v7.15.0, v7.16.0, v7.16.1, v7.17.0, v7.17.1, v7.17.2, v7.18.0, v7.19.0, v7.19.1, v7.2.0, v7.2.1, v7.2.2, v7.20.0, v7.21.0, v7.22.0, v7.22.1, v7.22.2, v7.22.3, v7.22.4, v7.23.0, v7.23.1, v7.23.2, v7.24.0, v7.25.0, v7.26.0, v7.26.1, v7.27.0, v7.28.0, v7.28.1, v7.28.2, v7.28.3, v7.28.4, v7.29.0, v7.29.1, v7.29.2, v7.29.3, v7.3.0, v7.30.0, v7.30.1, v7.30.2, v7.30.3, v7.30.4, v7.4.0, v7.5.0, v7.5.1, v7.5.2, v7.6.0, v7.6.1, v7.6.2, v7.7.0, v7.7.1, v7.8.0, v7.8.1, v7.9.0, v7.9.1, v7.9.2].
     - Can only install one of: laravel/framework[7.x-dev, 6.x-dev].
     - don't install illuminate/support 7.x-dev|don't install laravel/framework 6.x-dev
     - don't install illuminate/support v7.0.0|don't install laravel/framework 6.x-dev
     - don't install illuminate/support v7.0.1|don't install laravel/framework 6.x-dev
     - don't install illuminate/support v7.0.2|don't install laravel/framework 6.x-dev

And here is my composer.json:
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": "^7.2",
        "anandsiddharth/laravel-paytm-wallet": "^1.0",
        "barryvdh/laravel-dompdf": "^0.8.2",
        "fideloper/proxy": "^4.0",
        "gabrielbull/ups-api": "^0.8.0",
        "guzzlehttp/guzzle": "^6.5",
        "instamojo/instamojo-php": "^0.4.0",
        "laracasts/flash": "^3.0",
        "laracon21/colorcodeconverter": "^1.1",
        "laravel/framework": "6.*",
        "laravel/passport": "^7.3",
        "laravel/socialite": "^4.3",
        "laravel/tinker": "^1.0",
        "maatwebsite/excel": "^3.1",
        "mehedi-iitdu/core-component-repository": "dev-master",
        "mehedi-iitdu/laravel-paystack": "dev-master",
        "mehedi-iitdu/paypal": "dev-master",
        "nexmo/laravel": "^2.2",
        "razorpay/razorpay": "2.0.0",
        "spatie/laravel-image-optimizer": "^1.3",
        "stripe/stripe-php": "^6.29",
        "twilio/sdk": "^6.1"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.0"
    },
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": ["app/Http/Helpers.php"]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "extra": {
        "laravel": {
            "dont-discover": [
                "laravel/dusk"
            ]
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ],
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

Please help me. how can I solve this?

A: Don't you see it requires laravel: ^7.0.0 ? You are trying to use laravel: ^6.x...
The error says it clearly: illuminate/support ^7.0, don't install laravel/framework v6.0.0.
So, you must change it to 7.x.


text:
Q: Spark ComboBox - issue with displaying text for new item? I've been playing with s:ComboBox and generally like them a lot. One detail is driving me nuts though - most likely due to my lack of knowledge in the subject - is that if I try to add a new item to my dataprovider in a changeHandler (registered to the change event) the text for the ComboBox textInput disappears - although the item addition works perfectly. Interestingly enough the same operation works fine if it gets called by clicking on a button, i.e. post the change event has been processed, and the text does not disappear. Here's some code from here that shows this
<?xml version="1.0" encoding="utf-8"?>
<!-- dpcontrols\spark\SparkCBAddItem.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
      xmlns:s="library://ns.adobe.com/flex/spark"
      xmlns:mx="library://ns.adobe.com/flex/mx">
 <s:layout>
  <s:VerticalLayout paddingTop="5" paddingLeft="5"/>
 </s:layout>

 <fx:Script>
  <![CDATA[
   import mx.collections.ArrayList;

   import spark.events.IndexChangeEvent;

   [Bindable]
   public var myDP:ArrayList = new ArrayList(["Red", "Orange", "Yellow", "Blue", "Green"]);

   // Event handler to determine if the selected item is new.
   protected function myCB_changeHandler(event:IndexChangeEvent):void
   {
    // Determine if the index specifies a new data item.
    if(myCB.selectedIndex == spark.components.ComboBox.CUSTOM_SELECTED_ITEM)
    {
     // Add the new item to the data provider.
     myCB.dataProvider.addItem(myCB.selectedItem);
    }
   }

   protected function button1_clickHandler(event:MouseEvent):void
   {
    // Determine if the index specifies a new data item.
    if(myCB.selectedIndex == spark.components.ComboBox.CUSTOM_SELECTED_ITEM)
    {
     // Add the new item to the data provider.
     myCB.dataProvider.addItem(myCB.selectedItem);
    }
   }

  ]]>
 </fx:Script>

 <s:Label text="The selected index is: {myCB.selectedIndex}"/>
 <s:Label text="The selected item is: {myCB.selectedItem}"/>

 <s:ComboBox id="myCB" width="140" change="myCB_changeHandler(event);" dataProvider="{myDP}"/>
 <s:Button label="Button" click="button1_clickHandler(event)"/>

</s:Application>

if you take out the change handler you will see that adding a new item and then clicking on the button keeps the new element in the textInput while adding the item to the data provider, which does not happen if you just enter a new item and press enter.
thanks in advance for any help!

A: Ok, I guess callLater on the contents of myCB_changeHandler seems to do the trick, i.e.
private function later(event:IndexChangeEvent):void
{
    // Determine if the index specifies a new data item.
    if(myCB.selectedIndex == spark.components.ComboBox.CUSTOM_SELECTED_ITEM)
    {
        // Add the new item to the data provider.
        myCB.dataProvider.addItem(myCB.selectedItem);
    }

}

// Event handler to determine if the selected item is new.
protected function myCB_changeHandler(event:IndexChangeEvent):void
{
      callLater(later, [event]);
}


text:
Q: ajax - view different content I want to listen to music or watch video in the same page (without opening a new page in browser). So I want to use ajax for this purpose. I have different files and I want to do something with them depends on it's type. For example, I have 1.mp3 - listen, 2.avi - watch, 3.png - view. I need to have the same behaviour like if I click on href.  - It opens new page and loads 3.png.
Please, help me! Thanks.

A: create individual classes for your contents as:

Now code in individual classes as

$('.png').click(function(){
 alert('png');
});
$('.avi').click(function(){
 alert('png');
});
$('.mp3').click(function(){
 alert('mp3');
});

OR
$('a').click(function(){
   var ext=$(this).attr('href').val().substring($(this).attr('href').val().lastIndexOf('.')+1).toLowerCase();
   if(ext=='png'){
     //code for png
   } //and so on
})

A: How about this:


text:
Q: Asp.net Column placement to next row in gridview Is it possible to move a column to the next row in a gridview somehow?
Like this:

This really is the best way to explain what i'm trying to do.
here's some code for you nice fellows.

ASP.NET
<asp:GridView
                runat="server"
                ID="Notifications"
                CssClass="Notifications"
                PageSize="30"
                AllowPaging="true"
                AutoGenerateColumns="false"
                ShowHeader="false"
                OnRowCreated="Notifications_RowCreated">
            <RowStyle CssClass="TableRow" />
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Image ID="IMG_Seen" runat="server" AlternateText="Error" ImageUrl='<%# Eval("cSeen") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Image ID="IMG_Status" runat="server" AlternateText="Error" ImageUrl='<%# Eval("cStatus") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="L_Title" runat="server" Text='<%# Eval("cTitle") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="L_Date" runat="server" Text='<%# Eval("cDate") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="L_Description" runat="server" Text='<%# Eval("cDescription") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lLB_inkTo" runat="server" PostBackUrl='<%# Eval("clinkto") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            </asp:GridView>

C# -Gridview bind method

void Init_Notifications(XDocument xDoc)
    {
        GridView GV = Notifications;
        var Root = from p in xDoc.Descendants("User") select p;
        var getNotify = from n in Root.Descendants("Notifications") select n;
        foreach (XElement xe in getNotify.Nodes())
        {
            NotifList.Add(new Notification(
                xe.Attribute("ID").Value,
                xe.Attribute("Status").Value,
                xe.Attribute("Title").Value,
                xe.Attribute("Seen").Value,
                xe.Attribute("linkTo").Value,
                xe.Element("Description").Value
                )
            );
        }
        DataTable DT = new DataTable();
        DT.Columns.Add("cDate", typeof(System.String));
        DT.Columns.Add("cStatus", typeof(System.String));
        DT.Columns.Add("cTitle", typeof(System.String));
        DT.Columns.Add("cSeen", typeof(System.String));
        DT.Columns.Add("cDescription", typeof(System.String));
        DT.Columns.Add("clinkTo", typeof(System.String));
        foreach (Notification n in NotifList)
        {
            object[] RowContent =
            {
                n.pDate,
                n.pStatus,
                n.pTitle,
                n.pSeen,
                n.pDescription,
                n.pLinkTo
            };
            DT.Rows.Add(RowContent);
        }
        Notifications.DataSource = DT;
        Notifications.DataBind();
    }

Im basically trying to somehow convert / move this into a new row via codebehind or aspx code.
I couldn't get this to look great using CSS as well

A: Yes that is certainly possible =) You can achieve this by rendering the gridview column as a new table row on your aspx page. Just add a template field in your gridview & include tr, td tags like this
<asp:TemplateField>
                 <ItemTemplate>

                 </ItemTemplate>
 </asp:TemplateField>


text:
Q: How to render the text in the editor of column of grid panel differently(ExtJs6.0.2) I have grid with a column that has an editor configured as text field.
var grid = Ext.create('Ext.grid.Panel', {
            title: 'Simpsons',
            itemId: 'gridPanel123',
            store: store,
            plugins: {
                ptype: 'cellediting',
                clicksToEdit: 1
            },
            columns: [{
                text: 'Name',
                dataIndex: 'name',
                editor: {
                    xtype: 'textfield'
                }
            }]
});

Say the column looks something like this,

Clearly the value of the column is ABCDE.
Now when the user clicks on the column, the editor mode pops up something like this :

Now my question is, is there any kind of renderer that would change the content of the editor based on the value of the column.
Considering my example, column value is "ABCDE", so the editor value is also coming as "ABCDE".
But what if I want to replace all 'A' in the column with 'Z' in the editor .So the editor value for me should have been 'ZBCDE'. How is this possible in extjs?

A: You can do it by setting value in beforeEdit event in cell editing plugin.
cellediting: {
     listeners: {
          beforeEdit: function (editor, context) {
               context.value = context.value.replace("A", "Z");
          }
     }
}

To determine which column should be replaced just add check:
if(context.column.dataIndex == 'name'){
    context.value = context.value.replace("A", "Z");
}

To reverse replace try :
validateEdit: function (editor, context){
    context.record.set('name', context.value.replace("Z", "A"));
    context.record.commit();
}

Example on fiddle: https://fiddle.sencha.com/#view/editor&fiddle/2thq.