text:
Q: R-Shiny Leaflet Right-Click Context Menu I got a R-Shiny app and a leaflet map in my UI output. I want to setup something where I can right click on the map and it opens a context menu on cursor coordinates, where I can select icons and input text. This will allow me to place custom markers on the map and name them.
observeEvent(input$map_right_click, {
showCustomMarkerMenu(location = (input$map_click$lat, input$map_click$lng)) //sample
addMarkers(lat = input$map_click$lat, lng = input$map_click$lng)
})

A: You can achieve right clicks with htmlwidgets::onRender and Shiny.setInputValue. With htmlwidgets::onRender its possible to retrieve the leaflet map instance, which you need to get the coordinates of the click. Next with Shiny.setInputValue you send the coordinates to your shiny module or application and trigger a change event of the input which you observe with observeEvent.
leaflet::leaflet() %>%
leaflet::addTiles() %>%
htmlwidgets::onRender("
    function(el,x) {
        map = this;
        map.on('contextmenu', function(e) {
        var coords = {lng: e.latlng.lng, lat: e.latlng.lat}
        Shiny.setInputValue('map_right_click', coords);
    });
    }
")

shiny::observeEvent(input$map_right_click, {
    output$myLng<- renderText({ input$map_right_click$lng })
})


text:
Q: High-frequency performance counter sampling using perf record/report I want to retrieve performance counter counts at a high frequency (i.e. 100-200Hz) using the perf tool (similar in functionality to https://github.com/RRZE-HPC/likwid/wiki/likwid-perfctr#the-timeline-mode but at a higher frequency).  Is there a way to do this?  If so, what flags do I need to use when recording with perf record and reporting results with perf report?
So far, I've tried the following to retrieve the r6d70 performance counter at 5ms intervals during sleep 5 execution: sudo perf record -F200 -e r6d70 -a sleep 5.  However, when I use perf report to view the outputted data, I see the following, which isn't really what I want:
Samples: 109  of event 'r6d70', Event count (approx.): 68432
Overhead  Command     Shared Object      Symbol
  33.77%  swapper     [kernel.kallsyms]  [k] update_blocked_averages
  10.30%  node        [kernel.kallsyms]  [k] update_blocked_averages
   9.07%  containerd  [kernel.kallsyms]  [k] update_load_avg
   8.98%  containerd  [kernel.kallsyms]  [k] __switch_to
   8.56%  node        node               [.] Builtins_LdaNamedPropertyHandler
   5.90%  swapper     [kernel.kallsyms]  [k] __sched_text_start
   5.88%  swapper     [kernel.kallsyms]  [k] cpufreq_this_cpu_can_update
   5.81%  nautilus    [kernel.kallsyms]  [k] update_blocked_averages
   4.56%  node        node               [.] v8::platform::tracing::TracingController
   3.82%  swapper     [kernel.kallsyms]  [k] arch_irq_work_raise
   3.20%  containerd  [kernel.kallsyms]  [k] select_task_rq_fair
   0.03%  swapper     [kernel.kallsyms]  [k] acpi_idle_do_entry

redpajama_set_name: RedPajamaStackExchange


text:
Q: python, map name from a list to a list of dict I have the following list and list of dicts:
data = [dict(position=1, value=150.3),
        dict(position=0, value=28.5),
        dict(position=2, value=1050.3)]

names = ["CL", "ES", "EUR"]

I would like to map the values of the list into the list of dicts so they match the value stated in the key "position" of the dict - to get the following result:
data = [dict(name="ES", position=1, value=150.3),
        dict(name="CL", position=0, value=28.5),
        dict(name="EUR", position=2, value=1050.3)]

Is there any "smart" and pythonic way to achieve that?

A: First of all, please present your question in actual Python form. dict is a type; the way you represent dictionaries in Python is with {}.
Also, you don't have "a dict and list", you have two lists, one of which consists of three dictionaries. So:
data = [
  {'position': 1, 'value': 150.3},
  {'position': 0, 'value': 28.5},
  {'position': 2, 'value': 1050.3}
]

names = ["CL", "ES", "EUR"]

So, given that you do have lists, there is no concern about ordering. A simple loop will give you what you want:
for d in data:
    d['name'] = names[d['position']]

This updates data in place:
>>> data
[{'position': 1, 'name': 'ES', 'value': 150.3}, {'position': 0, 'name': 'CL', 'value': 28.5}, {'position': 2, 'name': 'EUR', 'value': 1050.3}]

A: You can use a list comprehension and dictionary update:
data = [dict(position = 2, value=150.3),
        dict(position = 1, value = 28.5),
        dict(position=3, value=1050.3)]

names = ['CL', 'ES', 'EUR']

# Sort names according to "position" value of the dictionary
sorted_names = [names[idx] for idx in map(lambda x: x['position'], data)]
# Update modifies inplace
_ = [data[idx].update({'name' : el}) for idx, el in enumerate(sorted_names)]

Which gives the expected output:
data
[{'name': 'ES', 'position': 2, 'value': 150.3},
 {'name': 'CL', 'position': 1, 'value': 28.5},
 {'name': 'EUR', 'position': 3, 'value': 1050.3}]

A: You could try:
data = [{"position": 2, "value": 150},
        {"position": 1, "value": 200}]
names = ["CL", "ES"]

for item in data:
    item["name"] = names[item["pos"] - 1]

Where we go through all the dictionaries in the list, then for each dictionary we set the "name" key to be equal to the value in data at the position described in item["pos"] minus 1.
This of course assumes your data is clean and all items in data correctly map to items in names.
If this is not the case, use a try-except:
for item in data:
    try:
        item["name"] = names[item["pos"] - 1]
    except IndexError:
        item["name"] = None

A: You can also use the update method on the dictionary elements in the list, if you like the keyword-argument convention, as the style of your question suggests.
for item in data:
    item.update(name=names[item["position"]])

A: A one liner implementation using list comprehension.
print [dict(d.items()+[('name',names[d['position']-1])]) for d in data]


text:
Q: "Ajax is not found" exception - is Rails defaulting to Prototype by mistake? I am trying to create a page that shows a list of tasks and allows the user to update task status by checking a checkbox.
When I run the page on the browser and click on the checkbox, I get a Javascript Exception "

Uncaught ReferenceError: Ajax is not
  defined (anonymous function)2:96
  onclick

Here is the code that I have on my _task.html.erb file:
<%= check_box_tag "id", "id", task.done,
    :onclick => remote_function(
      :update => "task",
      :url => { :action => :update },
      :with => "'done=true'",
      :complete => "alert('hi')"  ) %>

Why am I getting this Ajax is not defined exception?
I reinstalled rails jquery, ensure that there is a rails.js and a jquery.js in the javascripts folder and confirmed they are loading on the HTML, see below:
<script src="/javascripts/jquery.js?1303396383" type="text/javascript"></script>
<script src="/javascripts/rails.js?1303562965" type="text/javascript"></script>
<script src="/javascripts/application.js?1301606933" type="text/javascript"></script>
<script src="/javascripts/jquery.purr.js?1302145859" type="text/javascript"></script>
<script src="/javascripts/best_in_place.js?1302150372" type="text/javascript"></script>

Someone posted a comment saying that "Ajax" with capital A is a prototype function rather than a rails function. Is my application somehow configured to try to use Prototype rather than rails? While files do I need to change to fix this?
I just tried changing config/application.rb and uncommented this line:
config.action_view.javascript_expansions[:defaults] = %w(jquery rails)

Didn't seem to work either. Any idea?
Thanks a lot for your help.

A: remote_function, like most of RJS, uses Prototype directly and is not part of the UJS concept. The Prototype helpers are always available in a Rails application (until Rails 3.1), but the JavaScript they produce is Prototype-only and will not work unless you are also using the Prototype JavaScript library.
In your example, you are using jQuery and not Prototype. If you want to use jQuery, you should write out the expected JavaScript or write your own remote_function helper.

A: Because you're not including the default javascript libraries.  Take a look in your layout file, and you need a line like this up in the head (I'm assuming ERB):
<%= javascript_include_tag :defaults %>

And make sure either prototype or jquery exists in public/javascripts and the rails.js too.
Update
You revealed in a comment that you're using jquery - but your error mentions a capital-a "Ajax" which is the prototype name.
To get the right rails.js follow these instructions


text:
Q: Spectral analysis with RF signal generator I need the spectral analysis of an LC circuit which oscillates in UHF band. I have a rough idea about its resonance peak but I need to observe it. As equipment, I have at my disposal Aeroflex 3020 RF signal generator, Aeroflex 3035 RF digitizer. Each uses a 3010 RF synthesizer as local oscillator.
My question is that, can I use this setup for spectral analysis purpose ? If yes, what would be the strategy to follow ? Should I sweep the frequency range via script? Should I send signals which contain many harmonics to excite the circuit ?
Thanks in advance,

A: You can use any source/receiver pair like that as a scalar network analyser. Just program them to the same frequency, and they'll give you a measurement of gain at that frequency. Step the frequencies over a range to get gain versus frequency vector, and plot it for a spectrum.


text:
Q: Matlab simulation of dog chasing a rabbit pursuit curve. Hi I'm really struggling with this problem of mine.
A rabbit is running along the x-axis ($0\to \infty$) with a constant velocity $v_r$ and a dog chases the rabbit starting at some point $L (0\cdots \infty)$ on the y-axis with a constant velocity $v_d$. The velocity vector of the dog is always pointing towards the rabbits location.
So I need the differential equation for the location of the dog and solve it numerically using matlab. To be exact, I need to plot the pursuit curve of the dog.
I also need to determine the time it takes to catch the rabbit (distance < 0.1m) at varying values of vr, vd and L (with matlab).
I can't make any sense of the examples I found over the past few days and can't figure out the use of ode45 function either.
I'd really appreciate your help. Thank you!

A: Begin by formulating your system.
$$\begin{align*}
\frac{dx_r}{dt} &= v_r, \\
\frac{dy_r}{dt} &= 0, \\
\frac{dx_d}{dt} &= v_{dx}, \\
\frac{dy_d}{dt} &= v_{dy}.
\end{align*}$$
Now, $v_{dx}$ and $v_{dy}$ are determined by the vector from the rabbit to the dog. In other words, they proportional to $v_d$ as the component of the vector $(x_r-x_d, y_r-y_d)$ are proportional to its overall magnitude. In other words, you should get
$$v_{dx} = v_d \cdot \frac{x_r-x_d}{\sqrt{(x_r-x_d)^2+(y_r-y_d)^2}}$$
and similarly for $v_{dy}$.
Now you have a first-order nonlinear system. You should be able to set up initial conditions, and ode45 should suit you just fine.
To use it, let's set up our function handle
%X = [x_r; y_r; x_d; y_d]
f = @(t,X)[v_r*(norm([X(1)-X(3); X(2)-X(4)])>.01);...
           0;...
           v_d*(X(1)-X(3))./norm([X(1)-X(3); X(2)-X(4)])*(norm([X(1)-X(3); X(2)-X(4)])>.01);...
           v_d*(X(2)-X(4))./norm([X(1)-X(3); X(2)-X(4)])*(norm([X(1)-X(3); X(2)-X(4)])>.01)];

Note that norm([X(1)-X(3); X(2)-X(4)]) just gives you the magnitude of the vector between the animals (e.g. the absolute distance).
The weird line that I put in the function handle ad the end of each line, *(norm([X(1)-X(3); X(2)-X(4)])>.01)] sets the system to be identically zero if our terminal condition is met. This is a hack! If the dog gets too close, we begin dividing by a small number and things go chaotic.
Normally, we might try a shooting method, but our initial conditions are well-specified.
Now just call ode45:
[tout, xout] = ode45(f,[0 T],x0);

