text:
Q: Ruby on Rails, how to structure this HAML code to not include some  at top level? if the HAML is:
.class1
  .class2
    .class3
      %div
        content... many lines

How can it be made so that it doesn't respond with class1 and class2 if it is Ajax?
- if !request.xhr?
  .class1
    .class2

.class3
  %div
    content... many lines

won't work, because if not Ajax, then class3 is not a child of class2.  It might have to be something like
- if !request.xhr?
  .class1
    .class2
      .class3
        %div
          content... many lines
- else
  .class3
    %div
      content... many lines

and it is repeating a lot of code.  Can it be structure within the same file?  Or the second part made into a partial?

A: It sounds to me like you do indeed want a partial - the fact there's no good way to do it with this hierarchy is a good sign to me that you want a partial. Then you can use it elsewhere, easily render a collection, or just generally partition that code.
Also, if this need occurs in other places in your project, you might want to consider using different default layouts for your different response formats.
However, you might also consider this pattern:
%div{:class => expr ? 'one' : 'two'}

which will vary the class based on expr. You would still end up with extra divs, but they could be of some other custom class.


text:
Q: Generating a random number excluding 0 from an ArrayList in java static ArrayList<Integer> usedArray = new ArrayList<Integer>();

public static void arrayContents(){

usedArray.add(2, 2);
usedArray.add(1, 1);

}

public static void app(){

    Random generator = new Random ();

    int randomNumber = generator.nextInt(usedArray.size());

    System.out.println(usedArray);

    System.out.println(randomNumber);

    if(randomNumber == 2){
        score();
        question2();
        usedArray.remove(2);
        app();
    }

With
.add(2, 2)

I get an error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0

However using
.add(2)

0 is generated as part of the array, even though it is not a value held within the array. Will arrays always contain 0 by default and is there any way of getting around this so that 0 cannot be generated as the random number ?

A: You are experiencing this problem because when you create the arraylist it has zero size, when you then call usedArray.add(2, 2); you are trying to update the second place in your arraylist with Integer 2; but as I say, the arraylist currently has no number 2 slot. Unless you have a reason for using the .add(index, object) method just add them normally, as .add(object)
usedArray.add(2, 2); //<-- here you update slot 2, putting Integer 2 in it, there is no slot 2 at this point

If this is simply a list of available random numbers you can just use;
usedArray.add(1);
usedArray.add(2);

Now the numbers 1 and 2 are available in the arraylist.
These can then be fetched randomly from the arraylist:
int randomNumber = usedArray.get(generator.nextInt(usedArray.size()));

In this example generator.nextInt(usedArray.size() will produce the number 0 or 1, which will fetch 1 or 2 respectively from the arraylist

A: The problem you have is that you create an empty List typing new ArrayList<Integer>().
You can not use add(int index, E element) because its

Inserts the specified element at the specified position in this list.

for your list that has length equal to 0 an exception occur.
when you use add(E e) its.

Appends the specified element to the end of this list.

As Ted Hopp pointed out in comment

The problem is that you cannot insert beyond the current end of the list.

This mean you can use add(int index, E element), only if index is lover than size.
Additionally when you call
int random = new Random().nextInt(list.size());
Then result is between 0 (inclusive) and list.size() (exclusive). This mean that you will always result some valid index and you do not have to worry about the order.

A: In your code you have removed 2nd position from list and trying to updating it. That's why your getting AIOBE. Use add() or try increase your list size.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple controls in MVC view that modify same model value I have a field in my model - call it 'distance' - and I want to write a view that contains both a checkbox and a textbox.
If the checkbox is checked, the textbox becomes disabled and 'distance' gets the value 0 when the form is submitted.
If the checkbox is not checked, 'distance' gets whatever value is in the textbox when the form is submitted.
Anybody have any guidance how to do this? It's the logic of assigning a model value based on the state of both the controls that confusing me...

A: The UI behaviour can be accomplished with Javascript via an onclick event handler on the checkbox. The only value you need to submit is the input field whose value will be set to 0 or whatever is set manually.
With jQuery you would have:
$('#checkbox_id').click(function() { $('inputfield_id').val('0');

A: The Model behavior depends on what the checkbox represents.  If it's an actual property on the Model, then you will need to check the value server-side as well as (optionally) using aleemb's javascript method.
If a check in that field simply represents a distance of zero, then aleemb's method will suffice.

A: Aleemb's answer worked like a charm, with a couple of minor modifications:
$("#Distance_checkbox").click(function() {
    if ($(this).is(':checked')) {
        $("#Distance_textbox").val(0);
        $("#Distance_textbox").attr("disabled", true);
    }
    else {
        $("#Distance_textbox").val("");
        $("#Distance_textbox").attr("disabled", false);
    }
});


text:
Q: Django TabularInline fields giving error on updating inline fields I have a models like
class Section(models.Model):
    section_title = models.CharField(max_length=200)
    section_tiles = models.ManyToManyField(Tile, blank=True)
    on_menu = models.BooleanField(default=False)
    section_is_active = models.BooleanField(default=True)

    class Meta:
        verbose_name = "Section"
        verbose_name_plural = "Sections"

    def __unicode__(self):
        return self.section_title

class Page(models.Model):
    page_title = models.CharField(max_length=200)
    page_sections = models.ManyToManyField(Section, blank=True)
    on_menu = models.BooleanField(default=False)
    page_is_active = models.BooleanField(default=True)

    class Meta:
        verbose_name = "Page"
        verbose_name_plural = "Pages"

    def __unicode__(self):
        return self.page_title

And at the admin part I have code such as:
class SectionTabularInline(admin.TabularInline):
    model = Page.page_sections.through

    class PageAdmin(admin.ModelAdmin):
        inlines = [SectionTabularInline,]

        list_display =[
        'page_title',
        'on_menu',
        ]

        list_filter =[
        'on_menu',
        ]

        search_fields = [
        'page_title',
        ]

        ordering = ['page_title']

    admin.site.register(Page, PageAdmin)

When I make changes in inline section of the page, Its giving an error "Please correct the errors below." without any additional information. If I remove sections from page and save it, then I can reassign them from scratch. Is there any way to change them without removing them first?

A: From: Save M2M "Through" Inlines in Django Admin
I found my problem: if you want many to many relationship you need to keep your original model's primary key(id).


text:
Q: Django 4 seems to be caching my query. How can I turn it off? The Issue
When I am updating a property (House) on the website.
Say for example, I update the State to Illinois -- the value does not show up in:
all_properties = models.Property.objects.all()

Even adding a new property (house) does not show up in the all_properties value when the UpdateView reloads.
It only shows up if I kill the Django server and restart it.
What can I do so that I have updated data show up on every load of the UpdateView?
Some context
I have a model with 20+ attributes.
This is for a property-listing site (like Airbnb). So there are things like size, bedrooms, city, state, etc.
There needs to be an auto-complete functionality on the textboxes when I am editing these properties.
So for example, State is a text field in my form. When I am adding a 2nd house to my website, the State textbox should suggest values from the previous houses that I have in my system.
(Basically when I type C, it should show California if I have any houses with California already in the DB)
UpdateView
I am using an Update View to show my Property-Edit (House-Edit) page.
I need to pass in all these auto-complete fields inside this Update View so that I can add them to my text boxes.
The code looks like this:
class PropertyUpdateView(LoginRequiredMixin, UpdateView):
    context_object_name = 'property'
    model = models.Property
    form_class = forms.PropertyForm
    template_name = 'desertland/admin/property_update.html'

    extra_context = get_autocomplete_fields()

    def get_success_url(self):
        messages.success(self.request, 'The property was updated successfully.')
        return reverse('property_update', kwargs={'pk': self.object.id})

The extra_content is where I am passing my autocomplete fields.
The get_autocomplete_fields() method is like so:
def get_autocomplete_fields():
    ac_keys = ['state', 'city', 'county', 'zip_code', 'zoning', 'power', 'water_district', 'water', 'access', 'vetting']
    autocomplete_data = {}
    temp_list = {}

    all_properties = models.Property.objects.all()

    # Creating empty dictionaries for the autocomplete fields
    for key in ac_keys:
        temp_list[key] = []
        autocomplete_data[key] = []

    for property in all_properties:
        for key in ac_keys:
            # Creating a key if it does not exist
            if autocomplete_data.get(key) is None:
                autocomplete_data[key] = []

            val = getattr(property, key)

            # Creating an array of distinct values from the property
            if val and val not in temp_list[key]:
                temp_list[key].append(val)
                autocomplete_data[key].append({'value': val, 'label': val})

    return {'autocomplete_data': autocomplete_data}

This function works correctly and generates the Dictionary correctly.
My DB Model looks like this:
class Property(models.Model):
    id = models.AutoField(primary_key=True)
    slug = models.SlugField(unique=True, db_index=True)
    name = models.TextField(null=False, blank=False)
    ... more attributes ...

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Property, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("property_update", kwargs={'id': self.pk})

Some further debugging since I posted this question:

*

*The value is updated in the DB immediately.

*The updated values are shown if I access them via the ListView or the UpdateView. (i.e. it shows up in the input fields or my table).

*It is only reflected via the models.Property.objects.all() if I restart the Django server.

*If I create a new object, the count stays the same inside of the models.Property.objects.all() method. (i.e. even new objects are not reflected even though they are persisted in the DB).

*There is no caching framework active.

*TIMEOUT=0 in my settings.py has no effect.

A: It doesn't show up, because you populate them when class is initialized.
class PropertyUpdateView(LoginRequiredMixin, UpdateView):
    context_object_name = 'property'
    model = models.Property
    form_class = forms.PropertyForm
    template_name = 'desertland/admin/property_update.html'

    # Here is the issue. extra_context is a static variable and
    # get_autocomplete_fields() is called when class is initialized,
    # which in your case means when you start the server.
    extra_context = get_autocomplete_fields()

You have to move this extra context to get_context_data() method.
class PropertyUpdateView(LoginRequiredMixin, UpdateView):
    context_object_name = 'property'
    model = models.Property
    form_class = forms.PropertyForm
    template_name = 'desertland/admin/property_update.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['autocomplete_properties'] = get_autocomplete_fields()
        return context

    extra_context = get_autocomplete_fields()

Here is documentation on adding extra context.


text:
Q: Выравнивание данных Наткнулся на термин Выравнивание данных в статье «Оптимизация кода на C++ (C++11) на примере конкретной задачи». В той статье код оптимизируется путем изменения порядка расположения переменных в структуре.
Почему происходит оптимизация кода, только из-за изменения порядка расположения переменных?

A: На самом деле, столкнуться с негативными последствиями невыравненных данных не так сложно.
Но вопрос был про члены в структурах, а по этому поводу я хотел бы дополнить, что существует интересный инструмент, обнаруживающий вот такие неоптимальности в коде.
Называется этот инструмент - pahole (данная утилита входит в состав пакета dwarves).
Приведу пример ее работы.
1) Код (сокращенный):
#include <stdio.h>
#include <stdlib.h>

struct B
{
    char a1;
    int  b[2];
    char a2;
};

int main(int argc, char *argv[])
{
    struct B b;   // надо, чтобы "подозреваемые" структуры использовались
    return 0;
}

2) Компиляция с отладочной информацией: gcc -g 1.c
3) Запуск анализа: pahole -R a.out
    Ключик -R означает reorganize.
4) Вывод программы:
pahole -R a.out
struct B {
    char                       a1;                   /*     0     1 */

