text:
Q: What is the transition time for "scroll-behavior: smooth" We know what "scroll-behavior: smooth" does, but what is the default transition time for this behavior? Or is it relative?

A: The specification says

The scrolling box is scrolled in a smooth fashion using a
user-agent-defined timing function over a user-agent-defined period of
time. User agents should follow platform conventions if any.

Right away that makes it a complicated question to which there is likely no answer, or at least no answer which will reliably stay put.
Browsers might

*

*Aim for a target speed rather than duration, and so scroll for a longer period of time if there are several pages to scroll.

*Adjust the scrolling behaviour if many nested scrolling panels are scrolling at once, such as sequencing them one after another (I see some code in Chromium which might be doing something like this)

*Allow it to be user-configurable, so people with poor vision or motion sickness can tweak it to their liking, or disable it

*Defer to the operating system, which might have its own quirks and customizations

*Change any of this with no notice, or the underlying OS might

Here is an excerpt of a comment in some Firefox code to do with smooth scrolling. I did not dig in to whether this is actually strictly relevant to the sorts of scroll you are doing, but it gives an idea:

|Smooth| scrolls have a symmetrical acceleration and deceleration curve modeled with a set of splines that guarantee that the destination will be reached over a fixed time interval.  |Smooth| will only be smooth if smooth scrolling is actually enabled. This behavior is utilized by keyboard and mouse wheel scrolling events.

|SmoothMsd| implements a physically based model that approximates the behavior of a mass-spring-damper system. |SmoothMsd| scrolls have a non-symmetrical acceleration and deceleration curve, can potentially overshoot the destination on intermediate frames, and complete over a variable time interval. |SmoothMsd| will only be smooth if cssom-view smooth-scrolling is enabled.

And here is a little bit of code you can use to test for yourself. In my experimentation I'm seeing the duration varying based on how far it scrolls, both in Firefox and Chromium, and I'm seeing different speeds in each of those.

const qs = document.querySelector.bind(document);

const viewportHeightInput = qs("#viewport-height");
const contentHeightInput = qs("#content-height");
const viewport = qs("#viewport");
const content = qs("#content");
const output = qs("#output");

function update() {
  viewport.style.height = `${viewportHeightInput.value}px`;
  content.style.height = `${contentHeightInput.value}px`;
}
update();

viewportHeightInput.addEventListener("input", update);
contentHeightInput.addEventListener("input", update);

qs("#to-top").addEventListener("click", () => {
  start = performance.now();
  scrollEvents = 0;
  updateScrollEvents();
  viewport.scrollTo({
    behavior: "smooth",
    top: 0,
  })
});
qs("#to-bottom").addEventListener("click", () => {
  start = performance.now();
  scrollEvents = 0;
  updateScrollEvents();
  viewport.scrollTo({
    behavior: "smooth",
    top: viewport.scrollHeight - viewport.clientHeight,
  })
});

const scrollEventsOutput = qs("#scroll-events");
const elapsedOutput = qs("#elapsed");
let scrollEvents = 0;
let start = performance.now();
let last = null;
viewport.addEventListener("scroll", () => {
  last = performance.now();
  scrollEvents++;
  updateScrollEvents();
});

function updateScrollEvents() {
  scrollEventsOutput.value = scrollEvents;
  elapsedOutput.value = last == null ? 0 : last - start;
}
#controls {
  display: grid;
  grid-template-columns: 10rem 1fr;
}

#controls fieldset {
  display: contents;
}

#viewport {
  overflow: auto;
  border: thick solid orange;
  margin: 4rem 0;
}

#content {
  background-image: linear-gradient(to bottom left, black, white);
  position: relative;
}

#content::before,
#content::after {
  position: absolute;
  left: 0;
  background-color: black;
  color: white;
  display: block;
}

#content::before {
  content: "start";
  top: 0;
}

#content::after {
  content: "end";
  bottom: 0;
}

  <fieldset>
    Viewport height
    <input id="viewport-height" type="number" min="1" value="400">
  </fieldset>
  <fieldset>
    Content height
    <input id="content-height" type="number" min="1" value="1000">
  </fieldset>
  <fieldset>
    Triggers

<button id="to-top">Scroll to top</button>

<button id="to-bottom">Scroll to bottom</button>

  </fieldset>
  <fieldset>
    Scroll events
    <input id="scroll-events" type="number" readonly value="0">
  </fieldset>
  <fieldset>
    Milliseconds between start of scroll and last scroll event
    <input id="elapsed" type="number" readonly value="0">
  </fieldset>


text:
Q: gcc заставляет использовать 11 стандарт? В gcc возникает странная ошибка, когда пытаюсь скомпилировать этот код. В clang такого нет. В чём проблема?

#error This file requires compiler and library support for the ISO C++ 2011 standard. This support must be enabled with the -std=c++11 or
  -std=gnu++11 compiler options.

#include <random>

int main() {
    int x; //Почему тут ошибка??/
    x = 0x42; // <--
}

A: В коде используется заголовочный файл <random>, характерный для стандарта c++11 и выше, потому и наблюдается упомянутая ошибка. Дополнительно в коде имеются приколы с триграфами (которые, кстати, в с++17 уже запретили), может это тоже косвенно дало причину думать, что ошибка не там, где она действительно есть.
По поводу того, на каком основании clang собирает код с <random> при режиме -std=c++98 задал вопрос на enSO Enforcing C++98/03 for clang. В комментариях люди выражают уверенность, что это баг clang.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas. Picking a column name based on row data In my previous question, i was trying to count blanks and build a dataframe with new columns for the subsequent analysis. The question became too exhaustive and i decided to split it for different purposes.
I have my initial dataset:
import pandas as pd
import numpy as np

df = pd.DataFrame({'id':[1000,2000,3000,4000],
               '201710':[7585,  4110,   4498,   np.nan],
               '201711':[7370,  3877,   4850,   4309],
               '201712':[6505,    np.nan,   4546,   4498],
               '201801':[7473,    np.nan,     np.nan,   4850],
               '201802':[6183,    np.nan,     np.nan,   np.nan ],
               '201803':[6699,  4558,   1429,   np.nan ],
               '201804':[ 118,  4152,   1429,   np.nan ],
               '201805':[  np.nan,  4271,   1960,   np.nan ],
               '201806':[  np.nan,    np.nan,   1798,   np.nan ],
               '201807':[  np.nan,    np.nan,   1612,   4361],
               '201808':[  np.nan,    np.nan,   1612,   4272],
               '201809':[  np.nan,  3900,   1681,   4199] ,

               })

I need to obtain start- and end- dates of each fraction (not blank) for each id.
I managed to get the first occurred start- and the last occurred end- data but not in the middle. An then, I counted blanks for each gap (for further analysis)
The code is here (it's might seem confused):
# to obtain the  first and  last occurrence with data
res = pd.melt(df, id_vars=['id'], value_vars=df.columns[1:])
res.dropna(subset=['value'], inplace=True)
res.sort_values(by=['id', 'variable', 'value'], ascending=[True, True, True],
inplace=True)

minimum_date = res.drop_duplicates(subset=['id'], keep='first')
maximum_date = res.drop_duplicates(subset=['id'], keep='last')

minimum_date.rename(columns={'variable': 'start_date'}, inplace=True)
maximum_date.rename(columns={'variable': 'end_date'}, inplace=True)

# To obtain number of gaps (nulls) and their length
res2 = pd.melt(df, id_vars=['id'], value_vars=df.columns[1:])
res2.sort_values(by=['id', 'variable'], ascending=[True, True], inplace=True)
res2=res2.replace(np.nan, 0)
m = res2.value.diff().ne(0).cumsum().rename('gid')
gaps = res2.groupby(['id',
m]).value.value_counts().loc[:,:,0].droplevel(-1).reset_index()

# add columns to main dataset with start- and end dates and gaps
df = pd.merge(df, minimum_date[['id', 'start_date']], on=['id'], how='left')
df = pd.merge(df, maximum_date[['id', 'end_date']], on=['id'], how='left')

I came to the dataset like this, where start_date is the 1st notnull occurrence, end_date - the last notnull occurence and 1-,2-,3- blanks are fractions with blanks counting for further analysis:

The output is intended to have additional columns:

A: Here is a function that may be helpful, IIUC.
import pandas as pd

# create test data
t = pd.DataFrame({'x': [10, 20] + [None] * 3 + [30, 40, 50, 60] + [None] * 5 + [70]})

Create a function to find start location, end location, and size of each 'group', where a group is a sequence of repeated values (e.g., NaNs):
def extract_nans(df, field):
    df = df.copy()

    # identify NaNs
    df['is_na'] = df[field].isna()

    # identify groups (sequence of identical values is a group):  X Y X => 3 groups
    df['group_id'] = (df['is_na'] ^ df['is_na'].shift(1)).cumsum()

    # how many members in this group?
    df['group_size'] = df.groupby('group_id')['group_id'].transform('size')

    # initial, final index of each group
    df['min_index'] = df.reset_index().groupby('group_id')['index'].transform(min)
    df['max_index'] = df.reset_index().groupby('group_id')['index'].transform(max)

    return df

Results:
summary = extract_nans(t, 'x')
print(summary)

       x  is_na  group_id  group_size  min_index  max_index
0   10.0  False         0           2          0          1
1   20.0  False         0           2          0          1
2    NaN   True         1           3          2          4
3    NaN   True         1           3          2          4
4    NaN   True         1           3          2          4
5   30.0  False         2           4          5          8
6   40.0  False         2           4          5          8
7   50.0  False         2           4          5          8
8   60.0  False         2           4          5          8
9    NaN   True         3           5          9         13
10   NaN   True         3           5          9         13
11   NaN   True         3           5          9         13
12   NaN   True         3           5          9         13
13   NaN   True         3           5          9         13
14  70.0  False         4           1         14         14

Now, you can exclude 'x' from the summary, drop duplicates, filter to keep only NaN values (is_na == True), filter to keep sequences above a certain length (e.g., at least 3 consecutive NaN values), etc.  Then, if you drop duplicates, the first row will summarize the first NaN run, second row will summarize the second NaN run, etc.
Finally, you can use this with apply() to process the whole data frame, if this is what you need.
Short version of results, for the test data frame:
print(summary[summary['is_na']].drop(columns='x').drop_duplicates())
   is_na  group_id  group_size  min_index  max_index
2   True         1           3          2          4
9   True         3           5          9         13


text:
Q: how to construct this query? I have a table that holds info about videos on a website.  It has fields for id (primary key),title, series (int, foreign key constraint), and episode number.  There is another table called "series" that indexes video series.  So for example, series "American Dad" would have a series id of 1, and the id column in the series table is the same as the series column in the videos table.
I am trying to create a query that, when given a video id, pulls the title and video id of the previous and next videos in the series, e.g. if I input an id for episode 5 for American Dad, I would also get back the info for episodes 4 and 6.
I know how to write the query to find the series id when given a video id, and I know how to write the query to find all the episodes of a series when given a series id.  I am having trouble putting it all together in one query, and also limiting it to the results immediately preceding and following (based on episode number) of a given video.
Hopefully that wasn't too convoluted.  Any help is appreciated!

A: If the episode numbers are always sequential, you can just do something like
SELECT ... WHERE (episode = :episode - 1 OR episode = :episode + 1) AND series = :series


text:
Q: Should I avoid creating lots of variables? I have two possibilities:
1) Store an object in a variable and use that variable in my code. But this uses memory to store the object right?
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
BOOL bool1 = [userDefaults boolForKey: key1];
BOOL bool2 = [userDefaults boolForKey: key2];