To compute the distance between the animals, it is simple:
delta = sqrt((xout(:,1)-xout(:,3)).^2+(xout(:,2)-xout(:,4)).^2);


text:
Q: Error in cordova local notification I added Cordova-plugin-local-notification on my project(https://github.com/katzer/cordova-plugin-local-notifications).
and I added this code to the project
cordova.plugins.notification.local.schedule({
    title: 'My first notification',
    text: 'Thats pretty easy...',
    foreground: true
});

but it shows an error:
cordova is not defined
    at new MyApp

how can I fix this issue?
pls help

A: Need to, declare cordova like this,
declare var cordova: any;


text:
Q: Symfony flag-toggling entities I want to ask, is it possible to have "Flagception - Feature toggle bundle", to have entities ignored in doctrine migrations?
I have a huge project, which I have to reuse many times. I can simply use it, flag unnecessary elements and it is pretty much ready, but doctrine migrations are still using unused entities, and creating tables for them. Is it possible flag specific entities, so doctrine migration would ignore them?

A: Try using doctrine dbal schema_filter option like this:
doctrine:
    dbal:
        schema_filter: ~^(?!prefix_)~

Every table starting with prefix_ will be ignored.
More about ignoring custom tables here

A: You can do it via command line no need to write in doctrine.yaml file everytime. Using this command would filter out all tables starting with foobar:
php bin/console doctrine:migrations:diff --filter-expression='~^(?!foobar)~'


text:
Q: Dropdown menu doesn't work from tutorial i have a code from a tutorial in youtube. I was stuck because it doesn't work while i already added its bootstrap js and others. Please help me . Thanks.
Here is the code from tutorial dropdown menu:

        Site Tittle

        <button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">

        </button>

Home

Blog

              Social Media

Twitter

Facebook

Google+

Instagram

About

Here is links :
<link href="<?php echo base_url('assets/css/bootstrap.css');?>" rel="stylesheet">
  <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  <link href="<?php echo base_url('assets/css/bootstrap-theme.css');?>" rel="stylesheet">
  <link href="<?php echo base_url('assets/js/jquery.min.js');?>" rel="stylesheet">

A: Without a working code, I can only guess.
But my guess is because of this:
data-target=".navHeaderCollapse"

Try to remove the period.
And I think navHeaderCollapse should be an id.

A:
you're including a js file as stylesheet

A: try adding

and .navHeaderCollapse was correct. Don't change it.

A: You forgot the bootstrap js file:

With this line it should work.


text:
Q: Predicting a numeric attribute through high dimensional nominal attributes I'm having difficulties mining a big (100K entries) dataset of mine concerning logistics transportation. I have around 10 nominal String attributes (i.e. city/region/country names, customers/vessel identification codes, etc.). Along with those, I have one date attribute "departure" and one ratio-scaled numeric attribute "goal".
What I'm trying to do is using a training set to find out which attributes have strong correlations with "goal" and then validating these patterns by predicting the "goal" value of entries in a test set.
I assume clustering, classification and neural networks could be useful for this problem, so I used RapidMiner, Knime and elki and tried to apply some of their tools on my data. However, most of these tools only handle numeric data, so I got no useful results.
Is it possible to transform my nominal attributes into numeric ones? Or do I need to find different algorithms that can actually handle nominal data?

A: you most likely want to use tree based algorithm. These are good to use nominal features. Please be aware, that you do not want to use "id-like" attributes.
I would recommend RapidMiner's AutoModel feature as a start. GBT and RandomForest should work well.
Best,
Martin

A: the handling of nominal attributes does not depend on the tool. It is a question what algorithm you use. For example k-means with Euclidean distance can't handle string values. But other distance functions can handle them and algorithms can handle them, for example the random forest implementation of RapidMiner
You can also of course transform the nominal attributes to numerical, for example by using a binary dummy encoding or assigning an unique integer value (which might result in some bias). In RapidMiner you have the Nominal to Numerical operator for that.
Depending on the distribution of your nominal values it might also be useful to handle rare values. You could either group them together in a new category (such as "other") or to use a feature selection algorithm after you apply the dummy encoding.
See the screen shot for a sample RapidMiner process (which uses the Replace Rare Values operator from the Operator Toolbox extension).
Edit: Martin is also right, AutoModel will be a good start to check for problematic attributes and find a fitting algorithm.


text: Q: Find sup and inf of $\frac{abc+bcd+cda+dab}{a^3 + b^3 + c^3 + d^3}$. Did I do it right? I need to find sup and inf of: $\frac{abc+bcd+cda+dab}{a^3 + b^3 + c^3 + d^3}$. Now I know that I can proof form the inequality of arithmetic and geometric means that $a^3 + b^3 + c^3 + d^3 >= abc+bcd+cda+dab$ so I know that the sup = 1 and the expression = 1 for a=b=c=d=1. On the other hand I see that for a = 1, b = 1, c = 1 and d = n, if $n \implies \infty$ then $\frac{1+n+n+n}{1^3 + 1^3 + 1^3 + n^3} =\frac{3n+1}{n^3 + 3} \implies 0 $ and $0$ is never reached. But is that enough to call my thinking a formal proof of sup and inf?


text:
Q: Concatenate Numpy arrays with least memory Not I have 50GB dataset saved as h5py, which is a dictionary inside. The dictionary contains keys from 0 to n, and the values are numpy ndarray(3 dimension) which have the same shape. For example:
dictionary[0] = np.array([[[...],[...]]...])
I want to concat all these np arrays, code like
sample = np.concatenate(list(dictionary.values))

this operation waste 100GB memory! If I use
del dictionary

It will decrease to 50GB memory. But I want to control the memory usage as 50GB during loading data. Another way I tried like this
    sample = np.concatenate(sample,dictionary[key])

It is still using 100GB memory. I think all the cases above, the right side will create a new memory block to save, and then assigned to the left side, which will double the memory during calculations. Thus, the third way I tried like this
sample = np.empty(shape)
with h5py.File(...) as dictionary:
    for key in dictionary.keys():
        sample[key] = dictionary[key]

I think this code has an advantage. The value dictionary[key] assigned to some row of sample, then the memory of dictionary[key] will clear. However, I test it and find that the memory usage is also 100GB. Why?
Are there any good methods to limit the memory usage as 50GB?

A: Your problem is that you need to have 2 copies of the same data in memory.
If you build the array as in test1 you'll need far less memory at once, but at the cost of losing the dictionary.
import numpy as np
import time

def test1(n):
    a = {x:(x, x, x) for x in range(n)} # Build sample data
    b = np.array([a.pop(i) for i in range(n)]).reshape(-1)
    return b

def test2(n):
    a = {x:(x, x, x) for x in range(n)} # Build sample data
    b = np.concatenate(list(a.values()))
    return b

x1 = test1(1000000)
del x1

time.sleep(1)

x2 = test2(1000000)

Results:

test1 : 0.71 s
test2 : 1.39 s

The first peek is for test1, it's not exactly in place but it reduces the memory usage quite a bit.

A: dictionary[key] is a dataset on the file.  dictionary[key][...] will be an numpy array, that dataset downloaded.
I imagine
sample[key] = dictionary[key]

is evaluated as
sample[key,...] = dictionary[key][...]

The dataset is downloaded, and then copied to a slice of the sample array.  That downloaded array should be free for recycling.  But whether numpy/python does that is another matter.  I'm not in the habit of pushing memory limits.
You don't want to do the incremental concatenate - that's slow.  A single concatenate on the list should be faster.  I don't know for such what
list(dictionary.values)

contains.  Will it be references to the datasets, or downloaded arrays?  Regardless concatenate(...) on that list will have to used the downloaded arrays.

One thing puzzles me - how can you use the same key to index the first dimension of sample and dataset in dictionary?  h5py keys are supposed to be strings, not integers.

Some testing
Note that I'm using string dataset names:
In [21]: d = f.create_dataset('0',data=np.zeros((2,3)))
In [22]: d = f.create_dataset('1',data=np.zeros((2,3)))
In [23]: d = f.create_dataset('2',data=np.ones((2,3)))
In [24]: d = f.create_dataset('3',data=np.arange(6.).reshape(2,3))

Your np.concatenate(list(dictionary.values)) code is missing ():
In [25]: f.values
Out[25]: <bound method MappingHDF5.values of <HDF5 file "test.hf" (mode r+)>>
In [26]: f.values()
Out[26]: ValuesViewHDF5(<HDF5 file "test.hf" (mode r+)>)
In [27]: list(f.values())
Out[27]:
[<HDF5 dataset "0": shape (2, 3), type "<f8">,
 <HDF5 dataset "1": shape (2, 3), type "<f8">,
 <HDF5 dataset "2": shape (2, 3), type "<f8">,
 <HDF5 dataset "3": shape (2, 3), type "<f8">]

So it's just a list of the datasets.  The downloading occurs when concatenate does a np.asarray(a) for each element of the list:
In [28]: np.concatenate(list(f.values()))
Out[28]:
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [1., 1., 1.],
       [1., 1., 1.],
       [0., 1., 2.],
       [3., 4., 5.]])