    /* XXX 3 bytes hole, try to pack */

    int                        b[2];                 /*     4     8 */
    char                       a2;                   /*    12     1 */

    /* size: 16, cachelines: 1, members: 3 */
    /* sum members: 10, holes: 1, sum holes: 3 */
    /* padding: 3 */
    /* last cacheline: 16 bytes */
};

Видим, что в нашей структуре имеется "дырка" между a1 и массивом b. Кроме того, замечаем, что вес такой структуры - 16 байт. Попробуем переставить местами члены в структуре следующим образом:
struct B
{
    char a1;
    char a2;
    int  b[2];
};

Вот так будет лучше! "Дырка" все еще присутствует между a2 и массивом b, но теперь "дырка" занимает 2, а не 3 байта, а общий вес структуры снизился до 12 байт.

A: Если честно, то просто не обращайте на это внимания. Такая нанооптимизация не понадобится большую часть вашей жизни. Большая часть проблем решается не перестановкой полей структуры, а вдумчивым переписыванием алгоритмов и выбором подходящих структур данных. Хотя конечно знать про это надо.

Итак, смотрите, в чём дело.
Память компьютера работает следующим образом. Память программы можно представить себе как большой массив байт, а адрес — индекс в этом массиве.
[байт 0] [байт 1] [байт 2] [байт 3] [байт 4] [байт 5] [байт 6] [байт 7]...

(Ну или иногда легче представлять так:
... [байт 7] [байт 6] [байт 5] [байт 4] [байт 3] [байт 2] [байт 1] [байт 0]

— вам ещё предстоит узнать про разницу между Big Endian и Little Endian.)
Байт, как минимально адресуемую единицу памяти, можно адресовать как угодно. Но обычно вы работаете с более крупными единицами. Например, это машинное слово: размер регистра процессора. Для 32-битной архитектуры это четырёхбайтовая структура.
Теперь, байты прекрасно организовываются в четвёрки:
[байт 0] [байт 1] [байт 2] [байт 3] [байт 4] [байт 5] [байт 6] [байт 7]...
[        машинное слово 0         ] [        машинное слово 1         ]...

Но заметьте, что в принципе байты можно бы комбинировать в машинные слова и по-другому:
[байт 0] [байт 1] [байт 2] [байт 3] [байт 4] [байт 5] [байт 6] [байт 7] [байт 8]...
         [          машинное слово         ] [     ещё одно машинное слово     ]...

— машинное слово может начинаться по любому адресу!
Так вот, большинство компьютеров устроено так, что машинные слова, скомбинированные в четвёрки верхним образом читаются быстро, а вот машинные слова второго типа (то есть, те, которые не получаются шагами по 4 от нуля) — медленно. (Хотя требования по выравниванию могут быть и сложнее, и не совпадать с кратностью машинного слова.) Хуже того, очень многие архитектуры вовсе не позволяют читать такие слова, и для того, чтобы прочитать вот такое слово:
[байт 0] [байт 1] [байт 2] [байт 3] [байт 4] [байт 5] [байт 6] [байт 7]...
         [          машинное слово         ]

приходится читать машинные слова по адресу 0 и 4
[байт 0] [байт 1] [байт 2] [байт 3] [байт 4] [байт 5] [байт 6] [байт 7]...
         [    нужно это машинное слово     ]
[     но приходится читать это    ] [              и это              ]

выбирать из них нужные байты, перетасовывать и собирать «вручную» в нужное машинное слово! Понятно, что это сложная и сравнительно дорогостоящая операция.
Поэтому компиляторы языка программирования C (да и большинства других тоже) проводят такую оптимизацию: между полями структуры вставляются незначащие байты для того, чтобы у всех полей было хорошее выравнивание.
Пример: для такой структуры:
struct
{
    char x; // 1 байт
    int y;  // 4 байта
    char z; // 1 байт
};

память выделяется так:
[    ] [    ] [    ] [    ] [    ] [    ] [    ] [    ] [    ] [    ] [    ] [    ]
[  x ] { потерянные байты } [             y           ] [  z ] { потерянные байты }

Если сама структура будет выровнена в памяти (об этом компилятор тоже заботится), то y будет выровнено, и доступ к нему будет быстрым (а на некоторых платформах, напомню, вообще только в этом случае возможен).
Но в этом случае наша структура занимает больше памяти, чем если бы порядок переменных был таким:
[    ] [    ] [    ] [    ] [    ] [    ] [    ] [    ]
[  x ] [  z ] {  потеряно } [             y           ]

Бóльшая структура означает бóльший расход памяти и бóльшие затраты на копирование, чтение этой структуры и тому подобное. Таким образом, переставив поля структуры, мы можем сэкономить.

Обратите внимание, что на самом деле универсальной оптимизации не существует. Например, для разных архитектур компьютера размер машинного слова будет отличаться. Кроме того, и размеры сколько-нибудь сложных данных могут отличаться тоже, а значит вычисленный оптимальный порядок на одной системе может оказаться очень неоптимальным на другой системе.

Дополнительное чтение по теме (на английском): http://www.catb.org/esr/structure-packing/


text:
Q: Topology on the space of compatible almost complex structures in symplectic geometry I have a few fairly generic questions, with a specific application to symplectic geometry in mind. Let me pose the specific problem first:
Let a symplectic manifold $(M,\omega)$ be given. One is naturally led to consider the "space" $\mathcal{J}$ of almost complex structures compatible with $\omega.$ One then shows that this space is non-empty and contractible. Of course, this is really just a set until one equips it with a topology. My basic question is: what is this topology? I can think of one possibility, which rests on the apparent fact (stated without proof in Audin-Lafontaine) that one has a bundle $\mathcal{J}(\omega) \to M$ of compatible almost complex structures, with fiber $\mathcal{J}_p = \{ \text{complex structures of } T_pM \text{ compatible with } \omega_p \}.$ Our space $\mathcal{J}$ is then the space of sections of said bundle.
Working fiberwise, we can see that we have a bijection $\mathcal{J}_p \cong Sp_{2n}/U(n),$ so we could let $\mathcal{J}_p$ inherit the topology of that homogeneous space. Is there a natural way, then, to construct a topology on $\mathcal{J}$ using the topologies on the fibers $\mathcal{J}_p?$
More generally, is there a natural way to topologize the space of sections of a vector bundle that applies to this scenario?
Finally, how would one construct the bundle $\mathcal{J}(\omega)$ from the fibers and the base space? I suppose one could use the fiber bundle construction theorem, but then one would need specific transition maps.

A: The space of smooth sections of a bundle is a subspace of the space of smooth maps from the base to the total space. The natural topology is then the subspace topology once we know how topologize the space of smooth maps between two smooth manifolds. There are many natural topologies on such a space, depending on how many derivatives you want to keep track of. The coarsest topology is the compact-open topology, on the space of continuous maps. The next trick is to embed the target manifold in some Euclidean space. Then you also have $C^k$-topology for each $k$ where you require uniform convergence on compacts of (all) the first $k$ partial derivatives. Lastly, you can also use the $C^\infty$-topology.

A: The Darboux theorem allows us to choose a covering $\{(U_{\alpha},\phi_{\alpha})\}_{\alpha\in A}$ of $M$ by coordinate charts such that $\omega$ restricted to $U_{\alpha}$ is $\sum_{i=1}^{n} dx_{\alpha}^{i}\wedge dy_{\alpha}^{i}$ for local coordinates $(x_{\alpha}^{1},\dots,x_{\alpha}^{n},y_{\alpha}^{1},\dots,y_{\alpha}^{n})$ on $U_{\alpha}$ given by $\phi_{\alpha}$.
The idea is that instead of defining the topology on ${\cal J}$ in terms of the topologies on the fibers ${\cal J}_{p}$ for $p\in M$, we define the topology on ${\cal J}$ in terms of the topologies on the restriction of the bundle ${\cal J}$ to the various $U_{\alpha}$'s.
The restriction of ${\cal J}$ to $U_{\alpha}$ is, as a set, in bijection (via $\phi_{\alpha}$) with the set of all almost complex structures compatible with the standard symplectic form on $\mathbb{R}^n$. Now, assuming we have a suitable topology on the set of all almost complex structures compatible with the standard symplectic form on $\mathbb{R}^n$, we can define a unique topology on the restriction of the bundle ${\cal J}$ to $U_{\alpha}$ such that the bijection of the previous sentence is a homeomorphism. Finally, we can define $U\subseteq {\cal J}$ to be open (where ${\cal J}$ is the bundle of all almost complex structures on $M$) if the intersection of $U$ with the restriction of ${\cal J}$ to $U_{\alpha}$ is open for all $\alpha\in A$.
I leave it as an exercise to determine a suitable topology on the set of almost complex structures on $\mathbb{R}^n$ compatible with the standard symplectic form.
Note that the way I have defined the topology on ${\cal J}$ in this case is not at all dissimilar to the way topologies are defined on fiber (and vector bundles) in general. For example, take a look at "Vector Bundles and K-theory" by Allen Hatcher where he defines many constructions on vector bundles (such as the direct sum, tensor product etc.) - locally, this can be done just as above using suitable trivializations, and then one can pass to the global case also as I have done above.
Hope this helps!


text:
Q: Insert a new database in redis using redis.StrictRedis() I know that Redis have 16 databases by default, but what if i need to add another database, how can i do that using redis-py?

A: You cannot. The number of databases is not a dynamic parameter in Redis.
You can change it by updating the Redis configuration file (databases parameter) and restarting the server.
From a client (Python or other), you can retrieve this value using the "GET CONFIG DATABASES" command. But the "SET CONFIG DATABASES xxx" command will be rejected.


text:
Q: Android navigation component with shared view models A viewmodel lives and dies with an activity or the fragment it is attached to. This has certain ramifications that it is beyond me why isn't anyone asking about (if we get the Navigation architecture into the picture).
According to the latest android blogs and the way navigation framework works , we are recommended to go in the Single Activity Multiple Fragments verse.
Supposedly I have the following app design .
Activity A (Application Entry Point)
----------
Fragment (A) (Uses ViewModel AB)
Fragment (B) (Uses ViewModel AB)
Fragment (C) (Uses ViewModel CDE)
Fragment (D) (Uses ViewModel CDE)
Fragment (E) (Uses ViewModel CDE)