2) Don't store it in a variable and create it from scratch when I needed.
BOOL bool1 = [[NSUserDefaults standardUserDefaults] boolForKey: key1];
BOOL bool2 = [[NSUserDefaults standardUserDefaults] boolForKey: key2];

What would be recommended in this case? If there's a difference between objects then how would I know which one to use?

A: As far as the particular example you showed in your question is concerned, there's no practical difference between those two ways of getting the NSUserDefaults. Unless you are dealing with large data objects (like UIImages) you should be concentrating on the clarity and readability of your code. If it turns out that you have a memory issue during your testing, come back and find ways to use less memory later.

A: You haven't been very specific, as to what kind of data. But irregardless, the things variables point at are what consume memory, not the variables themselves.
As for the rest of your question, if you leave a comment explaining your application centered around this question, as in what part your system is doing at this moment, I'll edit this to reflect that answer.
EDIT: Someone else answered and was accepted before I could update my answer. See the accepted answer.

A: If the operation executed is a very performance heavy method, it might be a performance loss to redo it every time, when you simply can save the information.
I feel you have to choices

*

*If you have a problem with allocated memory, redo it.

*If memory problem isn't an important factor and the executed operation isn't that heave that you have a performance loss, redo it.

I believe that doing iPhone-apps, the memory is not that super critical (might be now with multitask however), it's more critical to have the workload in mind, i.e. try not to redo same work. But as said, it all depends on the situation.

A: The wording of your question suggests you may not fully understand C pointers. You're not "storing an object in a variable." The userDefaults variable in your first example is just a C pointer. The +standardUserDefaults method returns a pointer to the global user defaults object, which you assigned to userDefaults. In your second example, you retrieved a pointer to the object twice, once for each line.
The only real difference between the two is that in the second example, you're doing a redundant message-send to retrieve the object reference again. Your examples aren't performance-critical, but there are cases where you might want to cache a reference to an object to avoid sending redundant messages, such as in a loop. It all depends on the performance of your program.
If you're not comfortable with C pointers, definitely read up on them. It should clear up some things for you.

A: You are not using any more of your program's memory in the first example. The NSUserDefaults object will be stored on the heap either way, and the storage for the variable itself will either be a) a register, or b) on the stack. Registers don't take up any of your app's real memory, and the memory for the stack is already reserved.
Also, pointers take up a very small amount of memory — 4 bytes on 32-bit and 8 bytes on 64-bit platforms. A quarter of a million of them would take less than 1 MB. Individual scalars like this are the very last place you should be looking for memory savings.


text:
Q: Setting ItemsSource of ListBox to a property of it's containing class I have the following xaml -
<Window x:Class="DataTemplateTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="400" Width="600" Loaded="Window_Loaded">
    <Grid>
        <ListBox Height="380" Margin="10,12,0,0" Width="355"/>
    </Grid>
</Window>

and the following code-behind -
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        _nameList = new List<string>
                        {
                            "X",
                            "Y",
                            "Z"
                        };
    }

    private List<string> _nameList;
    public List<string> NameList
    {
        get { return _nameList; }
    }
}

I want to set the NameList as the ItemsSource of the ListBox from the xaml, not from the code-behind. How do I do that?
EDIT : I know the MVVM-way of doing this. But that's not what I'm asking.
EDIT : It's not that I don't like MVVM or so. While doing some quick test I just realized that I don't know how to do this. So, wondering if it's possible, and trying to learn. Is it anyhow possible using StaticResource?

A: If you've meant on "not doing the MVVM-way" that you don't want to use ViewModels then you
can data-bind to the "codebehind" with the following steps:
Set the binding in XAML:
<ListBox ItemSource="{Binding NameList}"/>

And set the DataContext to this after you have populated your list e.g in the Window_Loaded event:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    _nameList = new List<string>
                    {
                        "X",
                        "Y",
                        "Z"
                    };
    DataContext = this;
}

Edit: If you don't want to set the DataContext you can bind directly to the window:
<Window Name="window" ... />

  <ListBox  ItemsSource="{Binding NameList, ElementName=window}"/>

Or you can use AncestorBinding as
<ListBox ItemsSource="{Binding NameList, RelativeSource={RelativeSource AncestorType=Window}}"/>

However I both cases the list will be empty because the view won't be notified by the fact that you populated your list in the loaded event. So you need to use INPC to notify that the "NameList" property changed.


text:
Q: Android IllegalArgumentException - no view found for ID I am new to Android and am having issues with fragment navigation and instantiation from the action bar.
I have a MainActivity class and 2 fragments from the Basic activity template in Android Studio, which also implements a navigation graph. For each of the fragments I have an action icon in the action bar, like below:

The app's start destination is the first fragment. What I would like to happen is that when I click the second icon fragment2 would appear. The code I have for starting an instance of fragment2:
(...)
case R.id.action_steps:

       Fragment stepsFragment=new StepsFragment();
                    fm.beginTransaction().replace(R.id.nav_host_fragment_container, stepsFragment).commit();
       return true;

However, when I click on the second icon the app crashes:
java.lang.IllegalArgumentException: No view found for id 0x7f0800cb (project:id/nav_host_fragment_container) for fragment StepsFragment{8238b37} (1bab8c06-d49e-4f22-a06e-cb0dc89b113f) id=0x7f0800cb}
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:315)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
        at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
        at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2169)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1992)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
        at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

*

*How can I fix this?

*Is it possible to "toggle" between the fragments by using the navigation controller (via the menu items in the action bar)? How can that be achieved (if possible, without losing state)?

Below xml for MainActivity:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

And content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>

PS: I have several classes and layouts and would be too much if I post everything at once, but please let me know if you need more info, thanks.


text:
Q: In case task fails, how to terminate rest of the execution? I am running a complex playbook using shell in one of my Ansible playbook task. And I am running an upgrade for s/w using command module in one of my Ansible playbook tasks.
How do I terminate execution of rest of the playbook in case output of this command includes failed?
Currently its silently failing and rest of the playbook executing without alerting any failure.
Below is a part of main playbook which has multiple other tasks:
- hosts: abc
  tasks:
    - name: Upgrade S/W
      include_role:
        name: sw.upgrade
      register: upgrade_result
      tags:
      - upgrade

    - debug:
        msg: "{{upgrade_result}}"

and below is task from role:
- name: Execute upgrade
  command: "running some upgrade command here"
  async: 7200
  poll: 10
  register: sw_upgrade_hosts

I am new to Ansible and tried failed_when option but that doesn't give expected result.

A: You can try using following logic :
For shell invoking in Ansible use bash script and can write all shell cmds there.
Next step is to invoke this bash script in ansible ..
- name: example of many failed
  ansible.builtin.shell: "./xyz.sh"
  register: ret
  failed_when: >
    ("Error string") or
    (ret.stderr != '') or
    (ret.rc == 10)

Something like this could be of help here!

A: Regarding

How do I terminate execution of rest of the playbook in case output of this command includes failed?

you would need to Define failure with failed_when, or could assert that given expressions are true or end_play.


text:
Q: Atomic operations in ARM I've been working on an embedded OS for ARM, However there are a few things i didn't understand about the architecture even after referring to ARMARM and linux source.
Atomic operations.
ARM ARM says that Load and Store instructions are atomic and it's execution is guaranteed to be complete before interrupt handler executes. Verified by looking at
arch/arm/include/asm/atomic.h :
    #define atomic_read(v)  (*(volatile int *)&(v)->counter)
    #define atomic_set(v,i) (((v)->counter) = (i))

However, the problem comes in when i want to manipulate this value atomically using the cpu instructions (atomic_inc, atomic_dec, atomic_cmpxchg etc..) which use LDREX and STREX for ARMv7 (my target).
ARMARM doesn't say anything about interrupts being blocked in this section so i assume an interrupt can occur in between the LDREX and STREX. The thing it does mention is about locking the memory bus which i guess is only helpful for MP systems where there can be more CPUs trying to access same location at same time. But for UP (and possibly MP), If a timer interrupt (or IPI for SMP) fires in this small window of LDREX and STREX, Exception handler executes possibly changes cpu context and returns to the new task, however the shocking part comes in now, it executes 'CLREX' and hence removing any exclusive lock held by previous thread. So how better is using LDREX and STREX than LDR and STR for atomicity on a UP system ?
I did read something about an Exclusive lock monitor, so I've a possible theory that when the thread resumes and executes the STREX, the os monitor causes this call to fail which can be detected and the loop can be re-executed using the new value in the process (branch back to LDREX), Am i right here ?

A: The idea behind the load-linked/store-exclusive paradigm is that if if the store follows very soon after the load, with no intervening memory operations, and if nothing else has touched the location, the store is likely to succeed, but if something else has touched the location the store is certain to fail.  There is no guarantee that stores will not sometimes fail for no apparent reason; if the time between load and store is kept to a minimum, however, and there are no memory accesses between them, a loop like:
do
{
  new_value = __LDREXW(dest) + 1;
} while (__STREXW(new_value, dest));

can generally be relied upon to succeed within a few attempts.  If computing the new value based on the old value required some significant computation, one should rewrite the loop as:
do
{
  old_value = *dest;

  new_value = complicated_function(old_value);
} while (CompareAndStore(dest, new_value, old_value) != 0);

... Assuming CompareAndStore is something like:

uint32_t CompareAndStore(uint32_t *dest, uint32_t new_value, uint_32 old_value)
{
  do
  {
    if (__LDREXW(dest) != old_value) return 1; // Failure
  } while(__STREXW(new_value, dest);
  return 0;
}

This code will have to rerun its main loop if something changes *dest while the new value is being computed, but only the small loop will need to be rerun if the __STREXW fails for some other reason [which is hopefully not too likely, given that there will only be about two instructions between the __LDREXW and __STREXW]
Addendum
An example of a situation where "compute new value based on old" could be complicated would be one where the "values" are effectively a references to a complex data structure.  Code may fetch the old reference, derive a new data structure from the old, and then update the reference.  This pattern comes up much more often in garbage-collected frameworks than in "bare metal" programming, but there are a variety of ways it can come up even when programming bare metal.  Normal malloc/calloc allocators are not generally thread-safe/interrupt-safe, but allocators for fixed-size structures often are.  If one has a "pool" of some power-of-two number of data structures (say 255), one could use something like:
#define FOO_POOL_SIZE_SHIFT 8
#define FOO_POOL_SIZE (1 << FOO_POOL_SIZE_SHIFT)
#define FOO_POOL_SIZE_MASK (FOO_POOL_SIZE-1)

void do_update(void)
{
  // The foo_pool_alloc() method should return a slot number in the lower bits and
  // some sort of counter value in the upper bits so that once some particular
  // uint32_t value is returned, that same value will not be returned again unless
  // there are at least (UINT_MAX)/(FOO_POOL_SIZE) intervening allocations (to avoid
  // the possibility that while one task is performing its update, a second task
  // changes the thing to a new one and releases the old one, and a third task gets
  // given the newly-freed item and changes the thing to that, such that from the
  // point of view of the first task, the thing never changed.)

  uint32_t new_thing = foo_pool_alloc();
  uint32_t old_thing;
  do
  {
    // Capture old reference
    old_thing = foo_current_thing;

    // Compute new thing based on old one
    update_thing(&foo_pool[new_thing & FOO_POOL_SIZE_MASK],
      &foo_pool[old_thing & FOO_POOL_SIZE_MASK);
  } while(CompareAndSwap(&foo_current_thing, new_thing, old_thing) != 0);
  foo_pool_free(old_thing);
}

If there will not often be multiple threads/interrupts/whatever trying to update the same thing at the same time, this approach should allow updates to be performed safely.  If a priority relationship will exist among the things that may try to update the same item, the highest-priority one is guaranteed to succeed on its first attempt, the next-highest-priority one will succeed on any attempt that isn't preempted by the highest-priority one, etc.  If one was using locking, the highest-priority task that wanted to perform the update would have to wait for the lower-priority update to finish; using the CompareAndSwap paradigm, the highest-priority task will be unaffected by the lower one (but will cause the lower one to have to do wasted work).

A: Okay, got the answer from their website.
If a context switch schedules out a process after the process has performed a Load-Exclusive but before it performs the Store-Exclusive, the Store-Exclusive returns a false negative result when the process resumes, and memory is not updated. This does not affect program functionality, because the process can retry the operation immediately.


text:
Q: Integrate SonataAdminBundle + FOSUserBundle Without SonataUserBundle for security in symfony 2.3? I am using FOSUserBundle for authentication and roles. For admin panel I am using SonataAdminBundle.
FOSUserBundle Version 2.0.dev (which support event listeners).
When I tried to install SonataUserBundle, It accept only <= 1.3 version of FOSUserBundle(without event listeners)
I need FOSUserBundle with event listeners.
Does anyone know how to provide security with FOSUserBundle (for Admin & Client panel both)?

A: Try:
php composer.phar require friendsofsymfony/user-bundle

and then type version:
dev-master as 1.3.2

then you can install Sonata User Bundle.

A: Should work with inline alias in your composer.json
 "friendsofsymfony/user-bundle": "2.0.x-dev as 1.3.2"


text:
Q: How to reRender a rich:dataTable which is inside a4j:repeat? I have sth like this:
<a4j:repeat value="#{results}" var="hdr" rowKeyVar="idx">
   <rich:dataTable var="item" value="#{results}" id="tbl#{idx}" first="#{idx}" rows="1">
       <a4j:commandButton value="update this table only" reRender="tbl#{idx}" />
   </rich:dataTable>
</a4j:repeat>

When I check from the output html, the data table has id like form:0:tbl that has no idx at the end.
The reRender will work when there is only one row in the results.
So here comes some questions:

*

*Why doesn't dataTable's id works with EL expression while the "first" attribute works nicely?

*How does reRender work that even I just specify tbl it can still be resolved while the actual HTML id is something longer like form:0:tbl? (if I know how does reRender work, I maybe able to hack it to work with a4j:repeat...)

*Is there any technique or workaround that I could use to refresh only a specific dataTable that is inside a4j:repeat?

In fact I have successfully reRendered the whole a4j:repeat block surrounded by s:div. But refreshing the whole block would reset the scrollbar so it isn't desired....

A: For 1, it is possible that the life cycle of the table is in a different phase.
For 2, it refers to UIComponent.findComponent in fact for looking up a component given an ID.
For 3, perhaps try to use UIComponent.findComponent() or #{rich:clientId('id')} to see whether the actual HTML element ID of the a4j:repeat embedded rich:dataTable to be retrieved.
If yes, then somehow reRender can be made to work. If no, look if there is anything that can override how reRender looks for component.

A: Okay latest experiment shows that simply using the rich:dataTable id can do.
Keys to remember:

*

*Inside a4j:repeat, the absolute name of the id of dataTable will have something like :0: :1: for the corresponding index.

*However, to locate it, simply using the same id as defined in rich:dataTable is okay. Don't append any suffix at the end.

*When observing the ajax data from Chrome, the reRendered portion is just the same related dataTable of the component.

Conclusion, think too much, failed to try the simplest solution at the start.


text:
Q: MySql wont start in XAMPP I know this question has been asked several times, I have looked through other answers but couldn't find the solution.
Last night MySQL was working fine on my XAMPP. Today, When I started MySQL from control panel, it started for a brief moment and then stopped immediately.
I tried again but same thing happened.I completely stopped XAMPP from task manager and restarted again but no use.
I checked if some other application is using port 80 at canyouseeme.org but its giving an error,means port 80 is free.
BTW Apache is running fine.
Control panel log says "MySql started", but it stops immediately after that.

A: Uninstalling and reinstalling XAMPP worked for me.
MySql is running now.

A: Follow the steps;
1. Open C:\xampp on your device
2. Select xampp_stop.exe
3. Select xampp_start.exe
4. Right click on xampp_stop.exe and select 'Run as Administrator'
5. Select the marked button to install or re-install mysql.
6. Start mysql on xampp
I hope it worked


text:
Q: How to change classpath without administrative privileges On my current laptop I dont have administrative privileges and was trying to find a way to add some jars to my classpath using emacs or a cygwin shell. I believe i can do something like
javac -cp "./thing.jar" test.java

But is there a way to actually change my classpath? thanks.

A: if you want to permanently change the CLASSPATH environment variable you can use use setx


text:
Q: sudo tasksel remove lamp-server What is the command I ran and now I have no ubuntu left...
When I which the computer on, the monitor comes on, it goes passed the grub screen, it does not show anything after that.  How do I fix this?

A: I haven't tried this myself, but it may work. I don't really know what you mean by "I have no Ubuntu left" and how much of Ubuntu you are missing.
Take a look at https://help.ubuntu.com/community/Tasksel
The first thing i would try is to run...
sudo apt-get install ubuntu-desktop^
It may help. If not, let us know.

A: According to this bug report, tasksel behaves badly when removing packages. It seems that it removes many packages that it shouldn't, which can leave the machine in an inconsistent state.
Package Removal (A Better Way)
To remove something that you installed with tasksel, you need to mention the packages specifically. For example:
sudo aptitude remove apache2 apache2.2-common php5-common mysql-common

The theory is that removing these packages will cause the other parts of each system to also be removed. However, a manual search through Synaptic would still be beneficial.
This answer gives a much more detailed listing of what needs to be removed if you're trying to remove the LAMP stack.
Recovery
To recover from tasksel's over-zealous removals, you have to reinstall the affected packages. In some cases, installing ubuntu-desktop will do the trick:
sudo aptitude install ubuntu-desktop

To be more thorough, open up the Ubuntu Software Center and look through your removal history (see screenshot) to find the packages that were removed at the same time that you ran tasksel remove. You can then reinstall those packages.

A: This is a common bug with ubuntu (see #574287).
I was recently faced with the same issue. To address this, Once I was faced with the blank screen, I accessed an Auxiliary terminal by pressing Ctrl+Alt+F1 (F1-F6) usually work for me, logged in and ran sudo tasksel again to recover from my mistake.


text:
Q: Coda folder sorting Does anybody know if there's an option in Coda somewhere (or a hack) that would sort folders at the top of the list in the file browsers?

A: I don't know if that option exists, but if you send the question to @panic on twitter or better yet email support@panic.com, they'll respond and let you know.

A: I suspect that the File Browser sidebar is a standard Cocoa Widget. What this means is that it would follow all the same rules that standard OSX applications do (think: Finder).
Since the Finder does not show Folders first, Coda will probably not have a way to show Folder first.
I second Kris + Matthew B.'s answer, that Panic is a great company that answers users' questions. Having said that, don't get your hopes up, because Coda is just behaving exactly like the Finder does.


text:
Q: Save cx_freeze errors So when a python program has been frozen using cx_freeze it opens up an alert whenever the program crashes the only problem is the only way to distribute the traceback (for bug reports) is by screenshot-ting the alert box which is a bit of a pain (you can't copy text from the alert box).
Is there any way to save cx_freeze error reports? For example by writing them into a crash-log file. It seams a shame to present the crashes in such a helpful way and yet have no way of easily sending crash reports to developers (screenshot-ting being a but tedious).

A: I think it is actually possible to copy the text from a Windows message box, but I agree that it's not obvious to users that you can do that.
It should be possible to set sys.excepthook to a function that saves the error and traceback somewhere. This will stop cx_Freeze displaying the error message box, so it's up to you to notify the user about errors if that's appropriate.


text:
Q: How to build Front-End apart from Back-End with security? I have some knowledge of Vue and Experience with Django, wanted to know if there's a way to safely create an app with nuxt and django rest framework.
I saw that Nuxt is not a server framework and e only works for doing ssr for Vue, so i was wondering how would i do to use it with drf, i thought about using and api key but since the vue app in client-side would have to access the API directly (e.g: submitting forms) would be a breach, right? like, my API cannot be open to everyone and i cannot store api credentials inside vue app.
Is there a way to use Nuxt & Django Rest Framework together?

A: I've already answered questions regarding if Nuxt is private and how to make secure calls, reading some of those can be a nice start.
Overall, the practice of having such communication is totally common and can be achieved with a JWT. The main points are:

*

*you create an async pair of keys with Django (like SSH does)

*keep the private key on your Django server

*expose your public key on the Nuxt site

*force authentication before doing anything sensitive (using a global middleware)

*enjoying fully protected communication

*if somebody tries to break the client-side code, he will still not be able to access the most important part (the actual data in your database)

There are plenty of tutorials on the Web on how to achieve a working JWT flow.


text:
Q: Extra padding in position: absolute property In the following code, there is padding on the left div block navigation area with fixed (or absolute) position on the top of the div block looking like 1em but no padding on the left in comparison with no padding on another div content block having no top or left padding. This is true in at least Firefox and Chrome. How can I get no padding on the position: absolute block. Note: This problem disappears if I delete position: absolute. How can I fix it? I know I'll want padding later, but I want the padding to look right on the nav AND content area and I would like them to look the same with NO padding as a baseline.
Here's an image. See how the have area on the left is thicker and the content area on the left is thin?

Here is example code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

This is content area text

This is a nav area text

A: if you are assigning position: absoloute; to any element, then do not apply the margin property. take advantage of top, left, right, bottom property.

A: Found the answer here http://www.webmasterworld.com/css/3083754.htm
It needs a * {margin:0; padding:0} added to the beginning and it works right.


text:
Q: Replace String sequence using Recursion Java has the replace() and replaceAll() methods to replace parts/sequence of a string with a given new pattern. How does the internal of that function work? What if I had to write a function that inputs a string, OldPattern, NewPattern and replaces every occurrence of OldPattern with the NewPattern recursively without using RegEx?
I have done the following code using iteration for String input and it seems to work. What if the input is a characterArray instead of a string?
  public String replaceOld(String aInput, String aOldPattern, String aNewPattern)
        {
             if ( aOldPattern.equals("") ) {
                throw new IllegalArgumentException("Old pattern must have content.");
             }

             final StringBuffer result = new StringBuffer();
             int startIdx = 0;
             int idxOld = 0;
             while ((idxOld = aInput.indexOf(aOldPattern, startIdx)) >= 0) {
               result.append( aInput.substring(startIdx, idxOld) );
               result.append( aNewPattern );

               //reset the startIdx to just after the current match, to see
               //if there are any further matches
               startIdx = idxOld + aOldPattern.length();
             }
             //the final chunk will go to the end of aInput
             result.append( aInput.substring(startIdx) );
             return result.toString();
          }

A:
Java has the replace() and replaceAll() methods to replace parts/sequence of a string with a given new pattern.

To be precise, these methods create new strings with the relevant characters replaced.  A Java String is immutable.

How does the internal of that function work?

That's too complicated to explain in detail here.  (And the details actually may vary from one implementation to the next).  Your best bet is to read the source code of the relevant library classes for yourself.  (The source code is distributed as part of your JDK, and your Java IDE should be able to show it to you.  Alternatively, a Google search will find it for you on the web.)

What if I had to write a function that inputs a string, OldPattern, NewPattern and replaces every occurrence of OldPattern with the NewPattern recursively without using RegEx?

Well if you are talking about doing pattern match / replace without using the Pattern class, then yes that would be tricky ... not to mention that it would be pointless.
(A recursive solution could be dangerous.  Consider this problem: "recursively replace all instances of "a" with "ba" in "a".  What should the result be?  Should you even be trying to do this?)

Assuming that the arguments are simple strings (not patterns as you describe them) then here's a recursive solution (not tested):
public String replace1(String in, String target, String replacement) {
    if (target.isEmpty()) {
        return in;
    }
    int pos = in.indexOf(target);
    if (pos < 0) {
        return in;
    }
    String updated = in.substring(0, pos) + replacement +
                     in.substring(pos + target.length());
    return replace1(updated, target, replacement);
}

That solves1 the version of the problem where you want the replacement to be recursive; i.e. where you want to substitute instances of target that inserted by the replacement process.  If you don't want to do that, then:
public String replace2(String in, String target, String replacement) {
    if (target.isEmpty()) {
        return in;
    }
    int pos = in.indexOf(target);
    if (pos < 0) {
        return in;
    }
    return in.substring(0, pos) + replacement +
                     replace2(in.substring(pos + target.length()),
                             target, replacement);
}

Note that these are most likely less efficient than your original iterative solution. Even ignoring all of the string copying that is going on.  Java doesn't do tail-call optimization.

1 - If you call replace1 with pathological arguments, you will get a stack overflow.  For example replace1("ab", "b", "b")

A: try
public static String replaceOld(String aInput, String aOldPattern, String aNewPattern, int i) {
    i = aInput.indexOf(aOldPattern, i);
    if (i == -1) {
        return aInput;
    }
    aInput = aInput.substring(0, i) + aNewPattern + aInput.substring(i + aOldPattern.length());
    return replaceOld(aInput, aOldPattern, aNewPattern, i + aNewPattern.length());
}

note that param i is used for optimization, so that indexOf does not scan from pos 0 every time. And it also solves "recursively replace all instances of "a" with "ba" in "a" problem.

A: Maybe this method will answer your question.
  static int indexOf(char[] string, char[] pattern, int startIndex) {
     int index = startIndex;
     while(true) {
         while(index < string.length && string[index] != pattern[0]) index++;
         if(index >= string.length || index+pattern.length > string.length) return -1;
         boolean match = true;
         for(int i = 1; i < pattern.length; i++) {
             if(string[index+i] != pattern[i]) {
                 match = false;
                 break;
             }
         }
         if(match) return index;
         else index += 1;
     }
  }

If you want a recursive replace method, use this
static String replace(String string, String pattern, String replacement) {
  int index = string.indexOf(pattern);
  if(index < 0) return string;
  int endIndex = index+pattern.length();
  return string.substring(0, index) + replacement +
      replace(string.substring(endIndex), pattern, replacement);
}


text:
Q: "in each side" or "in each sides"? If I want to say that there are two people and each one of them is found in other side of the house. What is the correct way to say it?

1) There are two people in each side of the house
2) There are two people in each sides of the house

And by the way (in the same topic), are the two following sentences equal to the previous two - in the aspect of the meaning?

1) There is one person in each side of the house.
2) There is one person in each sides of the house.

A: Two people on each side means two people on this side and two people on that side—four people in all (if there are two sides).
What you mean is one person on each side, one on this side and one on that.
If you have not already explained that two sides are involved, you need to say so explicitly:

There is one person on each of the two sides.  OR
  There are two people, one on each of the two sides.

A: Each is used before a singular noun and a singular verb/pronoun is used for it.

Each item consists of 10 questions. (if there are two items, there are 20 questions)
Each of these people has some useful talent.
Each component can be replaced separately if it breaks.

As the comments point, you're considering each item individually. Then:

There is one person on each side


text:
Q: Is it possible to pass a variable of type 'type' to a ComboBox so that all the elements of the collection are selectable? I am trying to create a GUI app that lets me plot any variable against any other variable.  This is my first GUI app, so perhaps I'm biting more than I can chew.  The values of these variables are in arrays, which I have grouped into collections -- that is , I use collections.nametuple to group the raw values, the calculated magnitude and phase, the peak index, and a normalized values (please forgive me if I'm not using the correct terminology), for example.
What I would like to do is to have all these variables (or elements of the various collections(?) as  choices in two ComboBoxes, xdata and ydata, so that I can plot any variable against any other variable.  Is this even possible  to do? This is the MainWindow of the app I'm trying to create:

I have the selection of the file, and the parsing of the data working, and for example, say I created these two collections from the data in the file:
type_aData = collections.namedtuple('type_aData',
                                        'A_RX '
                                        'A_RXlogmag '
                                        'A_RXmag'
                                        'A_RXph'
                                        'A_pkMagInd'
                                        'A_RXlogmag_N'
                                        'A_RXmag_N'
                                        'A_RX_N'
                                        'A_RXph_N')

type_distance = collections.namedtuple('type_distance',
                                     'A'
                                     'B')

each A_x is an array, and so are distanceA and distanceB.  I'd like to do something like:
self.xdata.addItem(type_distance)
self.ydata.addItem(type_adata)

so that the all the distance variables and aData variables are exposed in the x and y data ComboBoxes, but it complains that the arguments cannot be of type 'type'. If I instead use 'type_distance', for example, in quotes, then all I get is the text in the ComboBox and not the actual variables (never mind that I still don't know how to grab the value selected from the ComboBox to do something with it --that's the next hurdle!).
In short, what I'd like to ultimately be able to do is select the variables I want to plot from the x and y data ComboBoxes so that I can use them in a function that would do something like:
self.data_line=self.graphWidget.plot(self.distance.A, self.aData.A_RX)

or
self.data_line=self.graphWidget.plot(self.distance.A, self.aData.A_RXph),

for example.
If anyone can point me to examples of simple GUI apps that do something similar to what I'm trying to do here , that would be great. I"m not married to doing it this way ---I just don't know any better.   I get the feeling I'm complicating this way more than it needs to be.

A: I'm not sure if this is what you have in mind, but here is a small example to illustrate how you can add the fields of a namedtuple to a QComboBox and use the currently selected fields in these combo boxes to plot the corresponding data in a matplotlib figure:
from PyQt5 import QtWidgets
from collections import namedtuple
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np

type_distance = namedtuple('type_aData', ['A_RX', 'A_RXlogmag', 'A_RXmag'])
type_aData = namedtuple('type_aData', ['A', 'B'])

class Widget(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)

        # setup matplotlib figure
        self.figure = Figure()
        self.ax = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self.figure)

        # setup rest of ui
        self.combo_x = QtWidgets.QComboBox(self)
        self.combo_y = QtWidgets.QComboBox(self)
        hlayout = QtWidgets.QHBoxLayout()
        hlayout.addWidget(self.combo_x)
        hlayout.addWidget(self.combo_y)

        vlayout = QtWidgets.QVBoxLayout(self)
        vlayout.addWidget(self.canvas)
        vlayout.addLayout(hlayout)

        # generate some random data
        self.distance, self.data = self.generate_data()

        # add field names of data to comboboxes
        self.combo_x.addItems(self.distance._fields)
        self.combo_y.addItems(self.data._fields)

        # connect signals to slot to automatically update plot when selected fields have changed
        self.combo_x.currentTextChanged.connect(self.plot)
        self.combo_y.currentTextChanged.connect(self.plot)
        self.plot()

    def plot(self):
        # extract field names and corresponding data that should be plotted
        xlabel = self.combo_x.currentText()
        ylabel = self.combo_y.currentText()

        x_data = getattr(self.distance, xlabel)
        y_data = getattr(self.data, ylabel)

        # update plot with newly selected data
        self.ax.clear()
        self.ax.plot(x_data, y_data, 'ro')
        self.ax.set_xlabel(xlabel)
        self.ax.set_ylabel(ylabel)
        self.figure.tight_layout()
        self.canvas.draw()

    def generate_data(self):
        # generate some random data and return data as type_distance and type_aData objects
        npoints = 300
        x_data = np.random.normal(size=npoints)
        y_data_a = np.random.normal(size=npoints)
        y_data_b = np.sin(x_data)

        distance = type_distance(x_data, np.log(np.abs(x_data)), np.abs(x_data))
        data = type_aData(y_data_a, y_data_b)
        return distance, data

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    win = Widget()
    win.show()
    app.exec()