e.g.:
In [29]: [np.array(a) for a in f.values()]
Out[29]:
[array([[0., 0., 0.],
        [0., 0., 0.]]), array([[0., 0., 0.],
        [0., 0., 0.]]), array([[1., 1., 1.],
        [1., 1., 1.]]), array([[0., 1., 2.],
        [3., 4., 5.]])]
In [30]: [a[...] for a in f.values()]
    ....

Let's look at what happens when using your iteration approach:
Make an array that can takes one dataset for each 'row':
In [34]: samples = np.zeros((4,2,3),float)
In [35]: for i,d in enumerate(f.values()):
    ...:     v = d[...]
    ...:     print(v.__array_interface__['data']) # databuffer location
    ...:     samples[i,...] = v
    ...:
(27845184, False)
(27815504, False)
(27845184, False)
(27815504, False)
In [36]: samples
Out[36]:
array([[[0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [0., 0., 0.]],

       [[1., 1., 1.],
        [1., 1., 1.]],

       [[0., 1., 2.],
        [3., 4., 5.]]])

In this small example, it recycled every other databuffer block.  The 2nd iteration frees up the databuffer used in the first, which can then be reused in the 3rd, and so on.
These are small arrays in a interactive ipython session.  I don't know if these observations apply in large cases.


text:
Q: converting formatted json object to array of objects by keys and sum up on each level Have the following tree json object:
{
  "Season1": {
    "Title1": {
      "a1": {
        "val1": "100",
        "val2": "200",
        "val3": "300"
      },
      "a2": {
        "val1": "100",
        "val2": "200",
        "val3": "300"
      }
    },
    "Title2": {
      "c1": {
        "val1": "100",
        "val2": "200",
        "val3": "300"
      },
      "d2": {
        "val1": "100",
        "val2": "200",
        "val3": "300"
      }
    }
  }
}

Tried to format the json using the following function:
function Format(obj){
    return Object.entries(obj).flatMap(([key, val]) => {
        let o = { name: key}
        if(Object.keys(val).some(function(k) {return typeof val[k] === 'object'})){
            o['_children'] = Format(val)
        } else {
            Object.keys(val).map(function(a){
                o[a] = val[a]
            })
        }
        return [o]
    })
}

That will return an array of nested objects by keys:
[
  {
    "name": "Season1",
    "_children": [
      {
        "name": "Title1",
        "_children": [
          {
            "name": "a1",
            "val1": "100",
            "val2": "200",
            "val3": "300"
          },
          {
            "name": "a2",
            "val1": "100",
            "val2": "200",
            "val3": "300"
          }
        ]
      },
      {
        "name": "Title2",
        "_children": [
          {
            "name": "c1",
            "val1": "100",
            "val2": "200",
            "val3": "300"
          },
          {
            "name": "d2",
            "val1": "100",
            "val2": "200",
            "val3": "300"
          }
        ]
      }
    ]
  }
]

The challenge is to calculate the subtotal of the bottom level keys, which are val1, val2, val3, in each parent levels recursively, .e.g. "Title1", "Title2", and "Season1", therefore after populating the output into a table can fill up the blank subtotal cells. The expected output should look like:
[
  {
    "name": "Season1",
    "_children": [
      {
        "name": "Title1",
        "_children": [
          {
            "name": "a1",
            "val1": "100",
            "val2": "200",
            "val3": "300",
          },
          {
            "name": "a2",
            "val1": "100",
            "val2": "200",
            "val3": "300",
          }
        ],
        "val1": 200,
        "val2": 400,
        "val3": 600
      },
      {
        "name": "Title2",
        "_children": [
          {
            "name": "c1",
            "val1": "100",
            "val2": "200",
            "val3": "300",
          },
          {
            "name": "d2",
            "val1": "100",
            "val2": "200",
            "val3": "300",
          }
        ],
        "val1": 400,
        "val2": 400,
        "val3": 600
      }
    ],
    "val1": 600,
    "val2": 800,
    "val3": 1200
  }
]

How to update the Format function for that purpose? Can someone share any thoughts or solution? Thanks!

A: You can also edit your recursive function like below. I'm accumulating the sum at each level of recursion and passing it up to the call stack

data = {
  Season1: {
    Title1: {
      a1: {
        val1: "100",
        val2: "200",
        val3: "300"
      },
      a2: {
        val1: "100",
        val2: "200",
        val3: "300"
      }
    },
    Title2: {
      c1: {
        val1: "100",
        val2: "200",
        val3: "300"
      },
      d2: {
        val1: "300",
        val2: "200",
        val3: "300"
      }
    }
  }
};

function merge(srcObj, destObj){
  Object.keys(srcObj).forEach(key => {
    if(destObj[key]) {
      destObj[key] = destObj[key] + srcObj[key]
    }
    else{
      destObj[key] = srcObj[key];
    }
  });
  return destObj;
}

function Format(obj, valObj = {}, level = 0) {
    valObj[level] = {};
    return Object.entries(obj).flatMap(([key, val]) => {
      let o = { name: key };
      if (typeof val === "object") {
        o["_children"] = Format(val, valObj, level + 1);
        valObj[level] = merge(valObj[level+1],valObj[level] || {});
        if(level <2){
          o = { ...o, ...valObj[level + 1]};
        }
      } else {
        valObj[level][key] =  Number.parseInt(val);
        o["value"] = val;
      }
      return [o];
    });
}

a =  Format(data);

console.log(a);

For your modified format function, you can try like below.

data = {
  Season1: {
    Title1: {
      a1: {
        val1: "100",
        val2: "200",
        val3: "300"
      },
      a2: {
        val1: "100",
        val2: "200",
        val3: "300"
      }
    },
    Title2: {
      c1: {
        val1: "100",
        val2: "200",
        val3: "300"
      },
      d2: {
        val1: "300",
        val2: "200",
        val3: "300"
      }
    }
  }
};

function merge(srcObj, destObj){
  Object.keys(srcObj).forEach(key => {
    if(destObj[key]) {
      destObj[key] = destObj[key] + srcObj[key]
    }
    else{
      destObj[key] = srcObj[key];
    }
  });
  return destObj;
}

function Format(obj, valObj = {}, level=0){
    valObj[level] = {};
    return Object.entries(obj).flatMap(([key, val]) => {
        let o = { name: key}
        if(Object.keys(val).some(function(k) {return typeof val[k] === 'object'})){
            o['_children'] = Format(val, valObj, level + 1);
          valObj[level] = merge(valObj[level+1],valObj[level] || {});
            if(level <2){
              o = { ...o, ...valObj[level + 1]};
            }
        } else {
            Object.keys(val).map(function(a){
                valObj[level][a] = (valObj[level][a] || 0) + Number.parseInt(val[a]);
                o[a] = val[a]
            })
        }
        return [o];
    })
}

a =  Format(data);
console.log(a);

A: You could update all levels, except the most nested one.

function sum(array, sums = {}) {
    var update;
    array.forEach(o => {
        if (!o._children) {
            sums[o.name] = (sums[o.name] || 0) + +o.value;
            return;
        }
        var x = {}
        sum(o._children, x) && Object.assign(o, x);
        Object.keys(x).forEach(k => sums[k] = (sums[k] || 0) + x[k]);
        update = true;
    });
    return update;
}

var data = [{ name: "Season1", _children: [{ name: "Title1", _children: [{ name: "a1", _children: [{ name: "val1", value: "100" }, { name: "val2", value: "200" }, { name: "val3", value: "300" }] }, { name: "a2", _children: [{ name: "val1", value: "150" }, { name: "val2", value: "260" }, { name: "val3", value: "370" }] }] }, { name: "Title2", _children: [{ name: "c1", _children: [{ name: "val1", value: "110" }, { name: "val2", value: "220" }, { name: "val3", value: "330" }] }, { name: "d2", _children: [{ name: "val1", value: "101" }, { name: "val2", value: "202" }, { name: "val3", value: "303" }] }] }] }];

sum(data);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: How can I use ObjectAnimator parameters to adjust for all devices? I want to use ObjectAnimator to move a textView in the Y axis.This code works but it is not suitable for every device because of the screen sizes.
   ObjectAnimator mover = ObjectAnimator.ofFloat(expand, "translationY", -250, 0);

How can I change the last two parameters?There are also similar questions there I tried these also but they don't work.

A: There are 2 cases:

*

*You want to move your view so that it takes some defined position relatively to another view. In that case you should make your calculations based only on position of those views (see getTop(), getLeft(), etc.)

*You want your views to move some defined physical distance of the screen (which is your case I guess), so user will percept it as movement. In such case you should use device-independent-pixels (dp) instead of raw pixels (-250 in your case). ObjectAnimator itself does not support such conversion, so you have to do it by yourself. The easiest way (to write, read and support) is to store such value in dimensions resources and get them through getResources().getDimensionPixelOffest() method


text:
Q: Ember.js inserting view into application controller but use another controller for actions I have default application template where i'm inserting a separate view.
<script type="text/x-handlebars">
...default template....

{{view App.LoginView}}
</script>

<script type="text/x-handlebars" data-template-name="login">
<form {{action login on='submit'}}>
   ...login...
</form>
</script>

I have a view and controller set up for the login view
App.LoginView = Ember.View.extend({
    templateName: 'login'
});
App.LoginController = Ember.Controller.extend({
        actions: {
            login: function() {
                console.log('test');
            }
        }
    }
);

Unfortunately the login action doesn't get sent to App.LoginController but it get sent to the App.ApplicationController. How do I get the actions to forward to the App.LoginController?
Here's a link to the jsbin - http://jsbin.com/ayAnUJi/6/edit

A: Instead of using {{view}} I used {{render}} which actually uses the corresponding views controller.
<script type="text/x-handlebars">
...default template....

{{render "login"}}
</script>


text:
Q: Check column value for Any 6 rows out of 10 rows Kusto query language I have 10 rows with two columns Time and Count, So I want to check among those 10 rows if any 6 rows having value 0 or not ? Data sample:

Time
Count

2022-09-01 17:23:00.000
70

2022-09-01 17:24:00.000
150

2022-09-01 17:25:00.000
300

2022-09-01 17:26:00.000
160

2022-09-01 17:27:00.000
210

2022-09-01 17:28:00.000
316

2022-09-01 17:29:00.000
265

2022-09-01 17:30:00.000
711

2022-09-01 17:31:00.000
185

2022-09-01 17:32:00.000
250

A: let t = datatable(Time:datetime, Count:int)
[
    '2022-09-01 17:23:00.000' , 70
   ,'2022-09-01 17:24:00.000' ,150
   ,'2022-09-01 17:25:00.000' ,300
   ,'2022-09-01 17:26:00.000' ,160
   ,'2022-09-01 17:27:00.000' ,210
   ,'2022-09-01 17:28:00.000' ,316
   ,'2022-09-01 17:29:00.000' ,265
   ,'2022-09-01 17:30:00.000' ,711
   ,'2022-09-01 17:31:00.000' ,185
   ,'2022-09-01 17:32:00.000' ,250
]
;
t
| summarize result = countif(Count == 0) >= 6

result

false

Fiddle


text:
Q: How can we prove that $N_G(H)=H$ implies $N_{f(G)}(f(H))=f(H)$ Let $f:G\to K$ be a surjective group homomorphism and $H$ be a subgroup of $G$ satisfying $N_G(H)=H$. Then $N_K(f(H))=f(H)$.
I'm trying to prove or disprove it. perhaps, this proposition is true. But, how can we prove it?
Edit: I thought it is true because WIKI said it is true without proof
https://groupprops.subwiki.org/wiki/Self-normalizing_subgroup

A: This is false, so the groupprops article is incorrect.
For example, every group is the homomorphic image of some free group, and in free groups there are lots of self-normalising subgroups. In particular, maximal cyclic subgroups are self-normalising (and every non-trivial element is contained in a maximal cyclic subgroup). So you just need to find a group $G$ which contains a cyclic subgroup which is not self-normalising.
So, getting specific, consider any surjective homomorphism $\phi:F(a, b)\twoheadrightarrow K_4$ the Klein $4$-group. Then $\langle a\rangle$ is self-normalising, but $\phi(\langle a\rangle)$ is normal.

What is true is that if $H\lhd G$ and $\phi:G\twoheadrightarrow K$ then $\phi(H)\lhd K$. But that's a separate question.


text:
Q: Undefined method `<<' for nil:NilClass (NoMethodError) I have an undefined method.
rb:31:in `add_song': undefined method `<<' for nil:NilClass (NoMethodError)

I do understand that @library[artist] gives nil, but I don't understand why and do not know how to fix it. Any advice?
module Promptable
  def prompt(message = "What music would you like to add", symbol = ":>")
  print message
  print symbol
  gets.chomp
  end
end

class Library
  attr_accessor :artist, :song
  def initialize
    @library = {}
  end

  def add_artist(artist)
    @library[artist] = []
  end

  def add_song(song)
    @library[artist] << song
  end

  def show
    puts @library
  end
end

class Artist
  attr_accessor :name, :song

  def initialize(artist)
    @name = artist[:name]
    @song = artist[:song]
  end

  def to_s
   "#{name}, #{song}"
  end
end

if __FILE__ == $PROGRAM_NAME
  include Promptable
  include Menu
  my_library = Library.new
  my_library.add_artist(Artist.new(:name => prompt("What it the artist name    ?")))
  my_library.add_song(Artist.new(:song => prompt("What is the song name ?")))
  my_library.show
end

A: You're calling add_artist with one instance of Artist and add_song with another. When you look up the artist's list of songs in add_song with @library[artist] you're using a hash key (the second instance of Artist) which is not equivalent to the hash key under which you stored the list (the first instance of Artist), so you're not getting the list back, but nil.
To use two different instances of Artist as equivalent hash keys, you'll need to decide when two instances of Artist should be equal and implement eql? and hash appropriately.


text:
Q: Envify CLI not removing process.env.NODE_ENV I am trying to reduce the size of my React bundle.js.
I am attempting to use Envify with Browserify to replace process.env.NODE_ENV with the string "production", in order to use uglifyjs and remove all the extra development code.
Here is my command: browserify -t [envify --NODE_ENV production] assets/js/app.js -o assets/js/bundle.js
So my bundle.js is successfully created, but it still has some of the instances of process.env.NODE_ENV.
All the instances that are in my "app.js" or my other components are correctly replaced with "production".
...But in all of my required modules from the node_modules folder (like react etc), the instances are not replaced.
Any help greatly appreciated! THX!
******************* Edit **********************
JMM's solution successfully answered the original question, but I still had an issue because I am using React-Router (I think).
I created a simple example that shows the situation.
Here is my app.js file:
var React = require('react');
var ReactDOM = require('react-dom');
var Router = require('react-router').Router;
var Route = require('react-router').Route;

var Example = React.createClass({
    render: function(){
        console.log(process.env.NODE_ENV);
        if (process.env.NODE_ENV === "development") {
          console.log('Development Version');
        } else {
            console.log('Production Version');
        }
        return Hello World!;
    }
});

var AppRoutes = ( <Route name="/" path="/" component={Example} /> );

ReactDOM.render(
    (<Router>
        {AppRoutes}
    </Router>),
    document.getElementById('ExampleApp')
    );

If I run NODE_ENV=production browserify -t envify assets/js/app.js -o assets/js/bundle.js, I still have some instances of process.env.NODE_ENV in the bundle.js.
I found a work-around by simply creating the bundle.js with: browserify assets/js/app.js -o assets/js/bundle.js, and then running envify on the bundle with: NODE_ENV=production envify assets/js/bundle.js > assets/js/bundle2.js
This solves my problem, but I am still unsure why react-router doesn't allow browserify and envify to work together.
I hope this helps others with a similar problem!!

A: Browserify doesn't run transforms on stuff in node_modules. However, React has envify (actually loose-envify now) configured in its package.json. I think the reason it's not working for you is passing the environment to envify as an option (again, your invocation of envify there is not running on React). The envify docs are not good about explaining how this works. To get the production build of React you should do:
NODE_ENV=production browserify -t envify assets/js/app.js -o assets/js/bundle.js

I believe this should cause envify to function as expected on your app code and React.

A: Unfortunately JMM's answer doesn't work, because setting process.env.NODE_ENV has no effect in Browserify. The resulting bundle still has process.env.NODE_ENV references in it and hence

*

*Browserify will not require() the React production version modules,

*the minifier will not be able to remove dead code, and

*the application will still be running in debug mode.

This is unfortunately not the only place where this approach is offered as the correct answer :-(

The correct approach can be found in e.g.

*

*https://github.com/hughsk/envify/issues/15#issuecomment-62229101

*https://reactjs.org/docs/optimizing-performance.html#browserify
You need to switch the envify transform to be a global one, e.g.
# note the "-g" instead of the usual "-t"
$ browserify ... -g [ envify --NODE_ENV production ] ....

or in gulpfile.js
browserify(...)
    ...
    .transform('envify', {
        global:   true, // also apply to node_modules
        NODE_ENV: debug ? 'development' : 'production',
    })
    ...
    .bundle()
    ...
    .pipe(gulpif(!debug, babelMinify())) // my example uses gulp-babel-minify
    ...


text:
Q: Reading in a .txt file in Java I am trying to write a program which reads in a a list of nodes that interact with each other within a network. This is written in a text file in the format:
node1   node2
node1   node3
node2   node3
node3   node5

This indicates node1 interacts with node2 and node3, node 2 interacts with only node3 etc.
The program will be able to read in this file and will remove any repeated interactions and will be able to return to me the number of interactions a node has with other nodes if I input the name of the node. However, I am very new to Java and am first trying to get it to read in the file, although my code does not read in the file at the moment. Here is the code I have so far:
import java.io.File;
import java.util.Scanner;

public class ReadFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("interactions.txt");
      Scanner FileReader = new Scanner(myObj);
      while (FileReader.hasNextLine()) {
        String data = FileReader.nextLine();
        System.out.println(data);
      }
      FileReader.close();
    }
  }
}