Now since I use shared viewmodels that means my viewmodels would be attached to the activity. However this appears to be leaky. Like if I have traversed all the way from A to E and now come back popping off fragments to fragment B , the viewmodel CDE should be destroyed , but it wont be since it is connected to the activity.
Also we cannot connect our viewmodels to the fragment since we are going to be sharing their data.
The fact that only I am raising this question makes me believe i am at mistake here with my understanding. Would be elated if I could be given a proper insight into the situation.

A: This is really a problem and has been reported to Google.
Fortunately since Navigation 2.1.0-alpha02 (stable in 2.1.0) this problem has been solved. You can find the change log here and the document.

You can now create ViewModels that are scoped at a navigation graph level via the by navGraphViewModels() property delegate for Kotlin users or by using the getViewModelStore() API added to NavController.

First you should select some of fragments in your nav graph designer, then right click on them and choice Move to Nested Graph to create a new graph which will be used as a 'scope' like this:
class DetailFr : Fragment() {
    private val vm: DetailViewModel by navGraphViewModels(R.id.main_nav_graph)
}

You can learn more about Nested Graph here.

A: Since Navigation 2.1.0-alpha02 (stable in 2.1.0), you can create ViewModels with a scope at a level of navigation graph through by navGraphViewModels().
To get a ViewModel not to be attached to an activity or a single fragment, you have to create a nested navigation graph and request instances of the ViewModel in the scope of that graph.
This will cause that while you are inside the nested navigation graph, ViewModel will live and the fragments inside the nested graph will reuse the same instance of the ViewModel.
In this way, you can have several nested navigation graphs, each with a single instance of ViewModel that will be shared among the fragments that make up that graph.
I will follow your same distribution of fragments and ViewModels:
MainActivity (Application Entry Point)
----------
Fragment (A) (Uses SharedViewModelOne) -> navGraphOne
Fragment (B) (Uses SharedViewModelOne) -> navGraphOne
Fragment (C) (Uses SharedViewModelTwo) -> navGraphTwo
Fragment (D) (Uses SharedViewModelTwo) -> navGraphTwo

To achieve this you must follow these steps:

*

*Your build.gradle(Module) should look like this
...
apply plugin: 'kotlin-kapt'

android {
    ...
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

dependencies{
    ...
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    kapt 'androidx.lifecycle:lifecycle-compiler:2.2.0'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.2.1'
    implementation 'androidx.navigation:navigation-ui-ktx:2.2.1'
}

*Select the fragments that will share the same ViewModel and add them to a nested navigation graph.
To do this, select the fragments in your navigation graph designer,
then right click on them and choose Move to Nested Graph
In this example I added FragmentA and Fragment B to navGraphOne and FragmentC and
Fragment D to navGraphTwo.
Find more information about Nested Navigation Graph here

*In Fragment A and Fragment B, request an instance of SharedViewModelOne.
private val modelOne: SharedViewModelOne by navGraphViewModels(R.id.navGraphOne) {
    //defaultViewModelProviderFactory or the ViewModelProvider.Factory you are using.
    defaultViewModelProviderFactory
}

override fun onCreateView(
    ..
): View? {
    ...
    //use binding.lifecycleOwner = viewLifecycleOwner
    //to make sure the observer disappears when the fragment is destroyed
    modelOne.item.observe(viewLifecycleOwner, Observer {
        //do Something
    })
    ...
}

*In Fragment C and Fragment D, request an instance of SharedViewModelTwo.
private val modelTwo: SharedViewModelTwo by navGraphViewModels(R.id.navGraphTwo) {
    //defaultViewModelProviderFactory or the ViewModelProvider.Factory you are using.
    defaultViewModelProviderFactory
}

override fun onCreateView(
    ..
): View? {
    ...
    //use binding.lifecycleOwner = viewLifecycleOwner
    //to make sure the observer disappears when the fragment is destroyed
    modelTwo.item.observe(viewLifecycleOwner, Observer {
        //do Something
    })
    ...
}

*Then to verify that only a single instance of the ViewModels is created and that it is shared among the fragments, override the onCleared() method and add a checkpoint in the init{} of the ViewModel.
For Example:
class SharedViewModelOne : ViewModel() {

    private val _item = MutableLiveData<String>()
    val item : LiveData<String>
        get() = _item

    init {
        Log.d(TAG, "SharedViewModelOne has created!")
    }

    override fun onCleared() {
        super.onCleared()
        Log.d(TAG, "SharedViewModelOne has removed!")
    }
}

After having followed the previous steps, you should be able to create a ViewModel that will be shared among the fragments that belong to the same nested navigation graph said ViewModel will only live while you are inside the graph, if you leave it, it will be destroyed.
If you feel that something is not very clear to you, you can review this repo and clarify your doubts.

A: I assumed this is your issue:

Like if I have traversed all the way from A to E and now come back
  popping off fragments to fragment B , the viewmodel CDE should be
  destroyed , but it wont be since it is connected to the activity.

You wanted to Share Data through between Multiple Fragments using ViewModel, yet you want to ensure the ViewModel's Data would be Destroy when the Fragment Navigate to certain Screen.
My Suggestion Solution for this is:

*

*Create a Destroy Data Function within the ViewModel Class that will Destroy the ViewModel's Data by Overwrite its value to empty value such as ""
class CDEViewModel : ViewModel() {
   var dataString: String = ""

   fun destroyViewModelData() { // Function that will Destroythe Data
       dataString= ""
   }
}

*Now you can Call the destroyViewModelData function in your Fragment whenever you need to make sure the ViewModel Data is being Clear/Destroy
class FragmentE {

private lateinit var cdeViewModel : CDEViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // Initialize your ViewModel
    cdeViewModel = ViewModelProviders.of(this).get(CDEViewModel ::class.java)
}

override fun onStart() {
    super.onStart()

    // Set your Value Here
    cdeViewModel.dataString = "String 1"
}

override fun onStop() {
    super.onStop()

    // Reset/Destroy Data when Screen is Being Close/Navigate to other Screen
    // After Call this function, in Whatever Screen, the ViewModel previous Set ""String 1"" Data is Clear/Destroy and become "" empty value.
    cdeViewModel.destroyViewModelData()
}
}

In your case, You can call destroyViewModelData function at onStop() of FragmentE, so when you have navigate from FragmentE to FragmentB, the CDEViewModel's data are all become "" empty String which mean it have been Reset/Destroy.
Hope this Simple Solution could help. Thank you.

A: Every LifecycleOwner (i.e. a Fragment or an Activity) keeps its models in a ViewModelStore that has a clear() function. However, the clearing sweeps all the models from the ViewModelStore which in your case is undesirable (Both ViewModel AB and ViewModel CDE would be cleared form the Activity's ViewModelStore). One possible solution to this issue is having a per-ViewModel stores that can be safely cleared when necessary:
class MainActivity : AppCompatActivity() {

val individualModelStores = HashMap<KClass<out ViewModel>, ViewModelStore>()

inline fun <reified VIEWMODEL : ViewModel> getSharedViewModel(): VIEWMODEL {
    val factory = object : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            //Put your existing ViewModel instantiation code here,
            //e.g., dependency injection or a factory you're using
            //For the simplicity of example let's assume
            //that your ViewModel doesn't take any arguments
            return modelClass.newInstance()
        }
    }

    val viewModelStore = this@MainActivity.getIndividualViewModelStore<VIEWMODEL>()
    return ViewModelProvider(this.getIndividualViewModelStore<VIEWMODEL>(), factory).get(VIEWMODEL::class.java)
}

    val viewModelStore = this@MainActivity.getIndividualViewModelStore<VIEWMODEL>()
    return ViewModelProvider(this.getIndividualViewModelStore<VIEWMODEL>(), factory).get(VIEWMODEL::class.java)
}

inline fun <reified VIEWMODEL : ViewModel> getIndividualViewModelStore(): ViewModelStore {
    val viewModelKey = VIEWMODEL::class
    var viewModelStore = individualModelStores[viewModelKey]
    return if (viewModelStore != null) {
        viewModelStore
    } else {
        viewModelStore = ViewModelStore()
        individualModelStores[viewModelKey] = viewModelStore
        return viewModelStore
    }
}

inline fun <reified VIEWMODEL : ViewModel> clearIndividualViewModelStore() {
    val viewModelKey = VIEWMODEL::class
    individualModelStores[viewModelKey]?.clear()
    individualModelStores.remove(viewModelKey)
}

}
Use getSharedViewModel() to obtain an instance of ViewModel which is bound to the Activity's lifecycle:
val viewModelCDE : ViewModelCDE = (requireActivity() as MainActivity).getSharedViewModel(/*There could be some arguments in case of a more complex ViewModelProvider.Factory implementation*/)

Later, when it's the time to dispose the shared ViewModel, use clearIndividualViewModelStore<>():
(requireActivity() as MainActivity).clearIndividualViewModelStore<ViewModelCDE>()

In some cases you would want to clear the ViewModel as soon as possible if it's not needed anymore (e.g., in case of it containing some sensitive user data like username or password). Here's a way of logging the state of individualModelStores upon every fragment switching to help you keep track of shared ViewModels:
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    if (BuildConfig.DEBUG) {
        navController.addOnDestinationChangedListener { _, _, _ ->
            if (individualModelStores.isNotEmpty()) {
                val tag = this@MainActivity.javaClass.simpleName
                Log.w(
                        tag,
                        "Don't forget to clear the shared ViewModelStores if they are not needed anymore."
                )
                Log.w(
                        tag,
                        "Currently there are ${individualModelStores.keys.size} ViewModelStores bound to ${this@MainActivity.javaClass.simpleName}:"
                )
                for ((index, viewModelClass) in individualModelStores.keys.withIndex()) {
                    Log.w(
                            tag,
                            "${index + 1}) $viewModelClass\n"
                    )
                }
            }
        }
    }
}

A: Alternatively, if you are unable to perform the suggested solutions, you can simply clear the ViewModel at the Activity level where the shared ViewModel is scoped.
You can do so by doing this:
getActivity().getViewModelStore().clear();

This will ensure that the shared viewmodel has its data cleared.

A: The only solution I found to get the view model from a fragment opened with navigation controller is to do
private val myViewModel by lazy {
        requireParentFragment().childFragmentManager.primaryNavigationFragment?.getViewModel<MyViewModel>()
    }

primaryNavigationFragment is used to get the currently displayed fragment inside the navigation (from this link)


text:
Q: Ajax datatable scrolling for large dataset I have a very large dataset (a few million rows) that I would like to have be scrollable on an HTML page.  I have been using jQuery DataTable Scroller with some success, but I am having some trouble with updating the result with new data (for example, after adding a filter, which I am doing external to DataTable).  I am curious what other tools folks are using for such a problem.
To clarify, I cannot load the entire dataset at once.  With scroller, I have a setup like this:
var oTable = $('#main_table').dataTable({
"bProcessing":true,
"bServerSide":true,
"bDeferRender":true,
"sScrollX":"100%",
"sScrollY":"500px",
"sAjaxSource":"/list/b",
"oScroller": {
"trace":true},
"fnServerParams": function ( aoData ) {
  aoData.push( {"name": "search", "value": $('#fSearch').val() } );
},
"sDom": '<"clear">rtiS'
} );