text:
Q: Unresolved reference JavaVersion in gradle buildSrc IntelliJ I am facing a problem with two existing gradle projects that worked fine a couple of months ago but that show now an annoying error in the buildSrc folder, where I use the org.gradle.api.JavaVersion constant.
The project compiles correctly and is imported to IntelliJ. I can also run it so I guess everything is working but of course I don't like to get an error thrown into my face ;)
Here are both example projects:

*

*https://github.com/Quillraven/Quilly-s-Adventure

*https://github.com/Quillraven/Dark-Matter
They are both a multi-project with a core, desktop and android project.
In both projects I use a buildSrc folder to define the versions in a common place for the entire project.
For whatever reason, IntelliJ is now showing an error "unresolved reference JavaVersion" in the Dependencies.kt/versions.kt file.

The build.gradle.kts of the buildSrc folder looks like this:
plugins {
    `kotlin-dsl`
}

repositories {
    jcenter()
}

Does anyone know how to get rid of this error? Is it an IntelliJ issue or something else? Or is the issue on my end ?

A: This is an Intellij IDEA 2020.2 bug: https://youtrack.jetbrains.com/issue/KT-40683. Dependencies are unresolved in the buildSrc module, when you also have an Android module in the project.
As a possible workaround, please use IDEA 2020.1.