Any help on how to solve this would be really appreciated, thank you!

A: It's probably because file doesn't exists in the location that you are looking.
You probably missed the catch clause, where you can print the exact exception.
First, try to run this:
public static void main(String[] args) throws IOException {
    try {
        File myObj = new File("interactions.txt");
        Scanner FileReader = new Scanner(myObj);
        while (FileReader.hasNextLine()) {
            String data = FileReader.nextLine();
            System.out.println(data);
        }
        FileReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

File should be at the root level of project, this might help you as well
public static void main(String[] args) throws IOException {
    try {
        File myObj = new File("interactions.txt");

        // check if file exists - if not - create
        if (myObj.createNewFile()) {
            System.out.println("File created: " + myObj.getName());
        } else {
            System.out.println("File already exists.");
        }
        Scanner FileReader = new Scanner(myObj);
        while (FileReader.hasNextLine()) {
            String data = FileReader.nextLine();
            System.out.println(data);
        }
        FileReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

A: just a little example how you can encapsulate your code for the task. Excuse my grammar please, i hope you can read it.
// extends means that the class will inherit properties of HashMap
// Parameters between <> are generics, they determinate the types
// that are used as keys and values and same goes for HashSet, It does not matter
// what you substitute here as long as its not a buildin type (so not int but
// Integer), if you dont know what hashmap is or dont understand generics, search
// it on internet
public class Network extends HashMap<String, HashSet<String>> {
        // this is a constructor as it is named the same as Class and hes not
        // return type specified. in this case we are initializin contents of the
        // map and throws specifies that this Method can fail and what it can
        // throw, this is java vay of passing errors up and leaving caller to
        // handle then.
        public Network(String filename) throws IOException {
                // This is what i hate about java and that are buffer readers
                // this isnt that bad but if you get like 4 nested to each other...
                BufferedReader reader = new BufferedReader(new FileReader(filename));

                while(true) {
                    String line = reader.readLine();
                    if(line == null) return; // null signalizes we read all lines
                    // look for dosc of String.split if you dont know what it
                    // does
                    String[] nds = line.split(" ");
                    // as you can see we can call methods of Hashmap, like
                    // computeIfAbsent, as if it was member of Network. That
                    // wierd arrow is an lambda expression, search for java lambda
                    // expressions to learn more, same goes for computeIfAbsent
                    HashSet<String> set = computeIfAbsent(nds[0], k -> new HashSet<>());
                    // Finally as ewerithing in java is pointer except some
                    // simple types we can modify set like so. Good thing about
                    // set is that i takes care of ensuring that we have no
                    // duplicates
                    set.add(nds[1]);
                }
        }

        // a simple abstraction that encapsulates logic, as i dont like returning
        // null in this case, throwing an exception makes it more obvious, though
        // of corse you might change it for better user experiance as writing try
        // catchs ewriwhare is annoying
        public int getInteractionCountFor(String nodeName) throws NoSuchElementException {
            HashSet<String> set = get(nodeName);
            if (set == null) {
                // throwing our own exception with custom message
                throw new NoSuchElementException("the network does not contain " + nodeName);
            }
            return  set.size();
        }
    }

A: Here is a full running answer if you are still interested...
For input file:
 node1   node2
 node1   node3
 node2   node3
 node3   node5
 node2   node3 <<< repeating
 node2   node6
 node1   node3 <<< repeating

The filtered output:
 node1   node2
 node1   node3
 node2   node3
 node3   node5
 node2   node6

SHORT ANSWER:
Use HashMap<String, String> and
check repeating nodes with
x_nodes.containsKey(x_key) && x_nodes.containsValue(x_value)
DETAILED ANSWER:
Copy & paste the following source:
public static char       q_TEXT_SEPARATOR            = '|';
public static int        q_MAX_TEXT_LINE_NBR         = 1000;
public static char       q_ALT_ENTER                 = '\n';
public static String     q_CUSTOM_COMMENT_CHAR       = "*";
public static String     q_CUSTOM_SPLIT_CHAR         = " ";

public static HashMap<String, String> w_nodes = new HashMap<String, String>();

public static boolean empty_line(String input) {
    boolean w_bos_bilgi = (input == null || input.equals("") || input.trim().equals(""));
    return  w_bos_bilgi;
}

public static String[] custom_split(String s) {
    return custom_split(s, q_TEXT_SEPARATOR);
}
public static String[] custom_split(String s, char   q_TEXT_SEPARATOR) {
    String[] p = new String[q_MAX_TEXT_LINE_NBR];
    for (int i = 0; i < q_MAX_TEXT_LINE_NBR; i++) {
        p[i] = "";
    }

    int totlen = s.length();
    int i = 0;
    int k = 0;
    boolean finish = false;
    while (!finish) {
        if ((k >= totlen) || (i >= q_MAX_TEXT_LINE_NBR)) {
            finish = true;
        } else {
            String w_tx = "";
            boolean finish2 = false;
            while (!finish2) {
                char c = s.charAt(k);
                if ((  c      ==      q_TEXT_SEPARATOR)  || (k > totlen) || (i == q_MAX_TEXT_LINE_NBR)) {
                    finish2 = true;
                } else {
                    if (c != q_ALT_ENTER) {
                        w_tx = w_tx + c;
                    }
                    k = k + 1;
                }
            }
            if (!empty_line(w_tx)) {
                p[i] = w_tx;
                i++;
            }
            k++;
        }
    }

    return p;
}

public static boolean existing(HashMap<String, String> x_nodes, String x_key, String x_value) {
    if ( x_nodes.containsKey(x_key) && x_nodes.containsValue(x_value) ) {return false;}
    else                                                                {return true;}
}

public static void import_nodes() {
   String q_NODES_FILENAME = "C://...//interactions.txt";

   BufferedReader q_NODES_in = null;
   try {
        q_NODES_in           = new BufferedReader(new FileReader(q_NODES_FILENAME));
   } catch (Exception e) {
        System.out.println("> WARNING : Nodes file not found !");
        return;
   }

   String w_file_str = "", w_line = "";
   while ( q_NODES_in != null && w_line != null ) {
       try {
         w_line        = q_NODES_in.readLine();
         if ( empty_line(w_line) ) {continue;}
         if ( w_line.startsWith(q_CUSTOM_COMMENT_CHAR)) {continue;}

         if  ( w_line == null || w_line.equals("null") ) {
              throw new IOException();
         }

         w_file_str   += w_line.replace(q_TEXT_SEPARATOR + "", "") + q_TEXT_SEPARATOR;
       } catch (Exception e) {
           break;
       }
   }
   try {q_NODES_in.close();} catch (Exception e) {}

   if ( empty_line(w_file_str) ) {
          System.out.println("> WARNING : Nodes file empty !");
          return;
   }

   String p[] = custom_split(w_file_str);
   for (int i = 0; i < p.length && !empty_line(p[i]); i++) {
       String w_key   = "";
       String w_node = (p[i] + " ");
       int    w_separator = w_node.indexOf(q_CUSTOM_SPLIT_CHAR);
       if   ( w_separator < 0 ) {continue;}
       else                 {w_key   = w_node.substring(0, w_separator);
                             w_node = w_node.substring(w_separator + 1);}

       if ( p[i].trim().toUpperCase().startsWith(q_CUSTOM_COMMENT_CHAR)) {continue;}                                                                                //UPD 2012/10/08

       if ( existing(w_nodes, w_key, w_node)      ) {
            w_nodes.put(w_key, w_node);
            System.out.println(w_key + " " + w_node);
       }
   }
}


text:
Q: Laravel Model Collections with multiple tables and where statement I need to get data from 2 tables using Laravel models and collections. I can do that with :
$results = Tasks::with('resource')->get();

how can i add a where statement to this? (I am trying to get all tasks where deleted=0;
//I tried $results = Tasks::with('resource')->get()->where('tasks.deleted', '!=','1');

with no luck

A: Since Tasks is the upper collection ( not nested ); you should be able to use this directly :
$results = Tasks::with('resource')->get()->where('deleted', '<>',1);

// all tasks where deleted is equal to 0
$results = Tasks::with('resource')->get()->where('deleted',0);


text:
Q: Delete a specific row from table with a list view I've a table 'itemsDataTable' and when I delete a row with:
public void deleteExpense(long idToDelete){ // Delete Expense
    Log.d(TAG, "Expense deleted with id: " + idToDelete);
    db.delete(TABLE, COLUMN_ID + " = " + idToDelete, null);
}

It mess it up.
I choose an item from list view and in a new screen I can choose to delete the row.
The _id of the row still in the table, but all of the details in the row are empty.
The position of the list view is not useful because if I delete several times, the position is not correct.
The result is something like this:
_id  some_title
1    blabla
2    blabla
3
4    blabla
5
6    blabla

Any ideas how to solve all this mess?
My list view:
ListView lvItemsHistory=(ListView)findViewById(R.id.listView1);
        final ArrayList<Expense>expensesList=new ArrayList<Expense>();
        Cursor sortCurser=MainActivity.itemsDataBase.query();

        while (sortCurser.moveToNext()) {
            expensesList.add( new Expense(
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_DESCRIPTION)),
                    sortCurser.getInt(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_PRICE)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_PAYMENT_OPTION)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_ITEM_CATEGORY)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_PHOTO_URL)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_LOCATION)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_DATE)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_TIME)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_VOICE_RECORD_URL))));
        }

        ArrayAdapter<Expense>itemsAdapter=new ArrayAdapter<Expense>(this, android.R.layout.simple_list_item_1, expensesList);
        lvItemsHistory.setAdapter(itemsAdapter);
        lvItemsHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Log.d(ItemsDataBase.TAG, "Position = " + (position + 1));
                Expense item=expensesList.get(position);
                Intent intent=new Intent(HistoryExpense.this, ShowExpense.class);
                intent.putExtra("itemName", item);
                intent.putExtra("positionExpense", position + 1);
                finish();
                startActivity(intent);
            }

        });