text:
Q: How to migrate to the latest ruby patch version How to migrate to the latest ruby patch version (say from 1.9.3p286 to 1.9.3p362 or later)

A: 1.9.3-p362 is current, but has some documented errors. 1.9.3-p327 is recommended until they issue a new release.
At that point, do:

*

*rvm get latest

*rvm install 1.9.3 or rvm reinstall 1.9.3
RVM will install the latest version if you don't specify the version number.
Per the documentation, rvm reinstall is equivalent to:
rvm remove  [ruby-string]
rvm install [ruby-string]


text:
Q: Adding items to ChoiceBox> in class DataConstantsNames I have:
public static final ObservableList<Object> IMPORTVARIABLES = FXCollections.observableArrayList(DATE, TIME, new Separator(),OPEN, HIGH, LOW, CLOSE, new Separator(),VOLUME);

I would like to add these variables to a choiceBox in class controller where I have 7 choiceBoxes:
ChoiceBox[] columnName = {choiceboxColumn1, choiceboxColumn2, choiceboxColumn3, choiceboxColumn4, choiceboxColumn5, choiceboxColumn6, choiceboxColumn7};

My question: If I do a for loop such as:
for (int i = 0; i < columnName.length; i++) {
    columnName[i].setItems(DataConstantsName.IMPORTVARIABLES);
}

Everything is fine, but if I try to set items to a single choiceBox, I get this error:

Where am I going wrong?

A: I don't know why SB generated your ChoiceBox with a wildcard (<?>), but you can't set items in a wildcarded lists without type specification.
See http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html for more details.
To make your code compilable either remove wildcards from ChoiceBoxes:
@FXML private ChoiceBox choiceboxColumn1;

or cast variable to specific type:
((ChoiceBox)choiceboxColumn1).setItems(IMPORTVARIABLES);

or
((ChoiceBox<Object>)choiceboxColumn1).setItems(IMPORTVARIABLES);

P.S.: for loop worked for you because you put choiceboxColumn1 into array of plain ChoiceBox. By this you said to compiler to ignore all generics and work with variables in old, java 1.4, style.
You may achieve that using direct set:
ChoiceBox cb = choiceboxColumn1;
cb.setItems(IMPORTVARIABLES);

You can do it due to Java type erasure concept: http://docs.oracle.com/javase/tutorial/java/generics/erasure.html


text:
Q: inner join select statements on itself I have a select statement that is built out of two select statements that are inner joined
SELECT stuff FROM
    (multiple SELECT statements) AS T1
INNER JOIN
    (SELECT stuff FROM
        (multiple SELECT statements same as T1)) AS T2 ON more stuff

What I did was copy paste T1 select statement, is there a way to give T1 a name that can be recognized in the sub query creating T2?
PS Im using MySQL


text:
Q: Load dynamically a ResourceDictionnary I'm having some issues. I want my app to load a ResourceDictonnary dynamically in app.xaml.cs.
This is my code for the moment :
ResourceDictionary theme = XamlReader.Load(???);
Resources.MergedDictionaries.Add(theme);

The problem is, how can I get my ResourceDictionnary stream from the xaml file ? I don't want to copy the xaml file with the exe. It's build action is set to Page and I want to load it.
Can you tell me how to do that ?
Thanks !

A: try using the following code (I call it from my IModule.Initialize)
 Application.Current.Resources.MergedDictionaries
            .Add(new ResourceDictionary
            {
                Source = new Uri(@"pack://application:,,,/My.Application;component/Resources/Resources.xaml")
            });

see the project tree in attached image:


text:
Q: DropboxSDK: What's the benefit of uploadFileChunk: over uploadFile: in DBRestClient? Preamble:
In case you feel that this might be a duplicate of Using iOS Dropbox SDK to do a Chunked Upload of Core Data then I have to disappoint you - my question is not about how to do the upload. Instead, my question is about comparing the pros and cons of two approaches for uploading. That's not covered by the other question, so my question is not a duplicate.
Question:
For uploading a file with the DropboxSDK, there are two methods for two different approaches. The comments only say that one method is "better for file larger than a few megabytes". What are the concrete benefits? The second approach seems to be more difficult to use, so what advantages does it provide?
Here are the two methods as found in the iOS DropboxSDK:
1.
uploadFile:
/* Uploads a file that will be named filename to the given path on the server. sourcePath is the`
   full path of the file you want to upload. If you are modifying a file, parentRev represents the
   rev of the file before you modified it as returned from the server. If you are uploading a new
   file set parentRev to nil. */
- (void)uploadFile:(NSString *)filename toPath:(NSString *)path withParentRev:(NSString *)parentRev
    fromPath:(NSString *)sourcePath;

2.
uploadFileChunk:
/* These calls allow you to upload files in chunks, which is better for file larger than a few megabytes.
   You can append bytes to the file using -[DBRestClient uploadFileChunk:offset:uploadId:] and then call
   -[DBRestClient uploadFile:toPath:withParentRev:fromUploadId:] to turn the bytes appended at that uploadId
   into an actual file in the user's Dropbox.
   Use a nil uploadId to start uploading a new file. */
- (void)uploadFileChunk:(NSString *)uploadId offset:(unsigned long long)offset fromPath:(NSString *)localPath;

A: See https://www.dropbox.com/developers/core/docs#files_put and https://www.dropbox.com/developers/core/docs#chunked-upload.
The former allows for up to 150MB and writes the file in a single HTTP request, so there's no way to resume a failed upload without starting over from the beginning of the file.
The latter allows any size, and any failed upload can be resumed where it left off (by just sending the next chunk).


text:
Q: Inject parameterBagInterface in nested service I have a SearchManager service which can execute search with the specified engine.
// controller

public function searchAction(RequestStack $requestStack, SearchManager $searchManager): Response
{
    // code

    $engine = new ElasticsearchEngine();
    $searchManager->setEngine($engine)->search($requestStack);
    // code
}

class SearchManager {

    private $engine;

    public function __construct(){
    }

    public function setEngine(EngineInterface $engine)
    {
        $this->engine = $engine;
        return $this->engine;
    }
}

class ElasticsearchEngine implement EngineInterface
{
    public function search(RequestStack $requestStack)
    {
        // Here I build the request
        $elasticsearchCommand['from'] = 0;
        $elasticsearchCommand['size'] = 100;
        $elasticsearchCommand['query']['bool']['must'] = ["match_all" => new \stdClass()];
        // so on
        // To continue building the query I need to parse posted data and get elasticsearch formatted query so I use a class to do that
        $formParser = new FormParser($requestStack);
        $elasticsearchCommand['query']['bool']['filter']['bool']['filter'] = $formParser->getFormattedQuery();
    }
}

In FormParser I need for some reasons some app parameter. But all these class are instantiate explicitly and I can't get benefits from auto wiring. How can access ParameterbarInterface without injecting it where it's not needed ? (cascading injection)


text:
Q: TinyMCE 4: How to make toolbar use full width of its fixed_toolbar_container I initialize my tinyMCE Editor like this:
this.editor = tinymce.init({
    ...
    target: anElementRef,
    inline: true,
    theme: 'modern',
    menubar: false,
    statusbar: false,
    fixed_toolbar_container: anotherElementRef,
    ...
 });

The toolbar renders at the correct place, but I want it to take full width of its container element like:

Any ideas how to achieve that? Thanks!


text:
Q: Spring boot catch exception to autoReconnect MYSQL I have a problem with an automatic connection to MySQL. I set up already options:
spring.datasource.url = jdbc:mysql://localhost/dbname?autoReconnect=true
spring.datasource.username = root
spring.datasource.password = xxx
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.testOnBorrow = true
spring.datasource.validationQuery = SELECT 1

I got this error:
This application has no explicit mapping for / error, so you are seeing this as a fallback.
Mon Aug 29, 2016 2:44:10 p.m. EDT
There was an unexpected error (type = Internal Server Error, status = 500).
PreparedStatementCallback; SQL [main_cat SELECT FROM WHERE category_mapping cat =?]; No operations allowed after connection closed .; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.

These options, however, do not cause reconnect. I would do it in a little different way. Namely, I want to catch this exception and restart connection to MySQL.
application.properties:
spring.datasource.url = jdbc: mysql://localhost/dbname?autoReconnect=true
spring.datasource.username = root
spring.datasource.password = zxxxx
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.testOnBorrow = true
spring.datasource.validationQuery = SELECT 1

CategoryRepository (here I would like to catch an exception):
Public Optional <Long> findMainCategory (Long category) {
        String sql = "SELECT FROM main_cat category_mapping WHERE cat =?";
        return Optional.ofNullable (
                jdbcTemplate.queryForObject (sql, Long.class, category));
    }

How can I do this? Any suggestions ?
I'm counting on your help.

A: *

*Try to execute your SQL
SELECT FROM main_cat category_mapping WHERE cat = some_value
from MySQL command prompt or MySQL workbench. I guess, you have an error in query.

*Try to find
conn.close();
in connection initialization method. Probably, your jdbcTemplate using closed connection.


text:
Q: App requests notifications are not appearing in facebook app I've developed a web facebook app with the possibility of invite a friend via a request that appears in the notifications. It works fine in the web version of facebook but in the Facebook app (Android and iOS) the notifications are not appearing.
Some questions here in SO address the same issue but all the solutions (Canvas configuration in the developer console, permissions, set the app live, etc) do not work. In this question: facebook app request notification not showing up in Facebook iOS app for mobile web app the accepted answer is to set an ID of the apple store but write a Native app to show the same content seems an overkill in time in money (Specially considering the time that the Apple store takes to accept and App).
Is there any way to fix this?, seems like before setting the canvas (Web and mobile) was enough, but it is not working.

A: This is actually by design. The actual answer is in the docs:

Requests will only surface on platforms where the game has been
  defined in the app dashboard as having a presence. So for example, if
  an app exists on iOS and Android, but has no Canvas presence,
  recipients will not see requests received via that app appear on the
  desktop web version of Facebook.com as notifications.


text:
Q: Font size without using @media queries? Goal is to have button that is resized depending on the screen size without using @media queries due to the reason Email is built half-way with a specific tool and the main style set isn't editable.
This means that it's not possible to set a content specific style tag for the button, as Gmail app for Android will ignore all secondary style tags.
I've found it should be possible with Viewport typography but for some reason not matter what I've tried, the font size doesn't change on the Android Gmail app.
I suspect the screen resolution is one thing (2960x1440) and possibly also that I cannot add inline viewport to the style.
Current button code:

      CLICK HERE

Is there anything else I could try here?

A: I don't think there is a working solution with real text.
But you might get along with an image – not very elegant though:

Sadly HTML for email is no fun.


text:
Q: Can I use @Viewbag... inside of webgrid column ActionLink format instead of hard-coding the name I have several pages to link to depending on the user level.
Sample: level 1 goes to pageA, level 2 goes to pageB, etc.
Inside of the controller, I set Viewbag.page to which page.
When the webgrid is creating the column below, is there a way to replace "actionName" with the content of Viewbag.page?
@grid.GetHtml(
columns: grid.Columns(
grid.Column("filename", format: @<text> @Html.ActionLink((string)item.filename, "actionName", "controllerName", new { id = item.id}, null) </text> ),

A: If you are redirecting from controller then better go for TempData instead of ViewBag since ViewBag will be null after POST.
here is a code snippet for using dynamic data in cshtml:
@{

var actionName = TempData["actionName"];
}

@Html.ActionLink((string)item.filename, actionName, "controllerName", new { id = item.id }, null) )

you should set value for TempData["actionName"]; from controller based on your level.


text:
Q: Chrome hangs on window.print() but not Ctrl+P Using Chrome Version 22.0.1229.79 m
We provide users with a way of printing the current page from a Javascript menu via:
javascript:window.print();
This works great in IE and FF, but on Chrome, the page hangs for a good 30 seconds before the Print Preview pops up. Interestingly, Ctrl+P or printing from the Chrome menu works instantly (so it's not printing in general, just bringing up the print preview using Javascript).
Thanks in advance.

A: It turns out I had a 30 second timeout for an unrelated feature of the website that was blocking the print Javascript from being executed. FF and IE had no problems running both but apparently Chrome's threading logic prevented it from launching until the other 30 second timeout.
Not completely resolved but this was a red herring... thanks for the help


text:
Q: Increasing the value of a nullable int (int?) I'm using a nullable integer, and increasing that by one in the following way:
        item.addItem = function () {
                //Check if item is already in the table on the right
                if (viewModel.orderedItems.indexOf(this) < 0) {

                    if (isNaN(this.qty) || this.qty == 'undefined' || this.qty <= 0) {
                        //alert('is NaN1')

                        this.qty = 1;
                        //this.qty.value = 0;
                    }
                    //alert(this.qty.value);
                    viewModel.orderedItems.push(this);
                }
                else {
                    if (isNaN(this.qty) || this.qty == 'undefined' || this.qty <= 0) {
                        //alert('is NaN2')
                        this.qty + 1;
                        //this.qty.value = 0;
                    }
                    else {
                        viewModel.orderedItems.remove(this);
                        this.qty = this.qty + 1;
                        viewModel.orderedItems.push(this);

                    }

                }`

Now, this qty shows in an inputfield, where you can change it.
Let's say, I wrote 15 as the quantity, and decided to 'click' to increase it by one, it results '151' (15 +1), instead of 16.
How could I get it to actually increase by one, instead of adding a one?
Thank you for your input.

A: Replace :
this.qty + 1;

By
parseInt(this.qty) + 1;

But you have a problem because something change type of qty value.

A: You can try by converting this string to number using parseInt and add 1 to it
parseInt(this.qty,10) + 1;

where 10 is the radix
You can also use Number
Beside a widely use construct is using Unary_plus which attempts to convert it to number .
So in your case it will be
+this.qty + 1;


text:
Q: Connect Four game in Javascript - how do I detect a horizontal win? I try to code a Connect Four game and define a winner when 4 pieces are aligned horizontally. I haven't moved to the diagonal part yet, want to get this one first.
What I try to achieve - check if the current location (i) and i+6, meaning the next column, same row, have the same player's class.
Problem - "Count" never adds up for horizontal victory.
The problematic part starts from checkForHorizontalVictory.
Pay attention that I switched for loop to go through allSlots.length, not slots.length, as I want all 42 slots. You'll see the rest.
Anyway, how do I write a code to understand where the player's button is, get the index, and check if index+6 (and later -6) has the same class?
var currentPlayer = "player1";
var column = $(".column");
var allSlots = $(column.children());
function switchPlayer() {
    if (currentPlayer === "player1") {
        currentPlayer = "player2";
    } else {
        currentPlayer = "player1";
    }
}
$(".column").on("click", function (e) {
    var col = $(e.currentTarget);
    var slots = col.children();

    for (var i = slots.length - 1; i >= 0; i--) {
        var currentSlot = slots.eq(i);
        var hole = currentSlot.children();

        if (!hole.hasClass("player1") && !hole.hasClass("player2")) {
            hole.addClass(currentPlayer);

            var verticalVictory = checkForVerticalVictory(slots);
            var horizontalVictory = checkForHorizontalVictory(slots);

            if (verticalVictory) {
            }
            if (horizontalVictory) {
            }

            switchPlayer();
            break;
        }
    }
});

function checkForVerticalVictory(slots) {
    var count = 0;
    for (var i = 0; i < slots.length; i++) {
        console.log(slots.length, "this is slots length in vertical");
        var currentSlot = slots.eq(i);
        var hole = currentSlot.children();

        if (hole.hasClass(currentPlayer)) {
            count++;
        } else {
            count = 0;
        }
        console.log(count, "this is count!");

        if (count == 4) {
            alert("you won! ");
            return true;
        }
    }

    console.log("no wins yet ❌");

    return false;
}

function checkForHorizontalVictory(slots) {
    var count = 0;

    for (var i = 0; i < allSlots.length; i++) {
        var thisSlot = allSlots.eq(i);
        var thisHole = thisSlot.children(i);

        if (
            thisHole.hasClass(currentPlayer) && allSlots.eq(i + 6).hasClass(currentPlayer)
        ) {
            count++;
            console.log("this is count", count);
        } else {
            count = 0;
        }

        console.log("this is count", count);

        if (count == 4) {
            // 3. If the counter reaches 4 - we have a win
            alert("you won! ");
            return true;
        }
    }

    console.log("no wins yet ❌");

    return false;
}

A: I can't be sure, since I can't reproduce your issue. But here is what I think:
In the for loop, when it reaches the indexes of the last column and checks for i + 6 it makes allSlots.eq(42) to allSlots.eq(47)... And that ends up in a false. So count gets resetted to zero.
So change the loop too:
for (var i = 0; i < allSlots.length - 6; i++) {

I also would move that after the loop. Notice the condition change.
if (count <= 4) {
  // 3. If the counter reaches 4 - we have a win
  alert("you won! ");
  return true;
}

In short, column #7 was already checked while checking column #6... ;)

EDIT
Using the full code from your gitHub, I changed the way you are checking the holes of a particular row.
First, pass the slot index to checkForHorizontalVictory
So in that function, you know exactly which slot is the starting point of your logic.
You can now get all the slots on the same row by filtering allSlots.
I used Arra.from() to be able to use JS .filter with a modulo of the deducted rowNum.
Then, recreate a jQuery object from that filtered element list.
function checkForHorizontalVictory(currentSlotIndex) {
  var count = 0;
  let rowNum = currentSlotIndex % 6; // rows from 0 to 5, top to bottom
  console.log("rowNum", rowNum);

  // Get a JS array from the jQuery collection
  var thisrow = Array.from(allSlots).filter((s, i) => i % 6 == rowNum);

  console.log("thisrow", thisrow);
  console.log("thisrow length", thisrow.length);

  // Create a jQuery collection from the filtered above
  var $thisrow = $(thisrow)

  for (var i = 0; i < thisrow.length; i++) {
    // var thisrow = allSlots.eq(currentRow);
    console.log(thisrow[i]);

    // Tests to confirm you are checking the right row
    // thisHole.addClass("test");
    // thisHole.text(i)

    if (
      // jQuery object for the specific row
      $thisrow
        .eq(i + 1)
        .children()
        .hasClass(currentPlayer)
    ) {
      count++;
    }

    console.log("this is count", count);

    if (count == 4) {
      console.log("you won! ");
      return true;
    }
  }

  console.log("no wins yet ❌");

  return false;
}

CodePen with your modified code
For fun, uncomment the Tests to confirm you are checking the right row.


text:
Q: Finding a minimum value of an expression I have this question to solve:
A city's temperature of y degrees Celsius on a day in February is given by $y = 16 + 8 \sin \left(\dfrac{\pi t}{12}\right)$ where t is the time in hours after 9am.
a). What is the minimum temperature?
b). At what time is the temperature a minimum?
c). What is the temperature at 5pm?
Any help would be appreciated. Thanks.

A: (b) $0=y'=\frac{2\pi}{3}\cos\left(\frac{\pi t}{12}\right) \Rightarrow t=6 \Rightarrow$ The time at which the temperature is minimal is $3$pm.
(a) In $t=6$, the temperature is minimal. So the minimum temperature is 24 degrees Celsius.
(c) The temperature at 5pm is calculated in $t=8$, ie, $y(8)=16+4\sqrt{3}$.


text:
Q: LM311 Current Sensing Switch I need to create a current sensing switch and am looking for ideas. I have very little experience with op amps / comparitors (as you'll see) but this seems to be the way to go.
I am monitoring 24VDC motor and if current is > 2.6A, I need to signal to a microcontroller to disable the motor.
I have a 175-R10-JBW (.1Ω) shunt resistor and an LM311 comparitor.
My testing shows that when the motor current = 2.6A, the voltage drop across the shunt resistor is ~.01v. When current is 1.3A the voltage drop is ~.005v.
My question is how do I use the LM311 to to state if "-" is .01v > than "+", send low output of LM311?
Of course I do not want to be shown exactly how to do this, just some direction on where to go. I've seen a lot of writing on current monitoring and op amp outputting an analog voltage proportional to motor current, that is just way overkill and would like to simplify.
Below is where I'm at and I know it's not close to where it needs to be. Any input would be greatly appreciated.

A: You need two op-amps.  One to give you the difference between the two volatges, and one to compare that voltage difference to a reference voltage.
Either that or read the voltage difference op-amp output with an ADC input on the microcontroller.
Also, you should investigate "High Side Current Sense Amplifiers" - they are chips specially designed for this purpose. They both calculate the voltage difference between two points and amplify it, and most often run off a lower voltage (3.3V or 5V) than the voltage level they are sensing at (say up to 60V).  I have used the AD8215 before now.


text:
Q: SWT folder '..\framework\x86' does not exist. Please set ANDROID_SWT to point to the folder containing swt.jar for your platform i try to run my android test script by "monkeyrunner cameraTest.py"
but it can't work, the cmd show me this
SWT folder '..\framework\x86' does not exist.
Please set ANDROID_SWT to point to the folder containing swt.jar for your platform.
anyone know how to deal with this?thanks

A: Hope http://blog.csdn.net/zjabc520/article/details/76043741 can help you.
modify:
for /f %%a in ("%APP_HOME%\lib\monkeyrunner-25.3.2.jar") do set jarfile=%%~nxa
set frameworkdir=.
set libdir=

**rem if exist %frameworkdir%\%jarfile% goto JarFileOk**

**rem   set frameworkdir=lib**

**rem if exist %frameworkdir%\%jarfile% goto JarFileOk**

**rem   set frameworkdir=..\framework**

rem add this

**set frameworkdir=..\lib**

:JarFileOk

and then run monkeyrunner,it'll happen adb not found.
next step:
go to your tools folder,create folder name framework.Then copy the adb.exe into framework folder.finally run monkeyrunner again.
good luck

A: In addition to @ohbo's solution, copying AdbWinApi.dll, AdbWinUsbApi.dll into framework folder solved my problem.


text:
Q: Using shell environment variables in Apache configuration conditional statements? I am unclear on whether I can have a variable such as
LAN_ALIAS=some.local.domain

in my shell environment, and conditionally use it to generate a ServerAlias directive:
<MagicalIfEnvVar LAN_ALIAS>
  ServerAlias ${LAN_ALIAS}
</MagicalIfEnvVar>

I've been reading through the Apache documentation, but as you can imagine, searching on "environment variables" (and variations thereof) leads to a lot of unhelpful references.
Any way to do something like that in Apache2.2?


text:
Q: WinRT XAML Textbox, SelectionStart and CR/LF I am using a simple multiline TextBox in one of my Windows Store Apps and I would like to enable use of tab to indent the text.
Since WinRT doesn't have the XAML AcceptsTab property on the TextBox I figured I'd have to handle it per hand when I detect the Tab keystroke.
The problem is: \r\n seems to be handled as one character instead of two by the SelectionStart property and I don't get the real char position.
The only idea I have right now is to normalize the SelectionStart by parsing the text and adding 1 to the SelectionStart for each of the \r\n occurences I see before the caret.
public static class TextBoxExtension
{
    public static int GetNormalizedSelectionStart(this TextBox textBox)
    {
        int occurences = 0;
        string source = textBox.Text;

        for (var index = 0; index < textBox.SelectionStart + occurences ; index++)
        {
            if (source[index] == '\r' && source[index + 1] == '\n')
                occurences++;
        }
        return textBox.SelectionStart + occurences;
    }
}

Finally the SelectionStart gets reseted to 0 after the manipulation, so I have to set it back to the correct position, this time using the non normalized position. Here's the caller:
if (e.Key == VirtualKey.Tab)
{
    int cursorIndex = MainTextBox.SelectionStart;
    int cursorIndexNormalized = MainTextBox.GetNormalizedSelectionStart();
    MainTextBox.Text = MainTextBox.Text.Insert(cursorIndexNormalized, "\t");
    MainTextBox.SelectionStart = cursorIndex + 1;
    e.Handled = true;
}

It works but... have I reinvented that round thing again? Is there a cleaner way to do this?

A: It seems that you have to do a "Ctrl + Tab" to actually insert a tab in your textbox. Therefor all you have to do is something like this
TextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
      if (e.KeyCode == Keys.Tab)
      {
          e.Handled = true;
          SendKeys(^{TAB});
      }
}

The ^ represents the CTRL key and the TAB your tab key. Using this combination you are able to use Tab normally in your application


text:
Q: EditText Label? I want to have some layout a bit like this
[text tabel][edittext]

i cant find an attribute like html esque label. It seems to be the case that i need to use
[TextView][EditText]

but i cant get them to go on the same line this is my xml file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">"
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/boat_1"/>
<EditText
    android:id="@+id/entry"
    android:hint="@string/IRC"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:drawable/editbox_background"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/boat_2"/>
<EditText
    android:id="@+id/entry"
    android:hint="@string/IRC"
    android:minWidth="100dip"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:drawable/editbox_background"/>
<Button android:id="@+id/close"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="@string/title_close" />

A: TextInputLayout is the answer.
Just use the correct version from the android material library:
https://developer.android.com/reference/com/google/android/material/textfield/TextInputLayout
The android:hint param will display the label in the text area, and when you click on it label will be moved above the text field.
<com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/points">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:id="@+id/points_gs_input"
            android:layout_height="wrap_content" />

</com.google.android.material.textfield.TextInputLayout>

A: You have basically two options:
Option 1: Use nested LinearLayouts:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/boat_1"/>
<EditText
    android:id="@+id/entry"
    android:hint="@string/IRC"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:drawable/editbox_background"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/boat_2"/>
<EditText
    android:id="@+id/entry"
    android:hint="@string/IRC"
    android:minWidth="100dip"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:drawable/editbox_background"/>
</LinearLayout>
<Button android:id="@+id/close"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="@string/title_close" />

Notice that I'm using android:orientation="horizontal" for those nested layouts.
Option 2: you can use another content manager, like RelativeLayout.
The advantage of this, is that you can avoid nesting, thus your layout will be easier to read/maintain/inflate. This is a brief example:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/text_view_boat1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/boat_1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"/>
    <EditText
        android:id="@+id/entry"
        android:hint="@string/IRC"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_toRightOf="@+id/text_view_boat1"
        android:layout_alignParentTop="true"/>
    <TextView
        android:id="@+id/text_view_boat2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/boat_2"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/text_view_boat1"/>
    <EditText
        android:id="@+id/entry2"
        android:hint="@string/IRC"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_toRightOf="@+id/text_view_boat2"
        android:layout_below="@id/entry"/>
</RelativeLayout>

A: The design support library has the TextInputLayout which animates the hint text turning it into a label when the user starts typing and can also show a red error message.
https://developer.android.com/reference/android/support/design/widget/TextInputLayout.html

A: Your LinearLayout has the attribute android:orientation="vertical" so of course everything is going to be displayed vertically within it.
Try wrapping a TextView and EditText with a LinearLayout that has android:orientation="horizontal"


text:
Q: fixing headers and column table Hi I have used a recent suggestion by @leandriis to fix the headers table, but when I tried to use his suggestion to draw another table, I'm getting several issues, here my suggestion, my output and the desired table to produce.
My suggestion :
    \documentclass{article}
    \usepackage{geometry}
    \usepackage{rotating}
    \usepackage{booktabs, makecell}
    \usepackage[referable]{threeparttablex}
    \usepackage{siunitx}
   \usepackage[skip=1ex]{caption}
   \usepackage{xcolor}
   \newcommand\tc[1]{\textcolor{blue}{#1}}
   \NewExpandableDocumentCommand\mcc{O{1}m}
   {\multicolumn{#1}{>{\bfseries}c}{#2}}
   \usepackage{multirow}
   \renewcommand{\theadfont}{\normalsize}

 \begin{document}
 \begin{table}[h!]
 \centering
 \begin{threeparttable}
  \caption{Forecasting and encompassing test results for the bagging model and combining methods,
   1995:04–2005:03 out-of-sample period}
   \label{tab1}
   \begin{tabular}{@{} >{\itshape}l
               *{8}{S[table-format=1.2]}
                }
  \toprule
  \multirow{2.1}{*}{Combining method}
  & \mcc[4]{$\thead{H_{0}$: BA encompasses CB}}
  & \mcc[4]{$\thead{H_{0}$: CB encompasses BA}}   \\
  \cmidrule(r){2-5} \cmidrule(l){6-9}
  & \mcc{\hat{\lambda}_{CB}} & \mcc{MHLN_{h}} & \mcc{P-value}
  & \mcc{\hat{\lambda}_{CB}} & \mcc{MHLN_{h}} & \mcc{P-value}\\
  \midrule
  BA model&9.13& & & & & \\
  Mean            & 0.35& 2.42\tc{**} & 0.01& 0.65& 3.54\tc{**} & 0.00\\
        Median          & 0.32& 2.38\tc{**} & 0.01& 0.68& 3.77\tc{**} & 0.00\\
        Trimmed mean    & 0.34& 2.39\tc{**} & 0.01& 0.66& 3.67\tc{**} & 0.00\\
        DMSE,$\Psi=1.00$& 0.35& 2.42\tc{**} & 1.00& 1.10& 3.54\tc{**} & 0.00\\
        DMSE,$\Psi=0.90$& 0.35& 2.41\tc{**} & 1.00& 1.10& 3.55\tc{**} & 0.00\\
        C(2, PB)        & 0.34& 2.34\tc{**} & 0.01& 0.66& 3.59\tc{**} & 0.00\\
        C(2, PB)        & 0.36& 2.33\tc{**} & 0.01& 0.64& 3.43\tc{**} & 0.00\\
        PC              & 0.59& 2.79\tc{**} & 0.00& 0.41& 2.14\tc{**} & 1.00\\
  \bottomrule
\end{tabular}
 \end{threeparttable}
 \end{table}
 \end{document}

my output:

Desired Table :

A: In the following MWE, I first of all made sure, the code is compilable. Your original code was not compilable and resulted in a bunch of error messages due to various syntax errors. As soon as you get an error message, do not look as the resulting pdf file, but fiy the error mesages first. If you can't ask a specific question about this error message, but don't ignore them.
I added some small comments regarding all the changes I made to your code hoping that this will help you understand the reason for all these changes.

\documentclass{article}
\usepackage{geometry}
\usepackage{rotating}
\usepackage{booktabs, makecell}
\usepackage[referable]{threeparttablex}
\usepackage{siunitx}
\usepackage[skip=1ex]{caption}
\usepackage{xcolor}
\newcommand\tc[1]{\textcolor{blue}{#1}}
\NewExpandableDocumentCommand\mcc{O{1}m}
{\multicolumn{#1}{>{\bfseries}c}{#2}}
\usepackage{multirow}
\renewcommand{\theadfont}{\normalsize}

 \begin{document}
 \begin{table}[h!]
 \centering
 \sisetup{table-format=1.2, table-column-width=1cm} % added. Setting are applied to all S type columns in this particular table, made all S type columns slightly wider to avoid uneven column widths due to too long shared header
 \begin{threeparttable}
  \caption{Forecasting and encompassing test results for the bagging model and combining methods,
   1995:04–2005:03 out-of-sample period}
   \label{tab1}
   \begin{tabular}{@{} >{\itshape}l
                       S  % suitable column type for the "MSFE" column
               *{2}{S S[table-space-text-post=\tc{**}] S} % added table-space-text-post option for all "MHLN" columns, since they not only contain numbers, but also asterisks. Added in order to avoid overfull boxes, to regular S type columns for the \labmda_CB and P value columns
                }
  \toprule
  % \multirow removed, moved text to next row
  & & \mcc[3]{$H_{0}$: BA encompasses CB}  % added another & here,  \thead reomved here sinye you don't need manual linebreaks here
  & \mcc[3]{$H_{0}$: CB encompasses BA}   \\  % \thead reomved here sinye you don't need manual linebreaks here
  \cmidrule(r){3-5} \cmidrule(l){6-8} % corrected \cmidrule commands.
 Combining method & {MSFE} & \mcc{$\hat{\lambda}_{CB}$} & \mcc{$MHLN_{h}$} & \mcc{P-value}   % added "Combining method"  and " MSFE & " here,  math mode ($...$) added since neither \lambda not _ for subscripts can be used in text mode. Do not ignore error messages!
  & \mcc{$\hat{\lambda}_{CB}$} & \mcc{$MHLN_{h}$} & \mcc{P-value}\\ % math mode ($...$) added since neither \lambda not _ for subscripts can be used in text mode. Do not ignore error messages!
  \midrule
  \multicolumn{8}{c}{A. $h=1$}\\ % added \multicolumn[1}{c}  for horizontally centered text here
 BA model        & 0.90 & 9.13 & & & & & \\ % added MSFE column here
 Mean            &      & 0.35 & 2.42\tc{**} & 0.01& 0.65& 3.54\tc{**} & 0.00\\
 Median          &      & 0.32 & 2.38\tc{**} & 0.01& 0.68& 3.77\tc{**} & 0.00\\
 Trimmed mean    &      & 0.34 & 2.39\tc{**} & 0.01& 0.66& 3.67\tc{**} & 0.00\\
 DMSE,$\Psi=1.00$&      & 0.35 & 2.42\tc{**} & 1.00& 1.10& 3.54\tc{**} & 0.00\\
 DMSE,$\Psi=0.90$&      & 0.35 & 2.41\tc{**} & 1.00& 1.10& 3.55\tc{**} & 0.00\\
 C(2, PB)        &      & 0.34 & 2.34\tc{**} & 0.01& 0.66& 3.59\tc{**} & 0.00\\
 C(2, PB)        &      & 0.36 & 2.33\tc{**} & 0.01& 0.64& 3.43\tc{**} & 0.00\\
 PC              &      & 0.59 & 2.79\tc{**} & 0.00& 0.41& 2.14\tc{**} & 1.00\\
  \bottomrule
\end{tabular}
 \end{threeparttable}
 \end{table}
 \end{document}


text:
Q: Не записывать значение в сессию Есть значение, точное название я его не знаю, оно автоматически передаётся в переменную сессии PHPSESSID, как вытащить это значение из PHPSESSID?

A: Всё просто:
print_r($_SESSION);

Выведет весь массив значений, содержащихся в сессии.
Рекомендую ознакомиться с документацией

A: Вероятно вы ведете речь об имени сессии. Получить его можно через функцию session_name()
<?php
session_start();

var_dump(session_name()); // выводим имя текущей сессии


text:
Q: get data, between 2 strings using python and re with the following text:
Style No. Pic Color Size Qty Unit Price Amount
T5890
NAVY STRIPE/… 0 $10.00 $0.00
BACK
ORDERED
NAVY STRIPE/… 6 $10.00 $60.00
BACK
ORDERED
NAVY STRIPE/… 6 $10.00 $60.00
BACK
ORDERED
NAVY STRIPE/… 0 $10.00 $0.00
BACK
ORDERED
NAVY/RED 0 $10.00 $0.00
BACK
ORDERED
NAVY/RED 6 $10.00 $60.00
BACK
ORDERED
D7077
IVORY/BURG… 0 $11.00 $0.00
D7077
BACK
ORDERED
IVORY/BURG… 0 $11.00 $0.00
BACK
ORDERED
IVORY/BURG… 6 $11.00 $66.00
BACK
ORDERED
IVORY/CHAR… 6 $11.00 $66.00
BACK
ORDERED
D7110
BURGUNDY 6 $17.50 $105.00
D7110
BACK
ORDERED
JADE 12 $17.50 $210.00
BACK
ORDERED
MUSTARD 6 $17.50 $105.00
BACK
ORDERED
T5895
BURGUNDY 6 $10.50 $63.00
T5895
BACK
ORDERED
MOCHA 6 $10.50 $63.00
BACK
ORDERED
NAVY 6 $10.50 $63.00
BACK
ORDERED
1/211/14/2019 Order Detail

Using the following iten_no
item_numbers = ['T5890', 'D7077', 'D7110', 'T5895']

I've been strugling getting colors for every item_number, also tried to use the previous item_number to get all the text between the previous and the actual item_number, but i wasnt succesful; the output of this shoud be:
{
'item_no' : 'T5890',
'color' : [
'NAVY STRIPE/…',
'NAVY STRIPE/…',
'NAVY STRIPE/…',
'NAVY STRIPE/…',
'NAVY/RED',
'NAVY/RED'
]
},
{
'item_no' : 'D7077',
'color' : [
'IVORY/BURG…',
'IVORY/BURG…',
'IVORY/BURG…',
'NAVY STRIPE/…',
'IVORY/CHAR…'
]
},
{
'item_no' : 'D7110',
'color' : [
'JADE',
'MUSTARD',
'BURGUNDY'
]
},
{
'item_no' : 'T5895',
'color' : [
'MOCHA',
'NAVY'
]
}
Any info that you can provide me will be highly apretiated.
Best regards.

A: Try that out:
result = []
temp_nums = []
numbers = list(set(re.findall('[A-Z]\d+', need_to_parse_string)))
temp_key = ''
for item in aaa.split('\n')[1:-2]:
    if item in numbers and item not in temp_nums:
        temp_key = item
        temp_nums.append(item)
        result.append({'item_co': item, 'color': []})
    elif item in numbers and item != temp_key:
        temp_key = item
    elif item not in ['ORDERED', 'BACK'] and item not in numbers:
        result[temp_nums.index(temp_key)]['color'].append(re.split('\s\d', item)[0])

for h in result:
    print(h)

where need_to_parse_string - variable where stored required to parse string
It's a bit meaty and have different result from yours, but visible, it works ok
numbers generated from the string, as well, but that step can be removed


text:
Q: Basic firestore get request problem in simple Gatsby website I have created a simple get request, but I am unsure what to do as it has asked for a key. This is a reduced version of my code:
import React, { Component, useEffect } from 'react';
import firebase from "gatsby-plugin-firebase";

var db = firebase.firestore();

var word1 = db.collection("menue").doc("word1");

 class newMenue extends Component {

     constructor(props) {
         super(props)
         this.state = {
              wordOne: "",
         }
     }

    render() {

        word1.get()
        .then(doc => {
          if (!doc.exists) {
            console.log('No such document!');
          } else {
            console.log('Document data:', doc.data());
            this.setState({
                wordOne: doc.data()
            })
          }
        })
        .catch(err => {
          console.log('Error getting document', err);
        });

        return (

{this.state.wordOne}

4 Slices of grilled Cypriot Halloumi

        )

        }
    }

export default newMenue

this is my database:
Document data: {One: "hi"}

This is what the dev tools states.

Error: Objects are not valid as a React child (found: object with keys
  {One}). If you meant to render a collection of children, use an array
  instead.

What do I do in order to add the key to display the information?
Specifically, I am trying to set up a website for my friend's burger place where he can put in the menu changes on the website himself and I am stuck at this last bit.

A: You are trying to render an object:

{this.state.wordOne}
 // which is {One: "hi"}
You need to render the property of the object:

{this.state.wordOne.One}


text:
Q: How can I get Eclipse PHP-IDE to collapse #regions with PHP like Visual Studio does with C#? Ever since I've seen a .NET/C# developer encapsulate code in regions and have Visual Studio collapse the code I started encapsulating my php code in regions. Not quite as much fun (or as useful) when I can't collapse regions in my IDE. Can anyone help?

A: Some where I read about coffee-bytes, which you can use on eclipse to attain region wise code folding.


text:
Q: MDI Application Main Menu help We are developing an MDI Application. What we need to do is that I Have 4 child forms and 1 Parent form. on the parent form ToolBox menu I have 3 buttons. Add,Save,Cancel.
What I want to do is What ever the child form has loaded. When these buttons clicked they should process the action on the child form.
LEts say, If my child form named CustomerManager is open, then by pressing the add button it should basically process my CustomerManager child form. Obviously I will right the logic against every form action Button.
I hope I am able define what I am looking for.
Regards
Shax

A: This is best done by declaring an interface:
public interface IChildCommands {
    void Add();
    void Save();
    void Cancel();
}

And let your MDI child form implement it:
public partial class Form2 : Form, IChildCommands {
   // Right-click IChildCommands in the editor and choose Implement Interface
   //...
}

In your parent, implement the Click event for the toolbar button like this:
    private void AddButton_Click(object sender, EventArgs e) {
        var child = this.ActiveMdiChild as IChildCommands;
        if (child != null) child.Add();
    }

It is also a good idea to disable the button if a child is active that doesn't implement the command.  Which you can do by writing an event handler for the Application.Idle event:
    void Application_Idle(object sender, EventArgs e) {
        AddButton.Enabled = this.ActiveMdiChild is IChildCommands;
        // etc..
    }


text:
Q: Android Cloudant sync query as docs say( https://github.com/cloudant/sync-android/blob/master/doc/query.md) im trying to do a query inside a list
look:
query.put("codigo", 4);
            result = q.find(query);
            for (DocumentRevision revision : result) {
                Log.d("QueryTest", "Test1 :" + revision.getBody().toString());
            }

return:

{      "codigo":4,    "companies":[
        {
           "id":"b9f19d88-13c0-40e3-89de-63dc787afb4c",
           "name":"Filial 0 1488949817178"
        },
        {
           "id":"f17fb098-316e-4d33-a0f7-f5719bf9d62e",
           "name":"Filial 1 1488949817178"
        }    ],    "employees":[
        {
           "codigo":2891,
           "id":"cc54fa37-0b64-4108-869a-1303c6176ce5",
           "name":"Employee 0 79ed4"
        },
        {
           "codigo":4642,
           "id":"19b76bbc-82c7-4295-a385-82ac2d892458",
           "name":"Employee 1 e1102"
        }    ],    "id":"ef2d0ebf-50b9-4cd0-9aaf-5389bccaaa56",    "nome":"Random 4" }

so its ok
but this query doesnt work:
query.put("employees.codigo",  2891);

first return:

QuerySqlTranslator: No single index contains all of
  [{employees.codigo={$eq=2891}}]; add index for these fields to query
  efficiently

after created the index:
Index i = q.createJsonIndex(Arrays.<FieldSort>asList(new FieldSort("employees.codigo")), null);

return

QueryExecutor: Projection fields array is empty, disabling project for
  this query

so i created the arraylist of fields to filter
List<String> fields = Arrays.asList("codigo");
result = q.find(query, 0 , 0 , fields, null);

nothing returned

adding more one field to filter:
    query.put("codigo",4)
query.put("employees.codigo",  2891);

returned: Complain about index

Created another index:
    i = q.createJsonIndex(Arrays.<FieldSort>asList(new FieldSort("employees.codigo"), new FieldSort("codigo")), null);

returned: Nothing

whats is wrong?
How can i get document by child and how can i get ONLY the children?
thanks

A: I think this is unsupported, see the doc on unsupported features, specifically the highlighted entry:

Arrays

*

*Dotted notation to index or query sub-documents in arrays.

*Querying for exact array match, { field: [ 1, 3, 7 ] }.

*Querying to match a specific array element using dotted notation, { field.0: 1 }.

*Querying using $all.

*Querying using $elemMatch.


text:
Q: .htacess existing URL from old domain, redirects to index.php on new domain Problem
I have a new TYPO3 website on a new domain. All important pages of the old website point to their new counterpart for which I added individual 301 redirects in the .htaccess. Those work fine!
However there are pages which have the exact same URL as the old website, which I cannot add individual redirects for (infinite loop). For example /contact/. When I access http://www.example-old.com/contact/ the page simply redirects to /index.php. Why?
Wishlist

*

*All non-www should be redirected to www (works)

*Other domains should be redirected to new (works)

*Referrals from the old website, should be redirected to the same URL on the new domain, unless a manual 301 redirect is in place. (does not work)
Current setup
This is the .htacess snippet I'm working with:
<IfModule mod_rewrite.c>

# Enable URL rewriting

RewriteEngine On
RewriteBase /

# Point old domain to new domain

RewriteCond %{HTTP_HOST} ^example-old\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^example-new\.com$ [NC]
RewriteRule ^(.*) http://www.example-new.com/$1 [R=301,L]

# Point idle domains to new domain

RewriteCond %{HTTP_HOST} ^/?(?:www\.)?example-01.nl [OR]
RewriteCond %{HTTP_HOST} ^/?(?:www\.)?example-02.de [OR]
RewriteCond %{HTTP_HOST} ^/?(?:www\.)?example-03.eu [OR]
RewriteCond %{HTTP_HOST} ^/?(?:www\.)?example-04.net [OR]
RewriteCond %{HTTP_HOST} ^/?(?:www\.)?example-05.org
RewriteRule ^(.*)$ http://www.example-new.com/$1 [R=301,L]

</IfModule>

I have tried every combination I could find to try and get this to work. What could be going wrong here?
Many Thanx!

A: Try to remove the leading "/?" and the inner "?:" also escape the last dot from your http host conditions:
RewriteCond %{HTTP_HOST} ^(www\.)?example-01\.nl$ [OR]
RewriteCond %{HTTP_HOST} ^(www\.)?example-02\.de$ [OR]
RewriteCond %{HTTP_HOST} ^(www\.)?example-03\.eu$ [OR]
RewriteCond %{HTTP_HOST} ^(www\.)?example-04\.net$ [OR]
RewriteCond %{HTTP_HOST} ^(www\.)?example-05\.org$
RewriteRule ^(.*)$ http://www.example-new.com/$1 [R=301,L]

A: If you remove the ^ from the first RewriteCond all request to the old domain will be redirected to the new domain.
If you want the specific redirects to have priority make sure you put them before this one.
# Point old domain to new domain

RewriteCond %{HTTP_HOST} example-old\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^example-new\.com$ [NC]
RewriteRule ^(.*) http://www.example-new.com/$1 [R=301,L]


text:
Q: pass uigesturerecognzer data to parent controller There is a master view controller with this method
- (void)revealGesture:(UIPanGestureRecognizer *)recognizer{
}

which works when I send it a mesage froma  child viewcontroller using a swipe:
UIPanGestureRecognizer *navigationBarPanGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self.navigationController.parentViewController action:@selector(revealGesture:)];
[self.navigationController.navigationBar addGestureRecognizer:navigationBarPanGestureRecognizer];

I want to pass the message on from within the child viewController so I can do some house keeping first
    UIPanGestureRecognizer *navigationBarPanGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(revealGesture:)];
    [self.navigationController.navigationBar addGestureRecognizer:navigationBarPanGestureRecognizer];

and
- (void)revealGesture:(UIPanGestureRecognizer *)recognizer
{
    [displaySearch resignFirstResponder];
    RevealController *revealController = [self.navigationController.parentViewController isKindOfClass:[RevealController class]] ? (RevealController *)self.navigationController.parentViewController : nil;

    NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys: recognizer, @"recognizer", nil];

    [revealController performSelector:@selector(revealGesture:) withObject:data];
}

Yes, all I'm trying to do is dismiss the keyboard before carrying on with a bit of code that works fine if I just target 'self.navigationController.parentViewController' directly
How do I add (UIPanGestureRecognizer *)recognizer to the NSDictionary?
My code crashes with
-[__NSCFDictionary state]: unrecognized selector sent to instance 0x8619860
2013-05-02 21:12:05.752 PwC UK[57884:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary state]: unrecognized selector sent to instance 0x8619860'

EDIT Proposed solution worked but keyboard didn't respond, needed to chage the line to
[self searchBarCancelButtonClicked:searchBar];

where searchBar is instance of UISearchBar

A: It looks like revealGesture is expecting a UIPanGestureRecognizer as its parameter but you are passing an NSDictionary. Try passing the gesture recognizer directly.
[revealController performSelector:@selector(revealGesture:) withObject: recognizer];


text:
Q: String.Parse() To Custom Object Using Specified Format EDITED TO REWORK AND (HOPEFULLY) SIMPLIFY THE QUESTION
I was working on a method for taking a String value and splitting it into its component parts for populating a custom structured object when a question occurred to me: Methods exist for parsing strings into "well-known" objects like System.Net.IPAddress or System.DateTime (e.g., DateTime.Parse(), DateTime.TryParse(), or DateTime.ParseExact()), but these objects use well-defined structures that don't change.
Nothing (at least, that I've been able to find) is available that can "quickly" parse a string into a custom-defined object/structure. Is there a way to achieve the same result by basically "reversing" the functionality of either the base String.Format() method or string interpolation to extract a target object's property/field values from a given string?
For the purposes of this question and my examples, I'll refer to this hypothetical method as String.Parse()
For example, given an object with the following definition:
Public Class LastModified
    Public Property User As String = Nothing
    Public Property FromIP As String = Nothing
    Public Property InterfaceName As String = Nothing
    Public Property Method As String = Nothing
    Public Property ModifiedDate As DateTime = DateTime.MinValue
End Class

I was thinking of something like one of the following pseudocode alternatives:
' PSEUDOCODE - NOT OPERATIONAL - DO NOT USE
Dim LMBString As String = "admin 192.168.168.168:X0 UI 03/26/2022 15:43:38"
Dim LMB As New LastModified

' USING "BASIC" String.Format() SYNTAX
LMBString.Parse("{0} {1}:{2} {3} {4}",
                LMB.User,
                LMB.FromIP,
                LMB.InterfaceName,
                LMB.Method,
                LMB.ModifiedDate)

' USING STRING INTERPOLATION SYNTAX
LMBString.Parse($"{LMB.User} {LMB.FromIP}:{LMB.InterfaceName} {LMB.Method} {LMB.ModifiedDate}")

Perhaps this functionality is available through a 3rd-party library, and I suppose I could probably build a .Parse() extension method that could achieve this goal relatively easily, but I wanted to go ahead and see if someone else had already invented that particular wheel, and my Google-fu may simply be too weak. As stated above, I've not been able to find implementations of either of these pseudocode operations currently available natively in .NET (I'm using Framework 4.7 for my current project), but I don't mind looking stupid to ask a question that might have a simple solution - especially if it helps someone else who faces the same issues.

Just for reference purposes, in my current implementation, I'm using the following (simplified) code, which is totally functional and provides the results I'm looking for. I'm satisfied to keep using this "as-is", but I couldn't help wondering if there might be a way to achieve the same goal with fewer lines of code.
Public Function ParseStringToLastModifiedObject As LastModified
    Dim LMBString As String = "admin 192.168.168.168:X0 UI 03/26/2022 15:43:38"
    Dim LMBBuffer As String() = LMBString.Split(" "c)
    Dim LMBReturn As New LastModified

    With LMBReturn
        Dim IPBuffer As String() = LMBBuffer(1).Split(":"c)

        .User = LMBBuffer(0) '-> "admin"
        .Method = LMBBuffer(2) '-> "UI"
        .ModifiedDate = CDate(LMBBuffer(3) & " " & LMBBuffer(4)) '-> #3/26/2022 15:43:38#
        .FromIP = IPBuffer(0) '-> "192.168.168.168"
        .InterfaceName = IPBuffer(1) '-> "X0"
    End With

    Return LMBReturn
End Function


text:
Q: Recovering files from an iMac G3 hard drive (Mac OS 8.6) I recently purchased an iMac G3 (M2452) running Mac OS 8.6 from eBay for a project I'm working on, and was hoping to recover system sound files (such as startup sound, error sounds, etc) to use in the project. The machine booted fine, but once it was running I was unable to open the hard drive in Finder, which was likely related to TechTools Pro claiming there was an issue with the volume structure. Attempting to open it would freeze the machine. I didn't hear any disk activity, and let it sitting for at least an hour just to see if it would follow through, no results.
I kinda got ahead of myself and disassembled the machine to continue with my project, and now have the intact hard drive separated. Is there any way I can connect this to a modern computer, and if so, would I even be able to recover files? I can't find anything but the startup sound after a bit of digging around online, and I'd love to have the original files anyway for authenticity's sake.
Thanks in advance!

A: From what I can tell the drive from an iMac G3 is an IDE type. HDDs running Mac OS System 8.6 ought to be running on the HFS+ disk format.
If you get a USB HDD enclosure with internal IDE connectors you should be able to plug the drive into it, connect the enclosure to a modern Mac and see the disk contents.
If you don't have access to a modern Macintosh you should be able to read HFS+ formatted drives under windows with the software hfsexplorer.

A: If your G3 has a Firewire port you can connect that directly to a more modern Mac (FW400->800 or FW400->400) and run dd in Terminal to make a full 1:1 disk image of the drive's contents. Boot into Target Disk Mode on the G3 when doing this (Boot and hold down T).
Alternatively, I believe Finder can natively view the contents of the disk. Then you can just click and drag your stuff out.
If the drive is already completely taken out, you can toss it onto an IDE to USB adapter and plug that in. It would function the same way any external storage device would.


text:
Q: COMODO Antivirus Considers a Python File a Threat I am using COMODO antivirus on my ubuntu partition, and recently ran a scan.  It found a HIGH PRIORITY error which seems like nothing more than a file in numpy.
Has anyone else seen this before?
(1) What causes it?
(2) Is it safe to ignore?
Thanks,
Ryan

A: *

*Has anyone else seen this before?

1 hit on google for Exploit.JS.Pdfka. Nobody even bothered answering that bug report except for an update your virus database file.
Upload the file to virustotal for an online scan. Those are a lot better than off line virus scanners.

*

*What causes it?

Comodo is a stupid piece of software that relies on malware and anti-virus that appear on a Windows machine to behave the same on Linux? io.py is probably used in a malware and now it believes all io.py's are malware?

*

*Is it safe to ignore?

99.99999999% of all notices from anti-virus software are false positives.
If you want to use an anti-virus install a 2nd anti-virus and compare results. Only when both alarm about the same file I would investigate it.