text:
Q: Uniform Convergence of a subsequence over an arbitrary interval I am getting ready for an entrance exam that is in August and I am trying to get a head start on the analysis section. I recently came across this problem and it is giving me some trouble.
Consider the sequence of functions
$$f_k(x) := {\sin(kx)},\quad k = 1, 2,\dots ,$$ and observe
that $\sin(kx) = 0$ if $x = mπ/k$ for all integers $m$. Given an arbitrary interval $[a, b]$, show that {${f_k}$} has no subsequence that converges uniformly on $[a, b]$.
I am rather unsure how to begin this problem. I can see that this sequence doesn't converge pointwise because if $k=2n$ and $x= \pi/4$, then when $n$ is even, then $\sin(kx) = 0$ but if $n$ is odd, then $\sin(kx) = \pm 1$. Since this function doesn't converge pointwise, then it doesn't converge uniformly. I am not sure if implies that there is no subsequence that converges uniformly. Or is there a better way to approach this problem?

A: To elaborate on the hints given in comments, suppose for contradiction that $\{f_k\}$ has a subsequence $\{ f_{k_j} \}$ that converges uniformly on $[a,b]$ to a limit function $f$.   Since the uniform limit of continuous functions is continuous, $f$ should be continuous.  However, I claim this is impossible.
To show that the limit function cannot be continuous, one should show that there exists $\varepsilon_0 \geq 0$ so that for any $\delta >0$, there are $x,y \in [a,b]$ with $|y-x| < \delta$ and $|f(y) - f(x)| \geq \varepsilon_0$.  I claim that taking $\varepsilon_0 = 1$ works.
Let $\delta$ be fixed.  By our assumption that $\{ f_{k_j} \} \to f$ uniformly, we can choose $J$ so that if $j \geq J$, then $|f(x) - f_{k_j}(x)| \leq 1/2$ for all $x \in [a,b]$.  By taking $J$ bigger as needed, we assume that $\frac{2 \pi }{k_J} < \delta$.  This guarantees that any interval of width $\delta$ contains an entire period of $f_{k_J}$.  Can you see how to pick $x$ and $y$ to make $|f(y) - f(x)| \geq 1$?


text:
Q: Nested v-for in Vue app uses the previous state I am new to Vue.js and I am trying to code a decision tree but I am having an issue. When people click buttons on a step it loads another step based on a JSON file. The user should be able to skip back to a previous step and have it reset from that set and allow them to work through it from there.
The issue I am having is that the steps that are loaded after choosing a previous step will have the active class still applied. I am pretty sure this has to do with the :key on the v-for loop but I don't know how to reset it so that Vue is not saving that setting.
I have setup the code in a Codepen here https://codepen.io/akrug23/pen/jOVYQPd?editors=0011
You can reproduce what I am saying by clicking the following buttons
Manage it myself -> Low -> 0-5 years now click on Medium and you will see that the first button is already set with the class active
Note: Since a lot of the questions are the same I have added numbers to the front so you can see that other questions from the JSON file are loading. I am using Vue.js 3
Thank you in advance.

A: Change the key in the BranchSteps component to something unique to the question, like the question text in item.question:
<div
  v-for="(item, index) in steps"
  :key="item.question"
  :data-step-id="index"
  class="card mb-2 js-step-card"
  :class="isLastCard(index)">

The reason for using a key in a v-for is so Vue won't reuse any existing DOM nodes when the list is re-rendered, such as when an item is added/destroyed.  But it only works if the key is unique to the list item.  Sometimes using index as a key is not unique enough, which is what's happening here.
The unique key above causes Vue to re-render the node with new info instead of reusing the ghost node of the removed item.


text:
Q: React - Filtering returns wrong rows It's driving me crazy. I've created a list with several entries. I added a filtering function, which seems to work fine. I've checked the number of results returned, but somehow it just showing the result number beginning at the first row.
For explanation:
Let's assume I search for "Zonen" and my filter function returns 4 rows with ID 23, 25, 59 and 60, the rows with ID's 1,2,3 and 4 are displayed. What I'm doing wrong!?
...
render() {
let filteredList = this.state.freights.filter((freight) => {
    let search = this.state.search.toLowerCase();
    var values = Object.keys(freight).map(function(itm) { return freight[itm]; });
    var flag = false;

    values.forEach((val) => {
        if(val != undefined && typeof val === 'object') {
            var objval = Object.keys(val).map(function(objitm) { return val[objitm]; });
            objval.forEach((objvalue) => {
                if(objvalue != undefined && objvalue.toString().toLowerCase().indexOf(search) > -1) {
                    flag = true;
                    return;
                }
            });
        }
        else {
            if(val != undefined && val.toString().toLowerCase().indexOf(search) > -1) {
                flag = true;
                return;
            }
        }
    });
    if(flag)
        return freight;
});
...
<tbody>
{
    filteredList.map((freight)=> {
      return (
        <Freight freight={freight} onClick={this.handleFreightClick.bind(this)} key={freight.id} />
      );
    })
}
</tbody>
...

UPDATE
freights is loaded and filled via AJAX JSON result. One object of freights looks like this:

I have a textbox where a user can perform a search. This search should return all freight objects which properties contain the search string.
The filter is so complex, because I want to also to search in sub-objects of freight. Maybe there is a more simple way?
"Zones" was just an example for a search string the user can search for.

A: Now that your intentions are clearer, I suggest this much less complex solution.
First, you can write a recursive utility fn to get all values of all keys in an n-depth object. Like this, for example (I'm using lodash's utility fn isObject there):
const getAllValues = (obj) => {
  return Object.keys(obj).reduce(function(a, b) {
    const keyValue = obj[b];
    if (_.isObject(keyValue)){
      return a.concat(getAllValues(keyValue));
    } else {
      return a.concat(keyValue);
    }
  }, []);
}

Now that you have an array of all object's values, it makes your filter very simple:
let filteredList = this.state.freights.filter((freightItem) => {
   const allItemValues = getAllValues(freightItem);
   return allItemValues.includes(this.state.search);
});

That should be it. If something is not working, gimme a shout.

A: I have found the solution why the "wrong" freight entries are displayed.
I needed to add in freight component the componentWillReceiveProps method:
componentWillReceiveProps(nextProps) {
    if(nextProps.freight) {
        this.setState({
            freight: nextProps.freight
        });
    }

}

Then everything worked fine.


text:
Q: How to alter index of a column in alembic in version: 0001, I create a table users like below:
def upgrade():
    op.create_table(
        'users',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('email', sa.String(length=255), nullable=False),
        sa.PrimaryKeyConstraint('id')
    )

    op.create_index(op.f('ix_user_email'), 'users', ['email'], unique=True)

def downgrade():
    op.drop_table('users')

In version 0020,
I want to alter the index of column email in users table. In this case, I want unique=False. Is there a way better than:
def upgrade():
    op.drop_index(op.f('ix_user_email'))
    op.create_index(op.f('ix_user_email'), 'users', ['email'],
    unique=False)
def downgrade():
    op.drop_index(op.f('ix_user_email'))

Because of doing this, when downgrade to version 0019 column ['email'] don't have index at all.
So if there is a way to alter back and forth the index of column email. It's gonna be better.

A: You could restore the original index by adjusting the downgrade() method in 0020 to re-create it:
def downgrade():
    op.drop_index(op.f('ix_user_email'))
    # re-create previous version of index
    op.create_index(op.f('ix_user_email'), 'users', ['email'], unique=True)


text:
Q: Pulling POSIXt dates into another dataframe as new columns based on row index in another dataframe - reproducible I have the dataframe "df1" below which contains row indices that relate to the rows of data frame "df".
I want to use the row indices in df1 to bring in the corresponding row in the dataframe df. i.e., the first row df1 is 4 and 6 and I want to create two new columns in df1 that are start time (timestamp on row 4 of df) and end time (timestamp on row 6 of df).
Actual dataframes are much longer so general code to do this would help
df1 <- structure(list(co2_start = c(4, 6, 9, 12), co2_end = c(6, 9,
12, 15)), class = "data.frame", row.names = c(NA, -4L))

df <- structure(list(date = structure(c(1623481200, 1623481500, 1623481800,
    1623482100, 1623482400, 1623482700, 1623483000, 1623483300, 1623483600,
    1623483900, 1623484200, 1623484500, 1623484800, 1623485100, 1623485400
    ), class = c("POSIXct", "POSIXt"), tzone = "")), row.names = c(NA,
    -15L), class = "data.frame")

So I would like df1 to look like below
4     6     2021-06-12 00:15:00     2021-06-12 00:25:00
6     9     2021-06-12 00:25:00     2021-06-12 00:40:00
9     12    2021-06-12 00:40:00     2021-06-12 00:55:00
12    15    2021-06-12 00:55:00     2021-06-12 01:10:00

A: Since your df1 are already row indices, you can just use dplyr::mutate() to create your columns and subset with the values in start/end columns.
library(tidyverse)

df1 <- structure(list(co2_start = c(4, 6, 9, 12), co2_end = c(6, 9, 12, 15)), class = "data.frame", row.names = c(NA, -4L))
df <- structure(list(date = structure(c(1623481200, 1623481500, 1623481800, 1623482100, 1623482400, 1623482700, 1623483000, 1623483300, 1623483600, 1623483900, 1623484200, 1623484500, 1623484800, 1623485100, 1623485400), class = c("POSIXct", "POSIXt"), tzone = "")), row.names = c(NA, -15L), class = "data.frame")

df1 %>%
  mutate(start = df$date[co2_start],
         end = df$date[co2_end])
#>   co2_start co2_end               start                 end
#> 1         4       6 2021-06-12 07:15:00 2021-06-12 07:25:00
#> 2         6       9 2021-06-12 07:25:00 2021-06-12 07:40:00
#> 3         9      12 2021-06-12 07:40:00 2021-06-12 07:55:00
#> 4        12      15 2021-06-12 07:55:00 2021-06-12 08:10:00

Created on 2022-03-29 by the reprex package (v2.0.1)


text:
Q: Scritp to wait for few seconds before executing next line I have a script which copies(scp) .war file to tomcat's webapps and the .war file extracts creating a folder under webapps directory on a ubuntu system. My next line of the script is restarting the tomcat which is executed immediately before the .war is extracted and this causing problem with
Is it possible so that it waits for few seconds/minutes before it executes the next line of the script. The script is of normal ubuntu commands.

A: sleep <seconds>

A: Use sleep 60 for 1 min.

A: Command sleep allows you to insert breaks to your scripts. For example, sleep 10 would wait 10 seconds before proceeding.


text:
Q: Is it bad for a potential grad schooler to take Abstract Algebra and Real Analysis my last year? I'm taking Abstract Algebra and Real Analysis my last year. I've already taken the following:
Calc 1-3
DiffEQ
Complex Analysis
Operations Research
Linear Algebra
Mathematics Foundations
Theory of Numbers
Advanced Stasticis
I'm worried that grad schoolers won't think I will do good in those courses because I don't have proof of good grades in time of application but I have gotten A's in all the other ones.
What do you think?

A: In my limited experience, the undergrad classes served as the pre-reqs for the grad classes, and the grad classes you take are much more dependent on your course of study and the school you attend. There are grad students at my school who began at the same time as me and I have only had a few courses in common with them (both math majors).
That being said, real analysis is a must. You could probably get away without abstract algebra as long as you know how to write proofs and some key vocabulary (groups, rings, fields, homomorphism, isomorphism, etc.). But again, this may be specific to my personal experience.
I think the best thing to do if you know you are going to study math in grad school is to start taking the math courses that interest you now. No matter what field you end up studying you're going to have to go back and re-visit some undergraduate content that you never studied, don't remember, or wasn't covered in enough detail. That's what your classmates, teachers, and websites like this one are for. Grad school is supposed to be your passion, so do what you like and enjoy yourself!:)