ShowExpense:
public class ShowExpense extends Activity {

    protected int expenseID;

    private boolean isPlay;
    private MediaPlayer mediaPlayer;
    Facebook facebook;

    private TextView tvDescription, tvPrice, tvPaymentOption, tvCategory, tvLocation, tvDate, tvTime, tvIsAudioNote;
    private ImageButton btnPlayRecordedNote, shareButton, btnShareToTwitter;
    private Button btnDeleteItem, btnExportToPDF;
    private ImageView ivItemPhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_item_activity);

        isPlay = true; // Reset so we can play the audio

        tvDescription = (TextView)findViewById(R.id.textView2);
        tvPrice = (TextView)findViewById(R.id.textView4);
        tvPaymentOption = (TextView)findViewById(R.id.textView6);
        tvCategory=(TextView)findViewById(R.id.textView8);
        tvLocation=(TextView)findViewById(R.id.textView10);
        tvDate=(TextView)findViewById(R.id.textView12);
        tvTime=(TextView)findViewById(R.id.textView14);
        ivItemPhoto=(ImageView)findViewById(R.id.imageView1);
        btnDeleteItem=(Button)findViewById(R.id.button1);
        btnExportToPDF=(Button)findViewById(R.id.button3);
        btnPlayRecordedNote=(ImageButton)findViewById(R.id.imageButton1);
        tvIsAudioNote=(TextView)findViewById(R.id.textView15);
        shareButton = (ImageButton)findViewById(R.id.imageButton2);
        btnShareToTwitter = (ImageButton) findViewById(R.id.imageButtonTwitter);

        Bundle bundle=getIntent().getExtras();
        final Expense item=(Expense)bundle.getSerializable("itemName");

        Bundle positionExpenseBundle = getIntent().getExtras();
        final int expensePosition = positionExpenseBundle.getInt("positionExpense");

        if (item.isAudioNote.equals("null") || item.isAudioNote.isEmpty()) {
            tvIsAudioNote.setText("No recorded audio note.");
        }
        else {
            tvIsAudioNote.setText("Recorded audio note saved to " + item.isAudioNote);
        }

        tvDescription.setText(item.strDescription);
        tvPrice.setText(item.strPrice+"");
        tvPaymentOption.setText(item.paymentOption);
        tvCategory.setText(item.productCategory);
        tvLocation.setText(item.isLocation);
        tvDate.setText(item.isDate);
        tvTime.setText(item.isTime);

        final String PHOTO_URL=item.photoURL+"";
        Log.i(ItemsDataBase.TAG, PHOTO_URL+"");

        if (PHOTO_URL.isEmpty() || PHOTO_URL.equals("null") || PHOTO_URL.equals(null)) {
            Log.d(ItemsDataBase.TAG, "There is no photo. Default photo will be presented.");
            int defaultImageID=R.drawable.default_item_photo;
            ivItemPhoto.setImageResource(defaultImageID);
        }
        else {

            File file=new File(PHOTO_URL);
            Log.i(ItemsDataBase.TAG, file.toString());
            if (file.exists()) {
                Log.d(ItemsDataBase.TAG, "File photo url exists");
                Bitmap bmp=BitmapFactory.decodeFile(file.getAbsolutePath());
                Log.i(ItemsDataBase.TAG, "File absolute path="+file.getAbsolutePath());
                ivItemPhoto.setImageBitmap(bmp);
            }
            else {
                Log.d(ItemsDataBase.TAG, "File photo url does not exists");
            }
        }

        btnDeleteItem.setOnClickListener(new View.OnClickListener() { // Delete Income

            @Override
            public void onClick(View v) {

                MainActivity.itemsDataBase.deleteExpense(expensePosition);
                runOnUiThread(new Runnable() {

                    public void run() {

                        AlertDialog.Builder builder=new AlertDialog.Builder(ShowExpense.this); //Notify user all is OK
                        AlertDialog completeOK=builder.setTitle("Information").setMessage("Expense deleted with id: " + (expensePosition)).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Log.d(ItemsDataBase.TAG, "Expense deleted with id: " + expensePosition);

                                finish();
                            }
                        }).create();
                        completeOK.show();
                    }
                });
            }
        });

        btnExportToPDF.setOnClickListener(new View.OnClickListener() { // Export to pdf

            @Override
            public void onClick(View v) {

                idanUtils idanUtils=new idanUtils();
                final String filename="/"+"EXPENSE_"+idanUtils.getDateAndTimeStamp()+".pdf";
                String deviceStorage=Environment.getExternalStorageDirectory().getAbsolutePath().toString();
                Log.d(ItemsDataBase.TAG, deviceStorage+filename);

                File myDir = new File(deviceStorage + "/My Wallet");
                myDir.mkdirs();
                File file=new File(myDir, filename);

                Document document=new Document();

                try {
                    PdfWriter.getInstance(document, new FileOutputStream(file));
                    document.open();
                    document.add(new Paragraph("Item description: "+item.strDescription));
                    document.add(new Paragraph("Paid by: "+item.paymentOption));
                    document.add(new Paragraph("Category: "+item.productCategory));
                    document.add(new Paragraph("Price: "+item.strPrice));
                    document.add(new Paragraph("Bught at: "+item.isLocation));
                    document.add(new Paragraph("Dated: "+item.isDate));
                    document.add(new Paragraph("Time: "+item.isTime));

                    if (PHOTO_URL.isEmpty() || PHOTO_URL.equals("null")) {
                        document.add(new Paragraph("No image available"));
                        Log.i(ItemsDataBase.TAG, "No image available");
                    } else {
                        Image image=Image.getInstance(item.photoURL);
                        image.scaleAbsolute(200f, 200f);
                        document.add(image);
                    }

                } catch (Exception e) {
                    String error=(e.getMessage()==null)?"Error adding information to PDF document":e.getMessage();
                    Log.e(ItemsDataBase.TAG, error);
                }
                document.close();

                runOnUiThread(new Runnable() {

                    public void run() {

                        AlertDialog.Builder builder=new AlertDialog.Builder(ShowExpense.this); //Notify user all is OK
                        AlertDialog completeOK=builder.setTitle("Information").setMessage(filename+" saved to /My Wallet folder on your internal storage.").setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Log.d(ItemsDataBase.TAG, filename+" saved to /My Wallet folder on your internal storage.");
                            }
                        }).create();
                        completeOK.show();
                    }
                });
            }
        });

        btnPlayRecordedNote.setOnClickListener(new View.OnClickListener() { // Play recorded audio note

            @Override
            public void onClick(View v) {

                if (isPlay) { // Play
                    mediaPlayer=new MediaPlayer();
                    try {
                        mediaPlayer.setDataSource(item.isAudioNote);
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                    } catch (IllegalArgumentException e) {
                        Log.e(ItemsDataBase.TAG, e.getMessage());
                    } catch (IllegalStateException e) {
                        Log.e(ItemsDataBase.TAG, e.getMessage());
                    } catch (IOException e) {
                        Log.e(ItemsDataBase.TAG, e.getMessage());
                    }
                    isPlay = false;
                } else{ // Stop
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    isPlay = true;
                }

                //              MediaPlayer mediaPlayer=new MediaPlayer();
                //              try {
                //                  mediaPlayer.setDataSource(item.isAudioNote);
                //                  mediaPlayer.prepare();
                //                  mediaPlayer.start();
                //              } catch (IllegalArgumentException e) {
                //                  Log.e(ItemsDataBase.TAG, e.getMessage());
                //              } catch (IllegalStateException e) {
                //                  Log.e(ItemsDataBase.TAG, e.getMessage());
                //              } catch (IOException e) {
                //                  Log.e(ItemsDataBase.TAG, e.getMessage());
                //              }
                // TODO - On Key Press Back - STOP PLAY THE AUDIO NOTE
                //              mediaPlayer.stop();
                //              mediaPlayer.release();
            }
        });

        btnShareToTwitter.setOnClickListener(new View.OnClickListener() { // Share to Twitter

            @Override
            public void onClick(View v) {

                String tweetUrl = "https://twitter.com/intent/tweet?text=";
                String text = "Hi, just twitting from My Wallet app! I just spent " + item.strPrice + " to buy " + item.strDescription;
                Uri uri = Uri.parse(tweetUrl + text);
                startActivity(new Intent(Intent.ACTION_VIEW, uri));
            }
        });

        shareButton.setOnClickListener(new View.OnClickListener() { // Share on Facebook

            @Override
            public void onClick(View v) {
                FacebookConnect.message = "Hi! Just saying hello from My Wallet app! I just spent " + item.strPrice + "$ to buy " + item.strDescription + "!";
                FacebookConnect.postStatusUpdate();
                Intent fbIntent = new Intent(ShowExpense.this, FacebookConnect.class);
                startActivity(fbIntent);
                Log.d(ItemsDataBase.TAG, FacebookConnect.message);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.show_item_activity, menu);
        return true;
    }

}

A: Delete row in database table given one column value - which is a string

A: Try passing the ID like this:
db.delete(TABLE, COLUMN_ID + " =?", new String[] { idToDelete });

If idToDelete is an int/Integer:
db.delete(TABLE, COLUMN_ID + " =?", new String[] { String.valueOf( idToDelete ) } );


text:
Q: How do i get the row Count from my Database after i've scaffolded it with EntityFrameworkCore i'm trying to learn how to work with entityframeworkCore for an academic project and i'm stuck at manipulating my scaffolded database as it is (in c#) .
for example i'm making a simple REST api that will retrun the number of people in my database (Sql-Server).
  [HttpGet("(Id)")]
    public String GetAdminList(int Id)
    {

        return "get me "+Id+" admins !";
    }

*

*

public class IndexModel : PageModel
{
    private readonly RAZORING.Models.DBContextClass _context;

    public IndexModel(RAZORING.Models.DBContextClass context)
    {
        _context = context;
    }

    public IList<AdmUser> AdmUser { get;set; }

    public async Task OnGetAsync()
    {
        AdmUser = await _context.AdmUsers
            .Include(a => a.AdmUserAdmRoleFk1Navigation)
            .Include(a => a.AdmUserCfgTierFk1Navigation).ToListAsync();
    }
}

this is the indexModel for the razor page that lists the table in question
the Scaffolded database is in an other project in the same solution and i have referenced it but i don't even know where to begin to be able to manipulate the tables, i have made a razor mvs webApp to confirm that it works but that's it.
Any help would be much appreciated even with a documentation as i haven't found much information online

A: The number of AdmUsers in the database would be given by:
_context.AdmUsers.Count();

EF will take this LINQ and translate it to SELECT COUNT(*) FROM AdmUsers
You don't "manipulate tables" per se; you treat things as collections of entities, and leave EF to worry about "manipulating tables" (creating SQL that manipualtes data in tables). This "manipulates a table [entity]" for example:
var u = _context.admUsers.Find(1234); //retrieve user 1234
u.FirstName = "Hello"; //change name
_context.SaveChanges(); //write new name to db. note, if you're in a position to be using async, then `await _context.SaveChangesAsync()` may be better

This works because when you download user 1234, EF keeps track of it. If you change its properties, EF will see the changes and can save them
Many things that you can do with LINQ will be translated to queries. Getting all the users in a city:
var usrs = _context.Users.Where(u => u.City == "Chicago").ToArray();

//probably becomes SELECT * FROM Users WHERE City = 'Chicago'

Move everyone to new york:
foreach(var u in usrs)
  u.City = "New York";
_context.SaveChanges();

Sometimes EF can't translate the expressions you use, so you'll get an error:
var twentyYrOlds = _context.Users.Where(u => u.Age.ToString("00").Substring(0, 1) == "2").ToArray();

Here it's quite likely (I'll never say never) that EF couldn't translate the ToString with formatting, and subsequent substring to the SQL equivalent. You need to write the query in a different way that it can translate:
var twentyYrOlds = _context.Users.Where(u => u.Age >= 20 && u.Age < 30).ToArray();


text:
Q: Route the traffic over specific interface for a process in linux Is it possible to route the traffic used by a process over a specific interface?
For example, network traffic by download application should always use the interface wlan0 whereas all other applications on the machine should use eth0.
Is it possible to have this kind of rule in Linux?

A: A few people have written shims that use the LD_PRELOAD feature of Linux to achieve this:

*

*force_bind

*Binding applications to a specific IP

A: Combining the excellent answers of mariusmatutiae and KrisWebDev I have created an extensively modified version KrisWebDev's excellent novpn.sh script. Whereas KrisWebDev's script is designed to scratch a more specific itch (running and moving processes inside/outside a VPN), my version allows you to run basically any command in a networking environment you specify. You can specify the interface to bind to, the default route, specify your own iptables rules, static routes, specify a "test" to confirm everything is operating as you desire before running the command... etc). It allows you to use multiple config files so that you can define any number of specific networking environments that you can run commands/processes inside of.
I posted it as a gist here:
https://gist.github.com/level323/54a921216f0baaa163127d960bfebbf0
It can even clean up the cgroup/iptables/routing tables afterwards!
Feedback welcome.
PS - It's designed for Debian 8 (Jessie)