text:
Q: React native setup error (app:processDebugResources FAILED) I'm running a new project of react native on vs code and after installing all possible libraries and environment variables I'm still facing these issues If anyone can help me ill be very thankful to you.
enter image description here


text:
Q: How to fwrite NA values as empty, not empty quotes When I fwrite to csv, I am getting empty quotes for NA values
I would prefer nothing at all
Here is the csv
# csv_in
1,2,,3
4,5,Dave,6

x = fread(csv_in)
fwrite(x, path.csv)

# Output
# 1,2,"",3
# 4,5,Dave,6

# Desired output
# 1,2,,3
# 4,5,Dave,6

I cannot find any way of setting na = to get this output
EDIT
The dput is a clue to the issue
# csv_in
1,2,,3
4,5,Dave,6

structure(list(V1 = c(1L, 4L), V2 = c(2L, 5L), V3 = c("", "Dave"
), V4 = c(3L, 6L)), row.names = c(NA, -2L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x0000000000111ef0>)

# csv_in_alternative
1,2,,3
4,5,,6

structure(list(V1 = c(1L, 4L), V2 = c(2L, 5L), V3 = c(NA, NA),
    V4 = c(3L, 6L)), row.names = c(NA, -2L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x0000000000111ef0>)

Still don't know how to control this behaviour however

A: add quote=F
fwrite(x, path.csv, quote=F)


text:
Q: How to start with 2D Ok my question is simple:
How do I start working with 2D graphics on android? Untill now,I found on the how to make almost anything on Android,however with graphics I see is harder.
On the android sdk website,I get some simple codes that don't really help me,and I also searched for a book,guess what,I didn't find one that actually shows you how to make a little game explaining me what does every line of code.
So: How do I start working with 2D graphics? I'm interested because I want to make some games.I would be very happy to find a tutorial for ex. that shows you how to make a little character that just jumps over a box.I know you need an engine and all that stuff,and I would actually want to learn how to make a little engine.

A: libGDX runs on Android (and a few other platforms) and provides high level 2D graphics features like sprites, fonts, tile maps, particles, etc.
Tutorials here.
A few complete demo games with source code here.

A: Here's a whole series that seems pretty decent, and starts from the beginning.
Also, the techniques of "generic" 2D programming apply, so general-purpose game engine information is useful as well.

A: If you are interested in android games(2d), I recommend this book http://www.amazon.com/dp/1430230428/

A: The following book is very good for learning 2d graphics in Android.
"Android 2D graphics with Canvas API".
http://www.amazon.com/Android-Graphics-Canvas-API-ebook/dp/B00DKIAVK8/ref=sr_1_8?s=books&ie=UTF8&qid=1374420538&sr=1-8&keywords=android+2d
It is not for game developers though.
It teaches how to use graphics primitives and work with different coordinate systems. It also has a chapter on multithreading.
It has many simple examples good for beginners.


text:
Q: Repository of "standard" BDD specs Do you know of any resources or libraries of BDD specs?
For example, almost every web app has a login process. Some "standard" features might be handling of forgotten passwords, reset password, etc.
I'm thinking of something like a code snippet archive of BDD specs so we don't all have to write them from scratch.

A: Jean-Paul S. Boodhoo has created a BDD repository of sorts at http://github.com/developwithpassion/developwithpassion.bdd which from the GitHub description is a "BDD Library (MbUnit Based)"


text:
Q: Markov-Text generating I've been looking in to generate text.
What I've learned so far is that I will have to use word-level Markov-text generation. I've found a few examples of those on this site. here
Now knowing this wouldn't work I tried it anyways and copied it to Processing. With the errors of not finding the correct libraries.
Is there anyone out there that has done this or can point me in a good direction to find more about doing text generation with processing. Or even somebody who want's to do a collab. Being open source and what not.
What I want isn't that more different than the example on the site, except the letter count should be word based and the database is given by words I put in there. The last part could be altered to an other source which I'm still brainstorming about. But could be everything actually with words. If you have any ideas please be free to contribute.
I'll edit this post when I know more from other forums. So when there's a solution I can pass it to others.
EDIT: SOLUTION CLICKBASED GENERATING
// required imports for Processing
import java.util.Hashtable;
import java.util.Vector;

String inputFile = "Sonnet51.txt";
Markov markovChain1;
String sentence = "";

void setup() {
  size (900, 500);
  background(0);

  markovChain1 = new Markov();

  // load text
  String[] input = loadStrings(inputFile);
  for (String line : input) {
    markovChain1.addWords(line);
    println(line);
  }

  // generate a sentence!
  sentence = markovChain1.generateSentence();

  println("-------------");
}

void draw() {
  background(0);
  // noLoop();
  fill(255);
  text(sentence, 19, 190);

  fill(2, 255, 2);
  text("Please press mouse", 19, height-33);
}

void mousePressed() {
  // generate a sentence!
  sentence = markovChain1.generateSentence();
  println(sentence);
}

// ==========================================

class Markov {
  Hashtable<String, Vector<String>> markovChain =
        new Hashtable<String, Vector<String>>();

  Markov() {
    markovChain.put("_start", new Vector<String>());
    markovChain.put("_end", new Vector<String>());
  }

  void addWords(String line) {
    String[] words = line.split(" ");

    for (int i=0; i<words.length; i++) {

      if (i == 0) {
        Vector<String> startWords = markovChain.get("_start");
        startWords.add(words[i]);
        Vector<String> suffix = markovChain.get(words[i]);
        if (suffix == null) {
          suffix = new Vector<String>();
          suffix.add(words[i+1]);
          markovChain.put(words[i], suffix);
        }
      }
      else if (i == words.length-1) {
        Vector<String> endWords = markovChain.get("_end");
        endWords.add(words[i]);
      }
      else {
        Vector<String> suffix = markovChain.get(words[i]);
        if (suffix == null) {
          suffix = new Vector<String>();
          suffix.add(words[i+1]);
          markovChain.put(words[i], suffix);
        }
        else {
          suffix.add(words[i+1]);
          markovChain.put(words[i], suffix);
        }
      }
    }
  }

  String generateSentence() {
    String newPhrase = "";
    String nextWord  = "";
    Vector<String> startWords = markovChain.get("_start");
    int startWordsLen = startWords.size();
    nextWord = startWords.get(int(random(startWordsLen)));
    newPhrase += " " + nextWord;
    while (nextWord.charAt (nextWord.length ()-1) != '.') {
      Vector<String> wordSelection=null;
      wordSelection = markovChain.get(nextWord);
      if (wordSelection!=null) {
        int wordSelectionLen = wordSelection.size();
        nextWord = wordSelection.get(int(random(wordSelectionLen-1)));
        newPhrase += " " + nextWord;
      }
      else
      {
        return newPhrase.toString();
      }
    }
    return newPhrase.toString();
  }
} // class
//

use following text to use for the generator.
Thus can my love excuse the slow offence
Of my dull bearer when from thee I speed
From where thou art why should I haste me thence
Till I return of posting is no need
O! what excuse will my poor beast then find
When swift extremity can seem but slow
Then should I spur though mounted on the wind.
In winged speed no motion shall I know.
Then can no horse with my desire keep pace.
Therefore desire of perfectst love being made.
Shall neigh no dull flesh in his fiery race;
But love for love thus shall excuse my jade.
Since from thee going, he went wilful-slow
Towards thee Ill run, and give him leave to go.

It works completely and now I can begin to change it for making bigger texts. I anybody have ideas let me know. But this case is solved for me.
Thanks to ChrisIr from Processing forum.

A: The RiTa library already does this if you want to take a look at it. Or just use it. http://rednoise.org/rita/

A: I think that code you're using is making things more complicated. This Java example is much clearer, and should work "out of the box" in Processing – just copy/paste!
Here's the Processing-ified version that should work, though I think it might need some tweaking.
// required imports for Processing
import java.util.Hashtable;
import java.util.Vector;

String inputFile = "Sonnet51.txt";
Markov markovChain;

void setup() {
  markovChain = new Markov();

  // load text
  String[] input = loadStrings(inputFile);
  for (String line : input) {
    markovChain.addWords(line);
  }

  // generate a sentence!
  String sentence = markovChain.generateSentence();
  println(sentence);
}

class Markov {
  Hashtable<String, Vector<String>> markovChain = new Hashtable<String, Vector<String>>();

  Markov() {
    markovChain.put("_start", new Vector<String>());
    markovChain.put("_end", new Vector<String>());
  }

  void addWords(String line) {
    String[] words = line.split(" ");
    for (int i=0; i<words.length; i++) {
      if (i == 0) {
        Vector<String> startWords = markovChain.get("_start");
        startWords.add(words[i]);
        Vector<String> suffix = markovChain.get(words[i]);
        if (suffix == null) {
          suffix = new Vector<String>();
          suffix.add(words[i+1]);
          markovChain.put(words[i], suffix);
        }
      } else if (i == words.length-1) {
        Vector<String> endWords = markovChain.get("_end");
        endWords.add(words[i]);
      } else {
        Vector<String> suffix = markovChain.get(words[i]);
        if (suffix == null) {
          suffix = new Vector<String>();
          suffix.add(words[i+1]);
          markovChain.put(words[i], suffix);
        } else {
          suffix.add(words[i+1]);
          markovChain.put(words[i], suffix);
        }
      }
    }
  }

  String generateSentence() {
    String newPhrase= "";
    String nextWord = "";
    Vector<String> startWords = markovChain.get("_start");
    int startWordsLen = startWords.size();
    nextWord = startWords.get(int(random(startWordsLen)));
    newPhrase += " " + nextWord;
    while (nextWord.charAt (nextWord.length()-1) != '.') {
      Vector<String> wordSelection = markovChain.get(nextWord);
      int wordSelectionLen = wordSelection.size();
      nextWord = wordSelection.get(int(random(wordSelectionLen)));
      newPhrase += " " + nextWord;
    }
    return newPhrase.toString();
  }
}


text:
Q: sftp file browser client I am looking for an stfp filebrowser, in either php, flash og as an java applet. I really dont wanna code this myself, since its really time consuming. So i was thinking if anyone know an opensource system that can do this. I know this can be very insecure, but i will only allow certain ips with certain passwords to use it.
Basicly what i want is some kind of filebrowser i can place on my webserver, so i can control the files on my server, witch is the same server i will host it on.
Thanks!

A: Here it is in php:
http://phpseclib.sourceforge.net/


text:
Q: How do I punctuate a list a questions in one sentence in a workbook context? Do I use question marks in place of commas in a sentence that includes several questions? If so, do I follow the question marks with a lower case letter as given in the examples below.
Examples:

Have you felt compelled to be more generous? to stop holding on to things you don't use? to share with others who are in need?
How was the work production today? why? and when do you think that will change?


text:
Q: Using Process.Start and shortPath on one computer it is working and on the other not I'm doing small software that reads from database names of applications to be open and open them automatically.
I developed it on one computer and create installation and install it on a few computers. All have Windows 7 and service pack 1. On all the computers it is working except one.
On this computer I get the following error:

'C:\Users\Pulse\MYDOCU~1\jdjdkjdjskjs.xlsx' could not be found. Check
  the spelling of the file name, and verify that the file location is
  correct.
If you are trying to open the file from your list of most recently use
  files, make sure that the file has not been renamed, moved or deleted.

The path is created correctly and the error is only in the file name. The characters that it creates are different for each execution (although the file name is the same).
The following is the code I use:
StringBuilder shortPath = new StringBuilder(255);
GetShortPathName(fileName, shortPath, shortPath.Capacity);
Process.Start(commandLine, shortPath.ToString());

Where the data for filename and commandLine I read from a Database.
What needs to be corrected here?


text:
Q: div box's in one line hy guys. i have again a lil problem.
Im trying to make a box with some div in a signle line.
the problem is that if i start a new div, its at the top of the one which is before him and not next to him.
i tryed it with float left or border-sizing and display table cell . it all didnt work. http://www.awesom-media.de/umgebung/index.html
its the one with the greenbackground.
in this part should be 4 icon divs . two are already there. and in the red box would come some content wich get showed if the visitors are clicking on each icon.
but the problem is like i said that i cant get the two icons (magicstick and the star ) in one line .

A: Use display: inline-block
DEMO http://jsfiddle.net/kevinPHPkevin/GAA9e/
div {
    width: 50px;
    height: 50px;
    background: #ccc;
    display: inline-block;
}

A: You need to add the css property  each div (magic and wand) to float:left; and the webicons div to clear:left;
#magic { float:left; }
#wand { float:left; }
#webicons  { clear: left; height:110px; }

DEMO - http://jsfiddle.net/J4QWq/3/

A: Try this, I added float: left; to each of your icons and added height: 100%; in .webicons like so :
JSFIDDLE
Hope this helps!


text:
Q: How to use sed to test and then edit one line of input? I want to test whether a phone number is valid, and then translate it to a different format using a script. This far I can test the number like this:
sed -n -e '/(0..)-...\s..../p' -e '/(0..)-...-..../p'

However, I don't just want to test the number and output it, I would like to remove the brackets, dashes and spaces and output that.
Is there any way to do that using sed? Or should I be using something else, like AWK?

A: I'm not sure why you're using a 0 in that position. You're saying "a zero followed by any two characters" in the area code position. Is that really what you mean?
Anyway, you want to use the sed substitution operator with the p command in conjunction with the -n switch. Here's one way to do it:
sed -n 's/(\([0-9][0-9][0-9]\))\s\?\([0-9][0-9][0-9]\)[- ]\([0-9][0-9][0-9][0-9]\)/\1\2\3/p'

A: You can also use something as simple as egrep to validate lines and tr to remove the characters you don't want to see:
egrep "\([0-9]+\)[0-9.-]+" <file> |tr -d '()\-'

Note that it will only work if you don't want to keep any of those characters.

A: This is a more succinct version of Jonathan Feinberg's answer. It uses extended regular expressions to avoid having to do all the escaping that the curly braces would require (in addition to moving the escaping of parentheses from the special ones to the literal ones).
sed -r 's/\(([[:digit:]]{3})\)\s?([[:digit:]]{3})[ -]([[:digit:]]{4})/\1\2\3/'

A: this suggestion depends on how your number format looks like , for example, i assume phone number like this
echo "(703) 234 5678" | awk '
{
 for(i=1;i<=NF;i++){
    gsub(/\(|\)/,"",$i)    # remove ( and )
    if ($i+0>=0  ){ # check if it more than 0 and a number
        print $i
    }
    if (){
       # some other checks
    }
 }
}
'

do it systematically, and you don't have to waste time crafting out complex regex


text:
Q: Sticky position bootstrap 4 Currently, I'm using bootstrap.
I have a nav-bar & a button in which both of them have a sticky position.
I want the nav-bar & the button to stack like this:

*

*------------------------------Nav-bar------------------------------

*------------------------------Button------------------------------

But what actually happens is they overlap each other. in a weird way.

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />

Hire Me

Shop

Social Media

<button class="btn snipcart-customer-signin nav-link"> Sign in</button>

<button class="btn snipcart-checkout nav-link">
                  $0.00
              </button>

MENU

    <button class="btn btn-outline-danger px-5 py-4">Download Now</button>

#logo {
    width: 138px;
}
.bg-dark{
    background-color: #CC2B57 !important;
}
.burger {
    padding-top: 0.5rem;
    padding-right: 0.5rem;
    padding-bottom: 0.5rem;
    padding-left: 0.5rem;
}
.burger-container {
    padding-top: 0.5rem;
    padding-right: 0.5rem;
    padding-bottom: 0.2rem;
    padding-left: 0.5rem;
    background-color: hsla(34,95%,57%,0.78);
}
.burger-text  {
    color: #FFFFFF;
    font-size: 2rem;
    background-color: #FED767;
    padding-right: 0.5rem;
    padding-left: 0.5px;
    text-align: center;
}
.burger-text  {
    color: #FFFFFF;
    font-size: 2rem;
    background-color: #FED767;
    padding-right: 0.5rem;
    padding-left: 0.5px;
    text-align: center;
}
.contact {
  flex-basis: 30rem;
}
.nav-links {
  font-size: 3rem;
  flex-basis: 30rem;
  }
  .nav-bar {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    justify-content: space-between;
    align-items: center;
    opacity: 1;
    clip-path: circle(50px at 100% -10%);
    -webkit-clip-path: circle(50px at 100% -10%);
    display: flex;
    z-index: 1000;
    background-color: #2D2871;
    position: absolute;
    font-family: 'Corben', cursive;
    background-blend-mode: overlay;
    padding-left: 15rem;
    padding-right: 15rem;
}

A: "sticky-top" class that is coming from bootstrap CDN is adding top:0 to your elements.
The elements had other classes , so used the class selector to override the property of that class.
.row.sticky-top, .navbar.sticky-top{
  top: unset;
}


text:
Q: How to redirect output of top command in a file for monitoring purpose of system, i need to redirect the output of top command in a file so i will use/parse it.
i am trying to do same thing but CPU performance stats are not getting saved in a file see
screen shots.
expected output:
[root@v100 /usr/local/bin]# top
last pid:  6959;  load averages:  0.01,  0.03,  0.03                                                                                up 0+02:47:34  17:51:16
114 processes: 1 running, 108 sleeping, 5 zombie
CPU:  0.0% user,  0.0% nice,  1.6% system,  0.0% interrupt, 98.4% idle
Mem: 734M Active, 515M Inact, 226M Wired, 212M Buf, 491M Free
Swap: 4095M Total, 4095M Free

 PID USERNAME  THR PRI NICE   SIZE    RES STATE    TIME   WCPU COMMAND
 1953 root      150  20    0  3084M   635M uwait    2:44  0.00% java
 1663 mysql      46  20    0   400M   139M sbwait   1:29  0.00% mysqld
 1354 root       31  20    0 94020K 50796K uwait    0:24  0.00% beam
 4233 root        1  20    0   122M 23940K select   0:06  0.00% python
 1700 zabbix      1  20    0 20096K  2436K nanslp   0:03  0.00% zabbix_agentd
 1799 zabbix      1  20    0   103M  7240K nanslp   0:02  0.00% zabbix_server
 4222 root        1  30    0   122M 23300K select   0:02  0.00% python
 1696 zabbix      1  20    0 19968K  2424K nanslp   0:02  0.00% zabbix_agentd
 2853 root        1  20    0   126M 29780K select   0:02  0.00% python
 1793 zabbix      1  20    0   103M  7152K nanslp   0:01  0.00% zabbix_server
 1797 zabbix      1  20    0   103M  8348K nanslp   0:01  0.00% zabbix_server
 1752 root        1  20    0   122M 22344K select   0:01  0.00% python
 1796 zabbix      1  20    0   103M  8136K nanslp   0:01  0.00% zabbix_server
 1795 zabbix      1  20    0   103M  8208K nanslp   0:01  0.00% zabbix_server
 1801 zabbix      1  20    0   103M  7100K nanslp   0:01  0.00% zabbix_server
 3392 root        1  20    0   122M 23392K select   0:01  0.00% python
 1798 zabbix      1  20    0   103M  7860K nanslp   0:01  0.00% zabbix_server
 2812 root        1  20    0   134M 25184K select   0:01  0.00% python
 1791 zabbix      1  20    0   103M  7188K nanslp   0:01  0.00% zabbix_server
 1827 root        1 -52   r0 14368K  1400K nanslp   0:01  0.00% watchdogd
 1790 zabbix      1  20    0   103M  7164K nanslp   0:01  0.00% zabbix_server
 1778 zabbix      1  20    0   103M  8608K nanslp   0:01  0.00% zabbix_server
 1780 zabbix      1  20    0   103M  8608K nanslp   0:01  0.00% zabbix_server
 2928 root        1  20    0   122M 23272K select   0:01  0.00% python
 2960 root        1  20    0   116M 22288K select   0:01  0.00% python
 1776 zabbix      1  20    0   103M  7248K nanslp   0:01  0.00% zabbix_server
 2892 root        1  20    0   122M 22648K select   0:01  0.00% python
 1789 zabbix      1  20    0   103M  7128K nanslp   0:01  0.00% zabbix_server
 1814 root        1  20    0   216M 15796K select   0:01  0.00% httpd
 1779 zabbix      1  20    0   103M  8608K nanslp   0:01  0.00% zabbix_server
 1783 zabbix      1  20    0   103M  8608K nanslp   0:01  0.00% zabbix_server
 1800 zabbix      1  20    0   103M  7124K nanslp   0:01  0.00% zabbix_server
 1782 zabbix      1  20    0   103M  8608K nanslp   0:01  0.00% zabbix_server
 1781 zabbix      1  20    0   103M  8608K nanslp   0:00  0.00% zabbix_server
 1792 zabbix      1  20    0   103M  7172K nanslp   0:00  0.00% zabbix_server
 2259 root        2  20    0 48088K  4112K uwait    0:00  0.00% cb_heuristics

If i do:
[root@v100 /usr/local/bin]# top > /tmp/top.output

then it shows:
[root@v100 /usr/local/bin]# cat /tmp/top.output

 last pid:  7080;  load averages:  0.09,  0.06,  0.03  up 0+02:52:24    17:56:06
 114 processes: 1 running, 108 sleeping, 5 zombie

 Mem: 731M Active, 515M Inact, 219M Wired, 212M Buf, 501M Free
 Swap: 4095M Total, 4095M Free

  PID USERNAME  THR PRI NICE   SIZE    RES STATE    TIME   WCPU COMMAND
  1953 root      150  20    0  3084M   633M uwait    2:17  0.00% java
  1663 mysql      46  20    0   400M   136M sbwait   1:08  0.00% mysqld
  1354 root       31  20    0 94020K 49924K uwait    0:18  0.00% beam
  4233 root        1  20    0   122M 23776K select   0:04  0.00% python
  1700 zabbix      1  20    0 20096K  2436K nanslp   0:02  0.00% zabbix_agentd
  1799 zabbix      1  20    0   103M  7240K nanslp   0:01  0.00% zabbix_server
  2853 root        1  20    0   126M 29780K select   0:01  0.00% python
  1696 zabbix      1  20    0 19968K  2424K nanslp   0:01  0.00% zabbix_agentd
  4222 root        1  28    0   122M 23264K select   0:01  0.00% python
  1793 zabbix      1  20    0   103M  7152K nanslp   0:01  0.00% zabbix_server
  1752 root        1  20    0   122M 22344K select   0:01  0.00% python
  1797 zabbix      1  20    0   103M  8088K nanslp   0:01  0.00% zabbix_server
  1796 zabbix      1  20    0   103M  7944K nanslp   0:01  0.00% zabbix_server
  1795 zabbix      1  20    0   103M  8044K nanslp   0:01  0.00% zabbix_server
  1801 zabbix      1  20    0   103M  7100K nanslp   0:01  0.00% zabbix_server
  3392 root        1  20    0   122M 23312K select   0:01  0.00% python
  2812 root        1  20    0   134M 25184K select   0:01  0.00% python
  1798 zabbix      1  20    0   103M  7628K nanslp   0:01  0.00% zabbix_server

so here, I am able to monitor Memory but not CPU
reason is during redirect output of top CPU stats did not update
How can i capture CPU stats also?
if you have any suggestion pls tell me.

A: top -b -n 1 seems to work on my Linux box here (-b: batch mode operation, -n: number of iterations).
Edit:
I just tried it on FreeBSD 9.2 which uses the 3.5beta12 version of top. It seems it needs at least one additional iteration to get CPU stats. So you might want to use:
top -b -d2 -s1 | sed -e '1,/USERNAME/d' | sed -e '1,/^$/d'

-b: batch mode, -d2: 2 displays (the first one does not contain CPU stats, second one does), -s1: wait one seconds between displays
The sed pipeline removes the first display which does not contain CPU stats (by skipping header and process list).


text:
Q: How to configure tomcat java application in apache web server? I just configured the tomcat java application in apache like below.
<VirtualHost *:80>
    ServerName domain.com
    ProxyRequests Off
    ProxyPreserveHost On
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>
    ProxyPass / http://localhost:8080/app_name
    ProxyPassReverse / http://localhost:8080/app_name
</VirtualHost>

Later I enabled site using a2ensite adavipalem.conf and restarted the server.
When I try to access from the browser by hitting like >> domain.com
I got something like below at browser.
    Internal Server Error

    The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator at [no address given] to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Apache/2.4.7 (Ubuntu) Server at adavipalem.com Port 80

Can anyone help me where should I have to change this config?
Regards,

A: I got solved the issue on my own. There is no problem with config what I have mentioned earlier..
<VirtualHost *:80>
    ServerName domain.com
    ProxyRequests Off
    ProxyPreserveHost On
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>
    ProxyPass / http://localhost:8080/app_name
    ProxyPassReverse / http://localhost:8080/app_name
</VirtualHost>

I just forgot to enable the
a2enmod proxy_http

Due to this, I can't able to make the HTTP request ultimately I was stuck at apache itself. Later I enabled proxy_http, Now it is proxying me to tomcat url I can able to refer the tomcat app now.
Thanks


text:
Q: ElasticSearch: "Object field starting or ending with a [.] makes object resolution ambiguous: []" I'm getting the error "object field starting or ending with a [.] makes object resolution ambiguous: []". But there isn't a single dot [.] in my object. Using elasticClient.update() I'm passing:
{
    "index": "applicants",
    "type": "applicant",
    "id": "A01gfGEBKfWmu0nhvuR7",
    "body": {
        "doc": {
            "phsEmploymentHistory": {
                "numSickDaysNotIll": "4",
                "employers": [{
                    "employmentType": {},
                    "": {},
                    "name": null,
                    "supervisor": null,
                    "contactNumber": null,
                    "extension": null,
                    "email": null,
                    "coworker1": null,
                    "coworker2": null,
                    "duties": null,
                    "jobTitle": null,
                    "reasonLeaving": null,
                    "fullTime": null,
                    "partTime": null,
                    "temp": null,
                    "selfEmployed": null,
                    "volunteer": null,
                    "duration": {
                        "startDate": null,
                        "endDate": null
                    },
                    "address": {
                        "street": null,
                        "city": null,
                        "state": null,
                        "zip": null
                    }
                }],
                "agencies": [{
                    "": {},
                    "agencyName": null,
                    "backgroundInvestigator": null,
                    "contactNumber": null,
                    "extension": null,
                    "position": null,
                    "email": null,
                    "stepsCompleted": null,
                    "dateApplied": null,
                    "status": null,
                    "address": {
                        "street": null,
                        "city": null,
                        "state": null,
                        "zip": null
                    }
                }],
                "disciplined": {
                    "response": false,
                    "explanation": ""
                },
                "warnedDrugs": {
                    "response": false,
                    "explanation": ""
                },
                "valid": true
            }
        }
    }
}

I've been over this several times. I don't think the error message is adequate. The "object resolution ambiguous: []" seems to hint that I have an empty array, but I don't.

A: Values of the json could be empty. But if the keys are empty then ES throws error while indexing.
Remove "":{} from the json and index again.
Reference:
https://discuss.elastic.co/t/object-field-starting-or-ending-with-a-makes-object-resolution-ambiguous/123351