A: I have sooo struggled with this so here's a COMPLETE solution. It's tested on Ubuntu 15 to 19.10. You can especially use it with OpenVPN to route certain apps outside the VPN tunnel interface.
The complete "cgroup" solution
How that works?

*

*Linux kernel will put the app into a control group. Network traffic from apps in this cgroup will be identified by their class ID at the network controller level.

*iptables will mark this traffic and force it to exit with the right IP

*ip route will process marked traffic in a different routing table, with a default route to whatever gateway IP you want.

Automated script
I've made a novpn.sh script to automate dependencies install & run. Tested on Ubuntu 15 to 19.10.
Start your VPN first.
wget https://gist.githubusercontent.com/kriswebdev/a8d291936fe4299fb17d3744497b1170/raw/novpn.sh
# If you don't use eth0, edit the script setting.
sudo chmod +x novpn.sh
./novpn.sh traceroute www.google.com
./novpn.sh --help

Manual HowTo
First, install cgroup support and tools:
sudo apt-get install cgroup-lite cgroup-tools

You need iptables 1.6.0+. Get iptables 1.6.0  release source, extract it, then run this (--disable-nftables flag will avoid errors) from iptables source dir:
iptables --version
sudo apt-get install dh-autoreconf bison flex
./configure --prefix=/usr      \
            --sbindir=/sbin    \
            --disable-nftables \
            --enable-libipq    \
            --with-xtlibdir=/lib/xtables
make
sudo make install
iptables --version

Now, the real config. Define a control group named novpn. Processes in this cgroup will have a classid of 0x00110011 (11:11).
sudo su
mkdir /sys/fs/cgroup/net_cls/novpn
cd /sys/fs/cgroup/net_cls/novpn
echo 0x00110011 > net_cls.classid

Now, we'll suppose the real interface you want to use for the specific app is eth0 with a gateway IP of 10.0.0.1. REPLACE these by what you really want (get the info from ip route), especially in newer Ubuntu versions where interfaces have weird names. Run still as root:
# Add mark 11 on packets of classid 0x00110011
iptables -t mangle -A OUTPUT -m cgroup --cgroup 0x00110011 -j MARK --set-mark 11

# Force the packets to exit through eth0 with NAT
iptables -t nat -A POSTROUTING -m cgroup --cgroup 0x00110011 -o eth0 -j MASQUERADE

# Define a new "novpn" routing table
# DO THIS JUST ONCE !
echo 11 novpn >> /etc/iproute2/rt_tables

# Packets with mark 11 will use novpn
ip rule add fwmark 11 table novpn

# Novpn has a default gateway to the interface you want to use
ip route add default via 10.0.0.1 table novpn

# Unset reverse path filtering for all interfaces, or at least for "eth0" and "all"
for i in /proc/sys/net/ipv4/conf/*/rp_filter; do echo 0 > $i; done

Finally, run your app on the specific interface:
exit
sudo cgcreate -t $USER:$USER -a $USER:$USER -g net_cls:novpn
cgexec -g net_cls:novpn traceroute www.google.com
# Close all Firefox windows first
killall firefox; cgexec -g net_cls:novpn firefox

Or if you want to move an already running process to the cgroup, well... you can't! That seems to be due to the NAT (masquerade) function: iptables -nvL -t nat doesn't match when the cgroup is switched, but iptables -nvL -t mangle does match.
# Get PID of the process (we'll then suppose it's 1234)
pidof firefox
# Add to cgroup - THIS DOESN'T WORK! Silently fails to produce the final result.
sudo echo 1234 > /sys/fs/cgroup/net_cls/novpn/tasks
# Remove - but this works...
sudo echo 1234 > /sys/fs/cgroup/net_cls

Credits: No answer were working as expected, but a mix of them did: chripell answer evolware article Per process routing take 2: using cgroups, iptables and policy routing, How do I make a specific process NOT going through a OpenVPN connection?, Kill switch for OpenVPN on the basis of iptables
Related question: iptables and cgroups v2 (netfilter's xt_cgroup)

A: It can be done using Linux Network Namespaces.
Here is an article that explains how. Basically you create a network namespace with a different default route and run the processes that need it there. You connect the newly created network namespace to the physical adapter with a bridge (but other solutions are possible of course).
Update: from kernel 3.14 it's even easier using control groups, as described in this article. You have to:
1) define a net_cls control group to annotate the packets from a given process with a classid (or group of process, note that there hasn't to be any parent-child relationship between them)
2) use the iptables cgroup module (added in Linux 3.14) to fwmark the packets
3) use policy routing (ip rule add fwmark ....) to create a new routing table for the marked packets
The advantage is that we don't have to do the bridging thing and everything is much more dynamic thanks s to cgroups.


text:
Q: Madlib - Our advice to the newly-weds is to (verb) your (verb) (adjective plural) as much as possible We have been invited to a wedding this fall, and in order to RSVP we have been asked to complete a Mad Lib for the couple.
I've hit a snag.
The sentence that is stumping us is
"Our advice to the newly-weds is to make sure to always (verb) your (verb)(adjective plural) as much as possible."
The first (verb) is fairly easy, although the second (verb) followed by (adjective plural) is frustrating me to no end. Is this something that should even be able to work? If so, what am I not understanding?
Also ANY suggestions to help us finish this would be appreciated.
"Mad Libs is a phrasal template word game where one player prompts others for a list of words to substitute for blanks in a story, before reading the – often comical or nonsensical – story aloud. The game is frequently played as a party game or as a pastime."

A: The suggested sentence

Our advice to the newly-weds is to make sure to always (verb) your (verb)(adjective plural) as much as possible

is problematic because your must be followed by a noun phrase. A verb certainly doesn't fit in that position. And "adjective plural" is meaningless because adjectives don't inflect for number in the way that French adjectives do, for example.
I surmise that the sentence is intended to be

Our advice to the newly-weds is to make sure to always (verb) your (adjective-from-verb)(adjective)(plural noun) as much as possible.

That interpretation would admit of something like

Our advice to the newly-weds is to make sure to always clean your renowned shiny kettles as much as possible.
Our advice to the newly-weds is to make sure to always oil your squeaking bed springs as much as possible.

Presumably if all you need to do is to provide a humorous sentence which fits a general pattern, any such sentence which vaguely satisfies the criteria will suffice. You might not even need a verb-derived adjective and perhaps many shiny kettles would be acceptable.
However, given that "(adjective plural)" is really problematic, good advice — probably the best advice — is, unfortunately, to ask those who devised the sentence to clarify what they meant. If everyone has the same requirement, maybe you could consult with other invitees to see how they have interepreted it.


text:
Q: User input to change time of notification I am writing a app, one of the features is that it delivers a notification at a set time. That time being 7am. Recently however I wanted to add a notification customize menu, Allowing you to change the time that notifications fire.
current code snippet: (Indents are correct in  code, Formatting them correctly here is difficult)
        val TTT = sharedPreferences.getInt("noti1", 7)

        val calendar: Calendar = Calendar.getInstance()
        calendar.timeInMillis = System.currentTimeMillis()
        calendar.set(Calendar.HOUR_OF_DAY, TTT)
        calendar.set(Calendar.MINUTE, 0)
        if (calendar.timeInMillis < System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_MONTH, 1)
        }
        val mIntent = Intent(this, MyReceiver::class.java)

        val mPendingIntent = PendingIntent.getBroadcast(
                    this, 1, mIntent, PendingIntent.FLAG_IMMUTABLE
                )
        val mAlarmManager = this
                .getSystemService(Context.ALARM_SERVICE) as AlarmManager
                mAlarmManager.setRepeating(
                AlarmManager.RTC_WAKEUP, calendar.timeInMillis, 1000*60*60*24, mPendingIntent,
                )

The variable TTT, is a int and is the time that the notification should fire. It can be selected by the user in another activity and is then saved in shared prefs and got here to be used.
The receiver file is the code that runs the notification.
When the TTT value hasn't been set, or is just set to a integer, It works fine and repeats fine. However when the value is set by the user, It doesn't work at all. No notifications fire, or they occasionally work but still at the default time (7am).
Is there any way to make this code work so that the notification can fire daily, at whatever time the user sets?
All help is appreciated :)
Edit:
Here is how I went about processing the value set by the user.

                val dropdown = dialog.findViewById<Spinner>(R.id.spinnyboi)
                val items = arrayOf("5:00", "6:00", "7:00", "8:00", "9:00", "10:00", "11:00", "12:00", "13:00")
                val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, items)
                dropdown?.adapter = adapter //applys list of items

                val timeAA = sharedPreferences.getString("notifA", "7:00") //gets shared prefs for the spinner

                //I gave up here, converts string value (got from dropdown) to needed int (time) based on the items position
                if (timeAA == "5:00") {
                    val shit = 0
                    dropdown.setSelection(shit)
                    val noti1 = getSharedPreferences("settings", MODE_PRIVATE).edit()
                    noti1.putInt("noti1", 5)
                    noti1.apply()
                }else if (timeAA == "6:00") {
                    val shit = 1
                    dropdown.setSelection(shit)
                    val noti1 = getSharedPreferences("settings", MODE_PRIVATE).edit()
                    noti1.putInt("noti1", 6)
                    noti1.apply()

(so on)

And here is another process used to save spinner state and save the shared pref.
                //gets the position of selected and then saves it
                dropdown.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(
                        parent: AdapterView<*>,
                        view: View,
                        pos: Int,
                        id: Long
                    ) {
                        val item = parent.getItemAtPosition(pos)

                        apply.setOnClickListener {
                            val timeA = getSharedPreferences("settings", MODE_PRIVATE).edit()
                            timeA.putString("notifA", item as String?)
                            timeA.commit()
                        }

                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                })

A: From the code you provided, there are 2 points worth noticing:
The first thing is when the user has selected an item in the drop down list, and after that has clicked on apply, it will set the time String to notifA in SharedPreferences. However, will it also set the Int value noti1 you are using for the alarm? Because for this piece of code:
if (timeAA == "5:00") {
    ... // Better rename your variable
    val noti1 = getSharedPreferences("settings", MODE_PRIVATE).edit()
    noti1.putInt("noti1", 5)
    noti1.apply()
} else if (timeAA == "6:00") {
    ... // Better rename your variable
    val noti1 = getSharedPreferences("settings", MODE_PRIVATE).edit()
    noti1.putInt("noti1", 6)
    noti1.apply()
} ...

If you just put it in like onCreate(), it will just be triggered when the Activity is shown. There will not be any update after the user has chosen a new time String from drop down list and click on apply. So, you may have to consider setting noti1 inside the OnClickListener if the above code is not being called.
The second thing is that, assume your noti1 in SharedPreferences is correctly updated through drop down list, will it cancel the previous set alarm and set another alarm with the updated time? You may have to consider calling the function again after the user has selected from the drop down list to reset for an updated alarm.

Update an alarm
And if you would like to update an alarm with new time, when you are creating the PendingIntent, use flag FLAG_CANCEL_CURRENT:

Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.

So you should have your PendingIntent created like this:
// Change PendingIntent.FLAG_IMMUTABLE to PendingIntent.FLAG_CANCEL_CURRENT
val mPendingIntent = PendingIntent.getBroadcast(
    this, 1, mIntent, PendingIntent.FLAG_CANCEL_CURRENT
)

And then you can call the above code again to update alarm with the new time.
And make sure the second parameter of the function PendingIntent.getBroadcast() is the same when recreating the alarm.
public static PendingIntent getBroadcast (Context context,
                int requestCode,
                Intent intent,
                int flags)

A different requestCode will create another alarm event instead.
Cancel an alarm
Meanwhile you can also cancel the alarm first and create another alarm later if you want to.
And you should make sure you have the variable holding this PendingIntent:
val mPendingIntent = PendingIntent.getBroadcast(
    this, 1, mIntent, PendingIntent.FLAG_IMMUTABLE
)

And you can call AlarmManager.cancel(PendingIntent) to cancel the alarm:
mAlarmManager.cancel(mPendingIntent)


text:
Q: Can't debug expo project on vscode I have an expo project, which we can run and build and it works correctly in android and iOS. What I want is to debug said project using my Visual Studio Code.
I followed some guides and tried the following:

*

*Adding React Native Tools extension in vscode.

*Adding the "Attach to packager" configuration in the vscode
debugger.

*Changing the "react-native.packager.port" in settings.json to match
the expo packager port (19001)

*Running expo (expo start)

*And tried to start the debugger with "Debug JS remotely" both
enabled and disabled and also with the chrome debugger open or closed

The result I get is the small window with the debugger controls appears for a second and then dissapears, without any logs or evidence that it did something. I checked the terminal tab, the output tab and the debug console tab in vscode
By the way, when I enable "Debug JS remotely" the chrome debugger does launch and works perfectly.
My launch.json was autogenerated by the react native tools extension. I also tried adding "sourceMaps":true to the attach configuration and the end result was the same. Here is my code:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
    {
        "name": "Debug Android",
        "cwd": "${workspaceFolder}",
        "type": "reactnative",
        "request": "launch",
        "platform": "android"
    },
    {
        "name": "Debug iOS",
        "cwd": "${workspaceFolder}",
        "type": "reactnative",
        "request": "launch",
        "platform": "ios"
    },
    {
        "name": "Attach to packager",
        "cwd": "${workspaceFolder}",
        "type": "reactnative",
        "request": "attach"
    },
    {
        "name": "Debug in Exponent",
        "cwd": "${workspaceFolder}",
        "type": "reactnative",
        "request": "launch",
        "platform": "exponent"
    }
]

}
Just in case you need it, the OS is Ubuntu 16.04
Thanks in advance!

A: Here is a .vscode/launch.json file with a single Attach to packager config.
Notice that the port property is set to 19001.
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Attach to packager",
            "cwd": "${workspaceFolder}",
            "type": "reactnative",
            "request": "attach",
            "port": "19001",
            "sourceMaps": true
        }
    ]
}

To debug your app, first start the expo packager, using the vscode console:
npm run start
Then start the "Attach to packager" debugger profile. In the Debug Console window, you should see that the debugger is now attached to the packager.
Finally go back to the console and launch your app on the desired target.
i.e: 'a' for android.
Instead of seeing a new react-native debug tab opening in your browser, you should now see that the debugger is connected in vscode.

A: Thanks Loupi & Bharat Lalwani your answers really helped me, and I want to post a more updated and detailed answer.

*

*Install React Native Tools

*Add Attach to packager config to .vscode/launch.json (Create the file if not exist)
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
    {
        "name": "Attach to packager",
        "cwd": "${workspaceFolder}",
        "type": "reactnative",
        "request": "attach",
        "port": "19000", //Port number may be different in your machine
        "sourceMaps": true
    }
]

*Edit vscode settings file to add "react-native-packger.port": 19000 //same port in the previous step
vscode settings files locations:

*

*Windows %APPDATA%\Code\User\settings.json

*macOS $HOME/Library/Application Support/Code/User/settings.json

*Linux $HOME/.config/Code/User/settings.json

*run expo start and find the correct port in the terminal (in my case it's 19000 update the port in steps 2&3 if yours is different, step the app and re-run expo start )

*open the debug menu and click attach to packager

*go back to terminal and press a to start the app in android emulator (make sure that the emulator is already running from AVD manager), if the emulator stuck on a white screen go to terminal press r to reload the app

*if no breakpoints where hit, make sure that Debug remote JS is enabled in your emulator, while the app is running in the emulator press CTRL+M and select    Debug remote JS
Note: to start a new debugging session, first make sure to stop expo server using CTRL+C in the terminal and disconnect the debugger in vs code as in the following screenshot, you may also need to close the running app in emulator first

Remember to close debugger-ui tab in the browser before attaching the debugger in vscode

A: I have done all changes as Loupi mentioned.
But for me worked for Port no. 19000.
I have to set both settings.json & launch.json port as "port" : "19000".
Here is the code snippet for the below images:-
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug Direct iOS - Experimental",
            "request": "launch",
            "type": "reactnativedirect",
            "cwd": "${workspaceFolder}",
            "platform": "ios"
        },
        {
            "name": "Debug iOS",
            "cwd": "${workspaceFolder}",
            "type": "reactnative",
            "request": "launch",
            "platform": "ios"
        },
        {
            "name": "Attach to packager",
            "cwd": "${workspaceFolder}",
            "type": "reactnative",
            "request": "attach",
            "port" : "19000",
            "sourceMaps": true
        }
    ]
}


text:
Q: Detection of abnormally rapid jumps in the graph I have some problems with detect fast up moving curve in dataset.
Example of dataset:
6500 (integer value), 2013-04-16 15:31 (date time value or timestamp in milliseconds)
6480, 2013-04-16 15:31
6480, 2013-04-16 15:32
6450, 2013-04-16 15:33
6430, 2013-04-16 15:34
6410, 2013-04-16 15:35
...
2110, 2013-04-26 1:56
This array of data forms a graph:

I need help with the detection of abnormally rapid jumps in the graph, for example - detect the start and end points of lines that are painted black:

Best solution, as it seemed to me - use gradients or local maxima and minima, but I do not understand how to apply it to solve this problem.
I would be grateful for any hint or for any piece of code algorithm (in any languages), thanks.

A: All your rapid jumps are jumps up rather than jump down.  If you data set is V[i] for 0<=i<n, you just need to look at whether V[i] - V[i-1] > T where T = some threshhold to detect the jump.  So it's all a question about how to set the T.  I'd suggest that the threshold also varies, so it's T[i] rather than a fixed number T.  For example, you could make T[i] = M C[i] where C[i] is an exponentially weighted moving average of the recent changes, i.e.
C[i] = C[i-1] * (1 - W) + W * Abs(V[i-1] - V[i-2])
Here, if W=1, then C[i] is always the most recent change, but with W<1 it does an average of recent changes, with the most recent change carrying the most weight.  The multipler M could be e.g. 2, meaning you're looking for double the jump of the exponentially weighted moving average of the recent changes.  Something along those lines should work :-)


text:
Q: How to run systemctl command inside ExecStart? I am trying to restart all the stale sqlrelay connection services using systemd.timer. Systemd service looks like this:
[Unit]
Description=sqlrelay-state-connection-restart

[Service]
Type=oneshot
User=sqlrelay
ExecStart=/bin/ps -eo pid,etimes,cmd  | /bin/awk '$2 >=100 && $3=="sqlr-connection"  {printf "sqlrelay@%s.target\n", $9}' | /usr/bin/sudo /bin/xargs -r /bin/systemctl restart

Timer:
[Timer]
OnCalendar=*-*-* *:0/5:0

[Install]
WantedBy=timers.target

I have added sqlrelay user with Nopasswd in sudoers file.
Timer starts properly without any errors. But with the service, it's not loaded. In the logs I see this:
Apr 23 23:10:00 ****.com systemd[1]: sqlrelay-stale-restart.service failed to run 'start' task: Operation not supported
Apr 23 23:10:00 ****.com systemd[1]: Failed to start sqlrelay-state-connection-restart.
Apr 23 23:15:00 ****.com systemd[1]: sqlrelay-stale-restart.service: main process exited, code=exited, status=1/FAILURE
Apr 23 23:15:00 ****.com systemd[1]: Failed to start sqlrelay-state-connection-restart.
Apr 23 23:15:00 ****.com systemd[1]: Unit sqlrelay-stale-restart.service entered failed state.
Apr 23 23:15:00 ****.com systemd[1]: sqlrelay-stale-restart.service failed.

Sometimes I get operation not permitted with sqlrelay user.
If I remove the sqlrelay user, to allow it to run as root, I get 'Unit entered failed state' error

A: I fixed it by putting them in a Bash script and call the script from ExecStart.
The problem here is pipe command should not be used directly with ExecStart. We have to use subshell
Example:
ExecStart=/bin/sh -c 'ps -eo ...| ....|.. '

A: The value of the ExecStart key in the .INI file is not shell script.
Further reading

*

*Lennart Poettering et al. (2019).  "COMMAND LINES".  systemd.service.  systemd manual pages.