text:
Q: Floating Action Button and CardView How to add Floating Action Button from the support library for CardView so that when you scroll through the ScrollView, the button has gone up along with the card?
My app
before scrolling

after scrolling

The button should go along with the card
I want to fix this
Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    >

    <ScrollView
        android:id="@+id/nested_scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white_vk_background_color">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/spacing_8"
            android:orientation="vertical"
            android:padding="@dimen/spacing_16">

            <android.support.v7.widget.CardView

                android:id="@+id/behavior_card_view"
                style="@style/RateCardView"

                app:cardBackgroundColor="@color/white"
                app:cardCornerRadius="@dimen/spacing_2"
                app:cardElevation="@dimen/spacing_8">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_margin="@dimen/spacing_16"
                    android:orientation="vertical"
                    >

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:paddingBottom="@dimen/spacing_8">

                        <TextView
                            android:id="@+id/description_rate_usd_text_view"
                            style="@style/AppTextView.RateTextView"
                            android:text="@string/description_currency_text_view_usd"/>

                        <TextView
                            android:id="@+id/rate_usd_text_view"
                            style="@style/AppTextView.RateTextView"
                            android:layout_centerHorizontal="true"
                            android:layout_toRightOf="@id/description_rate_usd_text_view"
                            tools:text="63.99"
                            />

                        <TextView
                            android:id="@+id/rate_difference_usd_text_view"
                            style="@style/AppTextView.DifferenceTextView"

                            android:layout_toRightOf="@id/rate_usd_text_view"
                            tools:text="+0.44"/>

                    </RelativeLayout>

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:paddingBottom="@dimen/spacing_8">

                        <TextView
                            android:id="@+id/description_rate_eur_text_view"
                            style="@style/AppTextView.RateTextView"
                            android:text="@string/description_currency_text_view_eur"/>

                        <TextView
                            android:id="@+id/rate_eur_text_view"
                            style="@style/AppTextView.RateTextView"
                            android:layout_centerHorizontal="true"
                            android:layout_toRightOf="@id/description_rate_eur_text_view"
                            tools:text="71.99"
                            />

                        <TextView
                            android:id="@+id/rate_difference_eur_text_view"
                            style="@style/AppTextView.DifferenceTextView"
                            android:layout_toRightOf="@id/rate_eur_text_view"
                            tools:text="+0.15"/>

                    </RelativeLayout>

                    <TextView

                        android:id="@+id/rate_update_time_text_view"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="bottom|start"
                        android:layout_marginBottom="@dimen/spacing_8"
                        android:layout_marginLeft="@dimen/spacing_16"
                        android:layout_marginTop="@dimen/spacing_16"
                        android:gravity="center"
                        android:textSize="@dimen/density_font_size_text_date"

                        tools:text="Date: 15.07.2016"

                        />

                </LinearLayout>
            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                android:id="@+id/converter_card_view"
                style="@style/RateCardView"
                app:cardBackgroundColor="@color/white"
                app:cardCornerRadius="@dimen/spacing_2"
                app:cardElevation="@dimen/spacing_8">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:padding="@dimen/spacing_16">

                    <com.rengwuxian.materialedittext.MaterialEditText

                        android:id="@+id/converter_ruble_edit_text"
                        style="@style/RateEditText"
                        android:hint="@string/description_currency_ruble"

                        app:met_baseColor="@android:color/black"
                        app:met_bottomTextSize="@dimen/density_font_size_text_converter"
                        app:met_errorColor="@color/red_light"
                        app:met_floatingLabel="normal"
                        app:met_floatingLabelAlwaysShown="true"
                        app:met_floatingLabelTextSize="@dimen/density_font_size_text_converter"
                        app:met_helperText=""
                        app:met_primaryColor="@color/red_light"
                        app:met_textColorHint="@android:color/transparent"/>

                    <com.rengwuxian.materialedittext.MaterialEditText

                        android:id="@+id/converter_dollar_edit_text"
                        style="@style/RateEditText"
                        android:hint="@string/description_currency_dollar"

                        app:met_baseColor="@android:color/black"
                        app:met_bottomTextSize="@dimen/density_font_size_text_converter"
                        app:met_errorColor="@color/red_light"
                        app:met_floatingLabel="normal"
                        app:met_floatingLabelAlwaysShown="true"
                        app:met_floatingLabelTextSize="@dimen/density_font_size_text_converter"
                        app:met_helperText=""
                        app:met_primaryColor="@color/red_light"
                        app:met_textColorHint="@android:color/transparent"/>

                    <com.rengwuxian.materialedittext.MaterialEditText

                        android:id="@+id/converter_euro_edit_text"
                        style="@style/RateEditText"
                        android:hint="@string/description_currency_euro"

                        app:met_baseColor="@android:color/black"
                        app:met_bottomTextSize="@dimen/density_font_size_text_converter"
                        app:met_errorColor="@color/red_light"
                        app:met_floatingLabel="normal"
                        app:met_floatingLabelAlwaysShown="true"
                        app:met_floatingLabelTextSize="@dimen/density_font_size_text_converter"
                        app:met_helperText=""

                        app:met_primaryColor="@color/red_light"

                        app:met_textColorHint="@android:color/transparent"/>
                </LinearLayout>
            </android.support.v7.widget.CardView>
        </LinearLayout>
    </ScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/update_floating_action_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/density_spacing_size_floating_action_button"
        android:layout_marginRight="@dimen/float_action_button_spacing_8"
        android:src="@drawable/ic_cached_white_24dp"
        app:fabSize="mini"
        app:layout_anchor="@id/behavior_card_view"
        app:pressedTranslationZ="6dp"
        app:layout_anchorGravity="end|right|center"
        />

</android.support.design.widget.CoordinatorLayout>

A: Instead of anchoring to behavior_card_view, try anchoring it to something inside behavior_card_view. Ideally, anchor to the bottom of the USD textview. This should prevent the FAB from sliding down.
I would actually create a invisible layout which I can use to anchor but it doesn't affect the UI otherwise.
I can't replicate the issue you are having but the following works as you want:
    <RelativeLayout
        android:id="@+id/rl1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="10dp"
        android:paddingRight="10dp">

        <TextView
            android:id="@+id/tv1"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:paddingLeft="12dp"
            android:text="Setting"
            android:focusable="true"
            android:focusableInTouchMode="true" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:src="@drawable/ic_add"
            app:fabSize="mini"
            app:pressedTranslationZ="6dp"
            app:layout_anchorGravity="end|right|center"
            app:layout_anchor="@id/tv1" />
... a lot of elements here ...
    </RelativeLayout>

This RelativeLayout is the only element inside my ScrollView element.


text:
Q: Is Firebase using cryptography? I am using firebase and email sign in method on my iOS app and also using database firebase, should I say "YES" on Export Compliance question about cryptography on iTunes Connect? if I should say yes what should I provide on the next step?

A: Here is a similar question - IOS App submission Export Compliance: Firebase. Based on the answers there it seems, that there is no need to answer "YES". But, as it was mentioned there - it is not a legal advice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Redraw HighChart After Dropdown Value is selected I have a drop down menu called info and I want to update my highchart everytime a user selects a value through the info menu.
Here is the code:
$('#info').on('change', function() {

  add_info(this.value);

});

The add_info() method simply gets data via ajax and this is how I am processing it after getting the response back:
if(chart=='stacked_chart'){

    console.log(JSON.stringify(response));

          var series = [{name:'Coached',data:[]},{name:'Non Coached',data:[],stack: 'yes'},{name:'Delta',data:[],stack: 'yes'}],
          year, month, day;

            for(var i=0; i<response.length;i++){

                var d = response[i].date.split(",");
                year = parseFloat(d[0]);
                month = parseFloat(d[1])-1; //date.utc method starts month 0-11
                day = parseFloat(d[2]);
                var coached = +(parseFloat(response[i].coached).toFixed(3));
                var non_coached = +(parseFloat (response[i].non_coached).toFixed(3));
                var delta = +(parseFloat (response[i].delta).toFixed(3));

                series[0].data.push([Date.UTC(year,month,day),coached]);
                series[1].data.push([Date.UTC(year,month,day),non_coached]);
                series[2].data.push([Date.UTC(year,month,day),delta]);
                console.log(Date.UTC(year,month,day));
            }

                  console.log(series);

          if(series.length){

           stacked_chart.userOptions.series = series;
            var chart = new Highcharts.Chart(stacked_chart.userOptions);
            console.log(chart.series[0].data[0].options);
            console.log(chart.series[1].data[0].options);
            console.log(chart.series[2].data[0].options);

          }
    }

I can see it brings back the new data but It doesn't redraw. I have looked at here but couldn't redraw the chart. Any ideas how to reset the chart every time a user selects a new value from the drop down?


text:
Q: Symfony2 validatePropertyValue for UniqueEntity Is there a way validate UniqueEntity on a single property value for symfony validator?
# Acme\Resources\config\validation.yml
Acme\DemoBundle\Entity\User:
    constraints:
        - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: { fields: username, message: This username is already taken}

    properties:
        username:
            - NotBlank: { message: You must provide a username}

When I run validation on the on the User Registration form it works perfectly, checking NotBlank then UniqueEntity and reporting violations.
But, I also run ajax validation on each field (as users type) using validator and validatePropertyValue as follows:
$violations = $this->validator->validatePropertyValue("Acme\DemoBundle\Entity\User", "username", $value);

var_dump($violations);

only the properties username contraint is ever checked. It never checks against the uniqueEntity constraint.


text:
Q: Kendo UI DataSourceRequest performance impact I'm using KendoUI grid and using its ToDataSourceResult to filter my data (as suggested by the documentation) but i'm worried about the performance impact.
Based on my understanding, the following suggested code get all records from database into memory and performm ToDataSourceResult extension method to filter the records in memory (LINQ fluent api concept). Will this have great performance impact if i have lots of records?
I suppose having a query to the database with the "where" clause upfront will have better performance... please advise.
Here's what suggested in the documentation
var countries = _database.Countries.GetAll();
return Json(countries.ToDataSourceResult(request, record => new
{
     record.Id,
     record.Name,
     record.Currency,
     record.TimeZone
}));

This is other option without using ToDataSource filter
var selectedCountries = _database.Countries.GetCountryStartWith("m")

A: It depends on what your GetAll method returns. If it returns IQueryable from a LINQ-enabled provider (Entity Framework, Linq to SQL or anything else) all operations will be performed at database level (not in memory). If it returns all records - well you have a problem even before using ToDataSourceResult.


text:
Q: Multiple similar entities or use the same one in core data? So I've got a Client entity that needs a relationship to a PhoneNumber entity to allow multiple phone numbers. And I've got an Employee entity that also needs a relationship to a PhoneNumber entity to allow multiple phone numbers. Should I create two separate PhoneNumber entities or can I somehow use the same entity for both?

A: I would create a parent entity called Person for your Client and Employee entities. The Person entity would have a relationship to the PhoneNumber entity.
Inherited entities have the same attributes and relationships as their parent entity. Of course you can add attributes and relationships to the "child"-entities as well. I omitted that in the screenshot.
Something like this:

you can configure the parent entity in the core data inspector in the right side pane.


text:
Q: Prove or disprove that there exists no $G$ structure with its bordism group $\Omega_1^{G} =\mathbb{Z}/N$ for $N>2$ It can be found that there are the following bordism group $\Omega_0^{G}$ at $d=0$ and 1 dimensions by requiring $G$ structure for $d$-manifolds:
$$
\Omega_0^{SO} = \mathbb{Z} , \quad \Omega_1^{SO} =  0.
$$
$$
\Omega_0^{Spin} = \mathbb{Z} , \quad \Omega_1^{Spin} =  \mathbb{Z}/2 .
$$
$$
\Omega_0^{O} = \mathbb{Z}/2 , \quad \Omega_1^{O} =  0.
$$
The group classification as the cobordism class is obtained by comparing any two sets of $d$-manifolds $M_1$ and $M_2$ and by seeking whether there are $d+1$-manifolds $\Sigma$ making $M_1$ and $M_2$ as $\Sigma$'s boundary. If yes, then $M_1$ and $M_2$ are in the same cobordism class or correspond to the same group element in the bordism group. All $M_1, M_2, \Sigma$ should have equipped with $G$ structure.
So generally we look at:
$$
\Omega_0^{G}  =  ?  , \quad \Omega_1^{G} =  ?.
$$

*

*The manifold generates $n \in \mathbb{Z}$ class for $d=0$ in $\Omega_0^{SO}=\Omega_0^{Spin} = \mathbb{Z}$ must be an integer $\mathbb{Z}$ number of $d=0$ points (as manifold generators). Is this true that we cannot regard the $n_1,n_2 \in \mathbb{Z}$ points as the boundary of 1d lines, if $n_1 \neq n_2$? But only if $n_1 = n_2=n$, we can use $n$ 1d lines to connect the two sets of $n$ points as boundaries of $n$ 1d lines?

*Since $\Omega_0^{O} = \mathbb{Z}/2$, this means two $d=0$ points can be cobordant to nothing via an unoriented $d=1$ line segment. I may conjecture that:

For any $G$ structure, its bordism group must be either $\Omega_0^{G} =\mathbb{Z}$ or $\Omega_0^{G} =\mathbb{Z}_2$. Namely, it cannot be $\Omega_0^{G} =\mathbb{Z}/N$ for $N\neq 2$ or
or $\Omega_0^{G} =0$  for any $G$.  Is this correct?

*I may conjecture that:

there exists no $G$ structure with its bordism group $\Omega_1^{G} =\mathbb{Z}$. Namely, we only have either
$\Omega_1^{G} =\mathbb{Z}/N$
or
$\Omega_1^{G} =0$ for any $G$. Is this correct?
(Is this true that we must have $\Omega_1^{G} =\mathbb{Z}/N$ with $N =1$ as 0 and $N =2$?)

If so:
This means that for some finite $N$, the $N$ sets of $1$-manifolds ($S^1$) must be regarded as some bundary of a $G$ structure $2$-manifold. Thus, the $N$ sets of $S^1$ must be cobordant to nothing via this $G$ structure $2$-manifold. Can we prove this? Is this true that $N\leq 2$?

A: $\newcommand{\Z}{\mathbb Z}$Part 2 is correct: for any $G$-structure, $\Omega_0^G$ is either isomorphic to $\Z$ or
$\Z/2$. Part 3 isn't correct, and I'll give a counterexample.
First, part 2: let $\rho\colon G\to O$ be a $G$-structure. $\Omega_0^G$ is isomorphic to $\pi_0(MG)$, where $MG$ is
the Thom spectrum of the pullback of the tautological bundle $V\to BO$ across $B\rho\colon BG\to BO$. Since $MG$ is
connective, the Hurewicz map $\pi_0(MG)\to \tilde H_0(MG)$ is an isomorphism. The Thom isomorphism implies
$\tilde H_0(MG)\cong H_0(BG; \Z_{\sigma})$, where $\Z_\sigma$ is the orientation local system for $B\rho^*V$.
For a general space $X$, the zeroth twisted homology with coefficients in a $\Z[\pi_1(X)]$-module $V$ is the
coinvariants $V/\{v - \gamma\cdot v\mid \gamma\in \pi_1(X)\}$ (See
Davis-Kirk, Proposition 5.14.) In our case, only two
things can happen.

*

*If $B\rho^*V$ is orientable, $\Z_\sigma$ is a trivial local system, and we obtain $H_0(BG;\Z_\sigma) \cong \Z/0 =
  \Z$.

*If $B\rho^*V$ is unorientable, $\Z_\sigma$ is a nontrivial local system. This means there is an element of
$\pi_1(BG)$ which sends $1\mapsto -1$, so we're quotienting by a subgroup containing $2\Z$. However, as
$\pi_1(BG)$ is a group, its action cannot send $1$ to $0$, so we're quotienting out by exactly $2\Z$, and we
obtain $H_0(BG;\Z_\sigma)\cong \Z/2$.

For part 3: for a $G'$-structure with $\Omega_1^{G'}\cong\Z$, consider $G' = \mathrm{SO}\times\Z$. This encodes the notion
of oriented manifolds with a principal $\Z$-bundle, or equivalently oriented manifolds with a map to $S^1$. The
Atiyah-Hirzebruch spectral sequence
$$E_2^{p,q} = H_p(S^1; \Omega_q^{\mathrm{SO}}) \Longrightarrow \Omega_{p+q}^{\mathrm{SO}}(S^1) = \Omega_{p+q}^{G'}$$ collapses in
degrees $3$ and below, producing an isomorphism $\Omega_1^{G'} \cong H_1(S^1)\cong\Z$. One can take as a generator
the $1$-manifold $S^1$ with principal $\Z$-bundle $\mathbb R\to \mathbb R/\Z\cong S^1$.


text:
Q: search filter changes result before i press enter Im having 2 problems with my search filter:

*

*When i write a search word in my search bar and change the filter
option shows me the result before i press enter. (It should not
function before i press enter)

*The second problem i have is when i have a search result and
changing the search word and press enter, i get no results.
Typescript
import { Component, OnInit } from '@angular/core';
import { RecipesService } from 'src/app/recipes.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  recipeslist: any;
  searchWord = '';
  type = '';
  intolerances = '';
  diet = '';

  constructor(private recipesService: RecipesService) {

  }

  loadRecipes() {
    this.recipesService.getSearch(this.searchWord, this.type, this.intolerances, this.diet).subscribe(recipes => {
      this.recipeslist = recipes.results;
      console.log(this.recipeslist);
    });
  }
  ngOnInit(): void {
  }

  handleSearch(event: any): void {
    this.searchWord = event.target.value;
    console.log(this.searchWord);
  }

  changeType(event: any): void {
    this.type = event.target.value;
    console.log(this.type);
  }

  IntolerancesType(event: any): void {
    this.intolerances = event.target.value;
    console.log(this.intolerances);
  }

  dietType(event: any): void {
    this.diet = event.target.value;
    console.log(this.diet);
  }

  search() {
    this.loadRecipes();
  }
}

html

      <input type="text" class="w-full bg-transparent px-4" ngModel placeholder="Search here ..." aria-label="serach" (input)="handleSearch($event)" id="search" type="text" (change)="search()" />
      <button class="bg-slate-300 py-3 px-6 text-sm" disabled="!form.valid" (click)="search()" type="button">Search</button>

          <select formControlName="typeControl" (change)="changeType($event)">
            <option value="">Mealtype</option>
            <option value="main course">Main course</option>
            <option value="dessert">Dessert</option>
            <option value="appetizer">Appetizer</option>
            <option value="salad">Salad</option>
            <option value="breakfast">Breakfast</option>
            <option value="soup">Soup</option>
          </select>

          <select formControlName="IntolerancesControl" (change)="IntolerancesType($event)">
            <option value="">Intolerances</option>
            <option value="dairy">Dairy</option>
            <option value="egg">Egg</option>
            <option value="gluten">Gluten</option>
            <option value="peanut">Peanut</option>
          </select>

          <select formControlName="dietControl" (change)="dietType($event)">
            <option value="">Diet</option>
            <option value="gluten Free">Gluten Free</option>
            <option value="ketogenic">Ketogenic</option>
            <option value="vegetarian">Vegetarian</option>
            <option value="lacto-vegetarian">Lacto-Veg</option>
          </select>

A: the event that you should do is not (change), you want ENTER pressed then and only then execute the filter, to do this you must implement (keyup.enter).

      <input type="text" class="w-full bg-transparent px-4" ngModel placeholder="Search here ..." aria-label="serach" (input)="handleSearch($event)" id="search" type="text" (keyup.enter)="search()" />


text:
Q: How to do something based on user input? I am trying to make a simple calculator, and I want the user to choose an operation at the start. I can run it fine, but it won't call the add method. Here is my code:
     operation = input("Choose an operation: ")

def Addition():
    print("Hello, world")

def ChooseOperation():
    if (operation == "Addition"):
        Addition()

A: You don't run the function ChooseOperation. Since you probably want to pass operation as an argument, the code should be:
def Addition():
    print("Hello, world")

def ChooseOperation(operation):
    if (operation == "Addition"):
        Addition()

operation = input("Choose an operation: ")
ChooseOperation(operation)


text:
Q: Flatpickr uses different native calendar in mobile browser and in webview (IOS) When I try to open my app that uses vue-flatpickr-component in a browser on my iphone I get a different native calendar than the one I get when I open the app in webview.
On android the calendars are the same in both cases.
What causes this? Can I somehow affect this? Is there some way I can debug this?

A: Reading the documentation of Flatpickr
You will find the option disableMobile.
disableMobile information:
Set disableMobile to true to always use the non-native picker.
By default, flatpickr utilizes native datetime widgets unless certain options (disable) are used.


text:
Q: Flutter: Get_it uses my abstract class instead of my implemented class Dependency injection initialization:
final sl = GetIt.instance;

init() {
  //! Features - Sign In
  //Bloc
  sl.registerFactory(() => SignInBloc(login: sl()));

  // Use cases
  sl.registerLazySingleton(() => Login(sl()));

  // Repository
  sl.registerLazySingleton<SignInRepository>(
    () => SignInRepositoryImpl(
      remoteDataSource: sl(),
      localDataSource: sl(),
      networkInfo: sl(),
    ),
  );

  // Data sources
  sl.registerLazySingleton<SignInRemoteDataSource>(
    () => SignInRemoteDataSourceImpl(client: sl()),
  );

  sl.registerLazySingleton<SignInLocalDataSource>(
    () => SignInLocalDataSourceImpl(),
  );

  //! Core
  sl.registerLazySingleton<NetworkInfo>(() => NetworkInfoImpl(sl()));
  sl.registerLazySingleton<DataConnectionChecker>(
      () => DataConnectionCheckerImpl());

  //! External
  sl.registerLazySingleton(() => http.Client());
}

Login class:
class Login extends UseCase<Either<Failure, Response>, SignIn> {
  final SignInRepository repository;

  Login(this.repository);

  @override
  Future<Either<Failure, Response>> call({required SignIn params}) async {
    return await repository.login(params);
  }
}

SignIn Repository:
class SignInRepositoryImpl implements SignInRepository<SignInModel> {
  final SignInRemoteDataSource remoteDataSource;
  final SignInLocalDataSource localDataSource;
  final NetworkInfo networkInfo;

  SignInRepositoryImpl({
    required this.remoteDataSource,
    required this.localDataSource,
    required this.networkInfo,
  });

  @override
  Future<Either<Failure, Response>> login(SignInModel signIn) async {
    if (await networkInfo.isConnected) {
      try {
        final remoteReponse = await remoteDataSource.login(signIn);
        return Right(remoteReponse);
      } on ServerException {
        return Left(ServerFailure());
      }
    } else {
      return Left(ErrorConnection());
    }
  }
}

error:

Reload already in progress, ignoring request Restarted application in
493ms. [VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: type
'SignIn' is not a subtype of type 'SignInModel' of 'signIn'
#0      Login.call package:app_mobile_chauffeur/…/usecases/login.dart:18
#1      new SignInBloc. package:app_mobile_chauffeur/…/bloc/sign_in_bloc.dart:35
#2      new SignInBloc. package:app_mobile_chauffeur/…/bloc/sign_in_bloc.dart:20
#3      Bloc.on..handleEvent package:bloc/src/bloc.dart:211
#4      Bloc.on..handleEvent package:bloc/src/bloc.dart:202
#5      Bloc.on. package:bloc/src/bloc.dart:220
#6      _MapStream._handleData (dart:async/stream_pipe.dart:213:31)
#7      _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
#8      _rootRunUnary (dart:async/zone.dart:1434:47)
#9      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
#10     _CustomZone.runUnar<…> Reloaded 1 of 784 libraries in 318ms. Reloaded 3 of 784 libraries in 318ms.


text:
Q: How to loop through map and fetch only first few key value pairs and pass them to another function? I have a map which is having key value pairs as below:
map =
    {
      "sha512-T9JWj==": [
        "mykey1597855209",
        "mykey159785520915978552101597855212"
      ],
      "sha512-lcddfd==": [
        "mykey15978552091597855210"
      ],
      "sha512-abcdfd==": [
        "otherkey15978552091597855210"
      ]
    }

I want to get the first key and pass it to another function func1.
Similarly I want to get all the values associated with that key and pass to a second function func2.
The map can have any number of key value pairs but I want to capture only first 10 key value pairs.
I am able to capture all keys and values using:
console.log(Object.keys(map));
console.log(Object.values(map));

How can I loop through the map and get the first key and pass it to func1 and pass its values to func2?  I need to capture only first 10 keys and corresponding values.
1) Get only 10 keys and values from the the map object
2) Loop through first key value pair
3) Pass key to `func1`
4) Pass all values associated with the key to `func2`
5) Repeat `4` and `5` until all `10` keys are read

Ordering is not important

A: By definition, a map doesn't actually have any ordering. You can retrieve all the entries from the map and pick the first 10 that are returned, but there is no guaranteed order to how the entries will be returned.
const entries = Object.entries(map).slice(0,10);
for (const [key, values] of entries) {
    func1(key);
    for (const value of values) {
        func2(value);
    }
}

Or, in more functional style
Object.entries(map).slice(0,10).forEach(([key, values]) => {
    func1(key);
    values.forEach(value => func2(value));
});

A: In ES6, you can use Reflect.ownkeys()
then it is simple to slice it to your prefer length and loop over it.

map = {
      "sha512-T9JWj==": [
        "mykey1597855209",
        "mykey159785520915978552101597855212"
      ],
      "sha512-lcddfd==": [
        "mykey15978552091597855210"
      ],
      "sha512-abcdfd==": [
        "otherkey15978552091597855210"
      ]
    }

Reflect.ownKeys(map).slice(0, 10).forEach((k)=>{
  console.log(k); // your func1
  console.dir(map[k]) // your func2
})


text:
Q: default apps win10 don't show all options I have installed notepad++ and within that set up the file associations. However in Win10 Apps/Features, I am not shown notepad++ as an option for any of the file types such as .txt, only notepad or wordpad or select from the app store.
Do I need a registry hack or what please?

A: There are a few ways to resolve the issue:

*

*Run Notepad++ as Administrator and try setting the filetype associations again. This is also necessary for 7-Zip and other applications that replace MS default apps. If this does not work:

*Right-click a .txt file and select Open with.

*

*Select Choose another app.

*

*If the desired application does not show, select More apps.

*Check Always use this app to open .txt files.
OR

*

*Press the Windows key and type "Def".

*Select Default Apps dialog.

*

*Select Choose Default apps by file type.

*Scroll down to .txt and select your application.

Having said all this, AFTER EACH WINDOWS UPDATE THAT INSTALLS OR UPDATES UWP (newspeak for "Metro") APPS, the default choices are compromised. Then you may see a dialog asking if you still wish to use Notepad++ or prefer the newest greatest app mirabile from MS.


text:
Q: How do I use PyMock and Nose with Django models? I'm trying to do TDD with PyMock, but I keep getting error when I use Nose and execute core.py from command line:
"ERROR: Failure: ImportError (Settings cannot be imported, because environment variable DJA
NGO_SETTINGS_MODULE is undefined.)"
If I remove "from cms.models import Entry" from the unit test module I created, everything works fine, but I need to mock functionality in django module cms.models.Entry that I created.
What am I doing wrong? Can this be done?

A: You do need DJANGO_SETTINGS_MODULE defined in order to run core.py -- why don't you just export DJANGO_SETTINGS_MODULE=whatever in your bash session before starting nose?


text:
Q: Mapping a number to an N dimensional grid/array Lets assume, for example, that I have a 3-dimensional grid/array where the axis run from 1 to 1000 (or 0 to 999 equivalently). This array has 1000^3 elements.
I would like to map a single integer in the range 0 to 1000^3 to this array in a deterministic way using Java. Preferably this solution would work for any dimension N.
Here is a pseudo-codish example of such a function:
public Vector<int> nthElement( Vector<int> dims, int n )

So if I would call it like nthElement([1000, 1000, 1000], 0) it would return [0, 0, 0] whereas nthElement([1000, 1000, 1000], 1001) would return something like [999, 1, 0].
The solution should be for N dimensions and not for 3 as in my example.

A: This is the correct mapping algorithm:
map([X, Y, Z, T, ...], N) = [
    N mod X,
    N div X mod Y,
    N div X div Y mod Z,
    N div X div Y div Z (mod ...)?
    ...
]

or recursive
map([X, Y, Z, T, ...], N) = [N mod X, map([Y, Z, T, ...], N div X)]

Where A div B is Floor(A/B).

A: You can do:
a = Number % (1000 * 1000)
b = (Number / 1000) % 1000
c = Number / (1000 * 1000)

It's a mapping (unique), and you can simply do reverse
note 2/3 = 0 not .6666

A: check this
List<Integer> nthElement( List<Integer> dims, int n ){
    List<Integer> res = new ArrayList<Integer>(dims.size());
    for(Integer cur  : dims){
        if(n <= 0 ){
            res.add(0);
        } else {
            n -= cur;
            res.add(n >= 0 ? cur -1  : cur + n );
        }
    }
    return res;
}

upd
examples of usage
    //create list with 3 dimensions using Guava
    List<Integer> dims = ImmutableList.of(1000, 1000, 1000);
    //or with standard JDK
    //List<Integer> dims = new ArrayList<Integer>(3);dims.add(1000);dims.add(1000);dims.add(1000);

    System.out.println(nthElement(dims, 0));
    System.out.println(nthElement(dims, 1000));
    System.out.println(nthElement(dims, 1001));
    System.out.println(nthElement(dims, 2001));

will print
    [0, 0, 0]
    [999, 0, 0]
    [999, 1, 0]
    [999, 999, 1]

A: What you are probably looking for is the Cantor pairing function. It is defined for NxN, so you can use it for arbitrarily large dimensions. As mentioned on the wikipedia page it can be inductively generalized to an array of dimension n, in your case n=3 works just fine.
The above page also explains inverting the function, so you can get your coordinates in the array from the given number, which is exactly what you want with nthElement.
Of course, Cantor has only defined one possible way to walk through a two-dimensional field. There are other possible walks, but this one is the most popular way to do it.
Edit: I should mention, that if your array has rectangular dimensions the Cantor pairing function would assume dimensions of the largest kind. So the associated numbers are no longer successively within your array. F.ex. an array of size 1000x2 would be treated as a 1000x1000 array and the numbers corresponding to entries in your actual array would only be a non-successive list of the numbers 0..1000*1000.
If, however, your three dimensions are always the same, then this point can be totally ignored.
In response to the comment: Row-by-row and Cantor pairing are just different ways to walk through your matrix space. An advantage of Cantor pairing is that it is defined over the natural numbers and hence also is applicable if you do not have exact values for your matrix dimensions, or your matrix grows over time.


text:
Q: How do I add an underline to all section headings in {section in head/foot}? I am using beamer, and I can change the size of the font by using
\setbeamerfont{section in head/foot}{size=\scriptsize}

However, I do not know the correct way to make this text also underlined. I have attempted to add a style to the template using
\setbeamertemplate{section in head/foot}{style=underline},

but this just prints "style=underline" instead of all the section headings.
How do I make all of the individual titles underlined?
EDIT: Here is an example:
\documentclass[10pt]{beamer}

\setbeamertemplate{headline}{%
\leavevmode%
  \hbox{%
    \begin{beamercolorbox}[wd=\paperwidth,ht=2.5ex,dp=1.125ex]{palette quaternary}%
    \insertsectionnavigationhorizontal{\paperwidth}{}{\hskip0pt plus1filll}
    \end{beamercolorbox}%
  }
}

\setbeamerfont{section in head/foot}{size=\scriptsize}

\begin{document}

\begin{frame}
\titlepage
\end{frame}

\section{Headline Title 1}
\begin{frame}{Local Title 1}
\end{frame}
 \section{Headline Title 2}
\begin{frame}{Local Title 2}
\end{frame}

\end{document}

A: The section header that is inserted is constructed as the sections/frames are set. So one would have to intervene during the setting of the header. Knowing that \insertsectionhead prints \hyperlink{<target>}{<title>}, you can redefine \hyperlink to insert \hyperlink{<target>}{\underline{<title>}}:

\documentclass{beamer}

\setbeamertemplate{headline}{%
  \leavevmode
  \begin{beamercolorbox}[wd=\paperwidth,ht=2.5ex,dp=1.125ex]{palette quaternary}%
    \let\oldhyperlink\hyperlink% Store old \hyperlink
    %  Update \hyperlink to insert \underline around second ##2 argument
    \renewcommand{\hyperlink}[2]{\oldhyperlink{##1}{\underline{##2}}}%
    \insertsectionnavigationhorizontal{\paperwidth}{}{\hskip0pt plus1filll}
  \end{beamercolorbox}%
}

\setbeamerfont{section in head/foot}{size=\scriptsize}

\begin{document}

\begin{frame}
\titlepage
\end{frame}

\section{Headline Title 1}
\begin{frame}{Local Title 1}
\end{frame}
 \section{Headline Title 2}
\begin{frame}{Local Title 2}
\end{frame}

\end{document}

You may want to use
\renewcommand{\hyperlink}[2]{\oldhyperlink{##1}{\underline{\smash{##2}}}}%

instead, as header titles with descenders might cause vertical nonalignment of the \underline.


text:
Q: how to save data in HDFS with spark? I want to using Spark Streaming to retrieve data from Kafka. Now, I want to save my data in a remote HDFS. I know that I have to use the function saveAsText. However, I don't know precisely how to specify the path.
Is that correct if I write this:
myDStream.foreachRDD(frm->{
    frm.saveAsTextFile("hdfs://ip_addr:9000//home/hadoop/datanode/myNewFolder");
});

where ip_addr is the ip address of my hdfs remote server.
    /home/hadoop/datanode/ is the DataNode HDFS directory created when I installed hadoop (I don't know if I have to specify this directory). And,
    myNewFolder is the folder where I want to save my data.
Thanks in advance.
Yassir

A: The path has to be a directory in HDFS.
For example, if you want to save the files inside a folder named myNewFolder under the root / path in HDFS.
The path to use would be hdfs://namenode_ip:port/myNewFolder/
On execution of the spark job this directory myNewFolder will be created.
The datanode data directory which is given for the dfs.datanode.data.dir in hdfs-site.xml  is used to store the blocks of the files you store in HDFS, should not be referenced as HDFS directory path.


text:
Q: using sessions: am I abusing it? Let's say I have a site where a reporting page will contain user-specific daily reports.
By default, the user lands on today's report but then if he clicks on a calendar control and selects a new date, a new report will load for that day. What I want to do is use sessions as a cache for reports. The first time he loads a report for a day, it's loaded from the database into the session and then from the session to the page. Each time he loads a new report for a date, the logic first checks to see if this particular report is in the session and only if it's not is it loaded from the DB. A report has about 15 columns and is made up of about 300-500 rows per day. What will be stored in the session is a dictionary of lists of objects, with the date as the key and the list as the value. I'm using InProc session. I'm also considering storing several other dictionaries as well for other lists of objects.
Is this an efficient way to make the most of the .net framework? If it doesn't actually improve performance over making calls to the data source, will it make it slower? I'm looking to build something that'll scale to about 500-1000 simultaneous users or so.
Thanks.

A: It sounds like your pre-optimizing to me.  Have you run any performance tests to verify that you get any benefit at all to putting it in Session (or Cache)?
Have your users expressed concern over the performance?
For me, I wouldn't consider optimizing to any kind of cache until I knew I had a performance issue, and then I would look at why I had the performance problem, and optimize that

A: There are striking differences between cache and session state:

*

*Cache is server-based but session is user-based (can be across multiple servers)

*Cache is usually URL-based so if the URL is the same for all users, this cannot be implemented via cache.

*Cache will be recycled and memory reclaimed when server is close to out of memory (so you will not get an OutOfMemory exception using cache) but session just grows and you will get an OutOfMemory if you are using in-process sessions and not.

*Session is usually used for user level state that has to be stored but cache is meant for performance boosting.

With all above, and considering your requirement, you had better use cache unless the URL is the same for all users. If you are using session state, you need to be very careful as just a little performance nicety can kill your website.


text:
Q: How do I keep track of different scripts with the same version number in change history table from snowflake schema change? I am following the demo template for Snowflake schema change. I already have one script recorded in my change_history table:
Current script recorded in change history table, which has a version of 1.1.1
In Github, I set up a separate environment file to have a path to a different, unrelated script which also has a version of 1.1.1, I want this script to be recorded in the change_history table as well:
Different script which also has a version of 1.1.1
When I run my action script, it finishes with success but the different script is not recorded in the change_history table. It keeps only the first script. From what I can tell it will not update unless I give my new script a different number. But in essence this is a completely separate script from the first one. How can I keep records of both scripts as V1.1.1 in the change_history table via schemachange?
Finished with success, but change_history table does not add the new script.


text:
Q: RegEx to extract array of strings in javascript using match() I'm trying to use string.match() to extract column names from an SQL query.
Here is a sample string:
CREATE TABLE "listings" (
        "listing_id"    INTEGER UNIQUE,
        "state" TEXT,
        "title" TEXT,
        "description"   TEXT,
        "price" TEXT,
        "currency_code" TEXT,
        "url"   TEXT,
        PRIMARY KEY("listing_id")

Expected results:
['listing_id', 'state', 'title', 'description', 'price', 'currency_code', 'url']

what I've tried:
/(?<!\()(\").+?(\")(?!\ \()/g
Is there a way to get column names without double quotes?

A: This regex will match " when its it not followed or preceded by ) or (
regex101 demo
(?<![\)\(])"(?![\)\(])

then you can substitute it with nothing' so they will be removed

A: You were close. Use the regex, /(?<!\()(?:\")(.+?)(?:\")(?!\s*\()/gm for your requirement.
Check this for the demo and the explanation of the regex.
Demo using Java:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // Test string
        String str="CREATE TABLE \"listings\" (\n" +
                "        \"listing_id\"    INTEGER UNIQUE,\n" +
                "        \"state\" TEXT,\n" +
                "        \"title\" TEXT,\n" +
                "        \"description\"   TEXT,\n" +
                "        \"price\" TEXT,\n" +
                "        \"currency_code\" TEXT,\n" +
                "        \"url\"   TEXT,\n" +
                "        PRIMARY KEY(\"listing_id\")";

        Pattern pattern = Pattern.compile("(?<!\\()(?:\\\")(.+?)(?:\\\")(?!\\s*\\()");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

Output:
listing_id
state
title
description
price
currency_code
url


text:
Q: How to recreate activity I have activity and fragment. I get shared pref. in my fragment:
   private var dManager: DataManager?=null
   private lateinit var sp: SharedPreferences
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View?{
    val view = inflater.inflate(R.layout.fragment_test1_new_design, container, false)
    level = arguments!![Constants.LEVEL].toString()
    sp = activity!!.getSharedPreferences(Constants.APP_PREFERENCES, AppCompatActivity.MODE_PRIVATE)
    dManager = MyApp.gManager.getDataManager(sp,level,test)

And some times I get crash report that
lateinit property sp has not been initialized

I do not use sp before initialization, so it means activity!!.getSharedPreferences(Constants.APP_PREFERENCES, AppCompatActivity.MODE_PRIVATE) returns null.   Is it means that activity has been destroyed?
If I check that sp == null, what should I do futher in fragment? Restart app or recreate activity? What is the right way?

A: One way to solve this would be calling:
if(!::sp.isInitialized) {
    sp = activity!!.getSharedPreferences(Constants.APP_PREFERENCES, AppCompatActivity.MODE_PRIVATE)
    dManager = MyApp.gManager.getDataManager(sp,level,test)
}

In the fragment onStart() method.


text:
Q: gojs+ customising picture based on some data condition I have a go.picture , but design can be changes based on same attribute value , so how can I customize based on data.
say for example
$(go.Picture, {
  width: 20,
  height: 20,
  source: '../img/cat.svg',
  imageAlignment: go.Spot.Top,
  alignment: go.Spot.Right,
}),

here I have a set of nodes data in nodeDataArray, and if the name is cat , then the cource should be
source: '../img/cat.svg',
and if the name property in nodes array is dog , source should dynamically changes to source: '../img/dog.svg',
Imagine this is my data
   const data = {
      nodeDataArray: [
        { key: 0, name: "Cat", color: "lightblue", loc: "0 0" },
        { key: 1, name: "Dog", color: "orange", loc: "150 0" },

      ],
      linkDataArray: [
        { key: -1, from: 0, to: 1 },
        { key: -2, from: 0, to: 2 },

      ],
      skipsDiagramUpdate: false
    };

Any help is highly helpful

A: Use a data-binding bound to the data.name property:
$(go.Picture,
  {
    width: 20,
    height: 20,
    source: '../img/default.svg', // This image will display if data.name does not exist
    imageAlignment: go.Spot.Top,
    alignment: go.Spot.Right,
  },
  // Note carefully that this binding ONLY runs if data.name is specified
  new go.Binding("source", "name", function(name){
    if (name === "Dog") return '../img/dog.svg';
    else if (name === "Cat") return '../img/cat.svg';
    else return '../img/unknown.svg';
  })
  )

Don't use an empty-string data binding unless you have to, since they have to evaluate on every data change, they are slower.

A:           go.Picture,
          {
            width: 30,
            height: 30,
            margin: new go.Margin(2, 5, 2, 22),
          },
          new go.Binding('source', '', (sourceData, target, name) => {
            if (sourceData.name.includes('cat') > -1) {
              return '../assets/img/cat.svg';
            } else return '../assets/img/dog.svg';
          })
            ),```


text:
Q: PS4 controller only working wired in games on WIN10 I've been using my PS4 controller wired on Windows 10, but it's not too comfortable.
I tried on several occasions to get it running wireless but to no avail. I have successfully connected it to my PC using a Bluetooth adapter, and it shows as connected and it is lit up, but it doesn't work in-game. Only works wired.
I have tried using DS4Windows (the new one that's maintained), but the problem with that is that it makes it be recognized as an Xbox360 controller, changing all the prompts in-game to Xbox controls.
Is there a way to get it to work in games wirelessly with or without DS4Windows while also keeping it visible to the game as a PS4 controller?.. The 'DInput only' option in DS4Windows only works wired.

A: I had this issue before, so I used Xpadder*.
It is a great software for programming input on your controller so that games on the PC recognise the DS4 input. It will allow you to use your PS4 controller on PC if you're playing steam or using emulators.
* I have no affiliation with the software or the team surrounding it.

A: You should try downloading Steam and running the game through it. You will have to add the game to Steam library and configure your PS4 controller into steam controller settings.
Here is how to add the game to steam library.
https://support.steampowered.com/kb_article.php?ref=2219-YDJV-5557


text:
Q: Obsolete proguard file; use -keepclasseswithmembers instead of -keepclasseswithmembernames I am having the following error on proguard.cfg file in my android project. I dont know what this error says. Any idea?

A: This is a bug with the SDK tools v11.
http://code.google.com/p/android/issues/detail?id=16384
When Lint generates error,

*

*go to lint warnings view (Window > Show View > Other > android > Lint Warnings) and double     click the error to modify proguard.cfg

*rename "keepclasseswithmembernames" to "keepclasseswithmembers" on line it shows error and save.

*run Lint again (click refresh in Lint Warnings view)

*repeat renaming if it shows further warnings in subsequent lines.
I changed mine to look like this.
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class com.android.vending.licensing.ILicensingService

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

A: Try with
Clean and build your project then select the error marker in the Problems view and
press Delete.
see the following link
http://groups.google.com/group/android-developers/browse_thread/thread/7606320e664fec9b


text:
Q: Floating video player using Youtube Android Player API I want to create a video player which plays Youtube video. I used YouTubePlayerView. It play the Youtube video. but i want the floating video player same as Youtube has.

A: Try to make use of the DraggablePanel library in Github. Draggable Panel is an Android library created to build a draggable user interface similar to the new YouTube draggable video component based on Fragments or Views. Check this SO thread for additional insight.


text:
Q: How to save AsyncTask class object in onSaveInstanceState() is this possible to save AsyncTask class object on rotation and reuse it again.
  public class MyTask extends AsyncTask<Void, Void, Integer>
    {

    }

any good solution.
Thanks

A:
is this possible to save AsyncTask class object on rotation and reuse it again.

Use onRetainNonConfigurationInstance() or a retained fragment.

thanks for reply but onRetainNonConfigurationInstance() deprecated after 3.0

That is because they recommend that you use a retained fragment instead. If you are not using fragments, use onRetainNonConfigurationInstance().


text:
Q: Two recursive functions and stackoverflow errors in javascript/nodeJs. Understanding the differences Looking into the SICP book and  JS functional programming I created two recursive functions. My expectation was that both of them raised a stack overflow error.
But it is only the sumAll() function that raised the error. See below the code for both functions sumAll() and factorial():
As expected the sumAll() function did raise a stack overflow error

function sumAll(n, i = 0, result = 0) {
  return (i > n)
    ? result
    : sumAll(n, i + 1, i + result);
}

console.log(sumAll(10000));

The factorial() function below did not raise a stack overflow error:

function factorial(n){
  return (n == 1)
    ? 1
    :  n* factorial((n-1))
}

console.log(factorial(10000))

My question is why the factorial() function does not raise a stack overflow and works perfectly in nodeJS meanwhile the sumAll() did raise it also in nodeJS

A: The number of local variables (i.e memory of local variables) is also considered in the call stack size.

function computeMaxCallStackFrames(a, b, c, d) {
  try {
    return 1 + computeMaxCallStackFrames(a + 1, b + 1, c + 2, d + 3);
  } catch (e) {
    // Call stack overflow
    // console.log(e);
    return 1;
  }
}
var stackFrames = computeMaxCallStackFrames(1, 4, 6, 2);
console.log(stackFrames);

try increasing the no. of parameters, you'll see the decrease in number of recursion calls / call stack frames.

function computeMaxCallStackFrames(a, b, c, d, e) {
  try {
    return 1 + computeMaxCallStackFrames(a + 1, b + 1, c + 2, d + 3, e-2);
  } catch (e) {
    // Call stack overflow
    // console.log(e);
    return 1;
  }
}
var stackFrames = computeMaxCallStackFrames(1, 4, 6, 2, 9);
console.log(stackFrames);

with zero local variables.

function computeMaxCallStackFrames() {
  try {
    return 1 + computeMaxCallStackFrames();
  } catch (e) {
    // Call stack overflow
    // console.log(e);
    return 1;
  }
}
var stackFrames = computeMaxCallStackFrames();
console.log(stackFrames);

So, we can clearly see that the number of local variables (i.e memory of local variables) is also considered in the call stack size. If there are many local variables then the no. of recursive calls will be less.
Edit: And we all know the stack size will vary from browser to browser. So the output will not be same in different browsers, but it should be consistent in the same browser even if we run it multiple times.
Hope it all makes sense now.

A:
I gave the below answer in error, I got mixed up about which function was throwing the exception. Please ignore.

Your first function is capable of taking advantage of tail-call optimization, while your second function is not (or it is, but perhaps not in a way that's implemented in the node.js language).
Consider this: your first function's usual condition is that it ends in return sumAll(n, i + 1, i + result), which means that once you get something to return, you can just return that.
Your second function however ends in return n* factorial((n-1)), which means that once you get something to return, you have to do ANOTHER operation on it (multiply it by n) before you can actually return the result.
I believe the node.js interpreter isn't able to tail-call-optimize the second function because it requires another operation to be performed on it before the return.
Please note: I am not certain this is the answer, and I suspect node.js may not support tail call optimizations of any sort. This is my theory though about why one function might error in that way and the other one wouldn't.


text:
Q: Printing 1-N with N threads. The threads should print it iteratively M times I was having a hard time trying to figure out an algorithm to print the following pattern in go using N goroutines,
1, 2 ..... N
2, 4 .....2N
3, 6 ..... 3N
M*1, M*2 ..... M*N

Please help me out.

A: You are actually trying to build a linked list of go routines here, passing message from one go routine to another for printing their own dedicated number.
The following code does this (https://play.golang.org/p/Bx6dDne4GFs)

import (
    "fmt"
)

var curLevel int = 1
var M int = 1
var N int = 0

var yield chan bool

func main() {
    N = 5

    yield = make(chan bool)

    firstCh := make(chan bool)
    nextCh := firstCh
    for i := N; i > 1; i-- {
        chSelf := make(chan bool)
        go passOver(i, chSelf, nextCh)
        nextCh = chSelf
    }

    go passOver(1, firstCh, nextCh)

    firstCh <- true

    <-yield
}

func passOver(nodeId int, selfCh chan bool, nextCh chan bool) {
    for {
        if curLevel > M {
            close(yield)
        }
        select {
            case <- yield: return
            case <- selfCh:
                fmt.Printf("%d", nodeId * curLevel)
                if curLevel <= M {
                    if nodeId == N {
                        fmt.Printf("\n")
                    } else {
                        fmt.Printf(", ")
                    }
                }
                if nodeId == N {
                    curLevel = curLevel + 1
                }
                nextCh <- true
        }
    }
}

I have used here to close all the goroutines safely.
Thing to note here would be that when we close a channel, all listeners on that channel get notified about this.
Other than that it's just a simple circular single linked list.
To understand more of these idioms, I would recommend you to go through the following video. It's an hour of video but it's worth it.
https://www.youtube.com/watch?v=f6kdp27TYZs


text:
Q: word wrapping in HTMLPanel I have a HTMLPanel element created like this:
String message = "Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"
HTMLPanel messageDiv = new HTMLPanel(SafeHtmlUtils.fromString(message));

and this panel has a max-width: 50px; (for example). How can I make the word split into multiple lines so it doesn't overflow?

A: try using word-break: break-all; or word-break: break-word;


text:
Q: MTU 1500: fragment packets after 1472 bytes I have couple of VMs running on Openstack. I have one data network gateway assigned into the switch with MTU=1500, where VMs has to running.
Also in Openstack, I have set the default MTU=1500 of the network.
I am trying to ping from the VM to gateway (OR any ip on same network) of the switch with 1500 packetsize, it's de-fragmenting the packet.
localhost:~# ping -M do -s 1500 10.4.14.18
PING 10.4.14.18 (10.4.14.18) 1500(1528) bytes of data.
From 10.4.14.17 icmp_seq=1 Frag needed and DF set (mtu = 1500)
From 10.4.14.17 icmp_seq=1 Frag needed and DF set (mtu = 1500)
From 10.4.14.17 icmp_seq=1 Frag needed and DF set (mtu = 1500)
From 10.4.14.17 icmp_seq=1 Frag needed and DF set (mtu = 1500)
From 10.4.14.17 icmp_seq=1 Frag needed and DF set (mtu = 1500)
From 10.4.14.17 icmp_seq=1 Frag needed and DF set (mtu = 1500)
From 10.4.14.17 icmp_seq=1 Frag needed and DF set (mtu = 1500)
From 10.4.14.17 icmp_seq=1 Frag needed and DF set (mtu = 1500

Instead, If I am sending packets with smaller mtu (1472) it works,
localhost:~# ping -M do -s 1472 10.4.14.18
PING 10.4.14.18 (10.4.14.18) 1472(1500) bytes of data.
1480 bytes from 10.4.14.18: icmp_seq=1 ttl=64 time=0.965 ms
1480 bytes from 10.4.14.18: icmp_seq=2 ttl=64 time=0.515 ms
^C
--- 10.4.14.18 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1875ms
rtt min/avg/max/mdev = 0.515/0.740/0.965/0.225 ms

I can see 28 bytes of difference, i don't understand, where this 28 bytes are being utilised ?

A: The 1500 byte MTU holds for standard Ethernet at the network layer. In other words: 1500 byte can be transmitted in Ethernet frames without being fragmented. However, further protocols on top of Ethernet of course cut into the maximum payload.
In your case (the case of ping) the additional protocols are IP and ICMP. They both have headers with lengths 20 byte and 8 byte, respectively.
This means that you can transmit at most
1500 bytes (Ethernet mtu) - 20 byte (IP header) - 8 byte (ICMP header)
= 1472 byte

See also this question regarding MTU for UDP.

A: Ping will add 28 bytes header and then send it.
So if you want to send -s 1500, the actual size is 1500 + 28 = 1528 bytes.


text:
Q: Capistrano 3: way to handle different deploy flows I am new to Capistrano, but I have succeded on getting it working for a custom deploy. I have to deploy Moodle to a cluster with an auto-scaling group in AWS and one or more static servers.
It works great! I have managed to alter the flow with custom tasks to put my site on maintenance and clear cache without problems:
namespace :moodle do

  desc 'Save config.php from current release directory'   task :'save-config'
    on roles(:web) do
      execute :sudo, :cp, shared_path.join('config.php'), release_path
      execute :sudo, :chown, 'www-data-aulatp:www-data', release_path.join('config.php')
    end
  end

  desc 'Copy config.php to release directory'   task :'restore-config' do
    on roles(:web) do
      execute :sudo, :cp, shared_path.join('config.php'), release_path
      execute :sudo, :chown, 'www-data-aulatp:www-data', release_path.join('config.php')
    end
  end

  desc 'Enable maintenance mode on Moodle site'   task :'enable-maintenance' do
    on roles(:admin) do
      execute :sudo, '-u', 'www-data-aulatp', '/usr/bin/php7.0', current_path.join('admin', 'cli', 'maintenance.php'), '--enable'
    end
  end

  desc 'Disable maintenance mode on Moodle site'   task :'disable-maintenance' do
    on roles(:admin) do
      execute :sudo, '-u', 'www-data-aulatp', '/usr/bin/php7.0', current_path.join('admin', 'cli', 'maintenance.php'), '--disable'
    end
  end

  desc 'Purge all internal Moodle caches'   task :'purge-caches' do
    on roles(:admin) do
      execute :sudo, '-u', 'www-data-aulatp', '/usr/bin/php7.0', current_path.join('admin', 'cli', 'purge_caches.php')
    end
  end
end

before   'deploy:starting',    'moodle:save-config'
before   'deploy:updated',     'moodle:enable-maintenance'
after    'deploy:updated',     'moodle:restore-config'
after    'deploy:finished',    'moodle:enable-maintenance'
after    'deploy:finished',    'moodle:disable-maintenance'
after    'deploy:finished',    'moodle:purge-caches'

The problem is, sometimes I will need to make quick deploys, a small patch that does not need enabling and disabling maintenance mode or purging caches.
Would it be posible with capistrano?
As a posible alternative, I have been looking also to capistrano-patch, a way to deploy a simple patch to every server without creating a full deploy process. It looks like it has not ben updated for some years and I suppose it will not work with capistrano 3. Any similar ideas to do HOTFIX with Capistrano 3?

A: You could use environment variables to state that something needs to be bypassed. E.g., you could run your deploy with NO_CACHE_PURGE=true cap production deploy and then wrap the relevant code with something like:
desc 'Purge all internal Moodle caches'
task :'purge-caches' do
  if ENV['NO_CACHE_PURGE'].nil?
    on roles(:admin) do
      execute :sudo, '-u', 'www-data-aulatp', '/usr/bin/php7.0', current_path.join('admin', 'cli', 'purge_caches.php')
    end
  else
    puts 'Skipping purge-caches due to env variable'
  end
end

If you know Ruby well, and you want to automate this, you could probably write a method which would simplify some of this (the following code is untested):
def disableable_task(*args)
  if ENV[args[:env_name]].nil?
    task(args)
  else
    puts "Skipping #{args[0]} due to #{args[:env_name]} environment variable being set"
end

desc 'Purge all internal Moodle caches'
disableable_task :'purge-caches', env_name: 'NO_CACHE_PURGE' do
  on roles(:admin) do
    execute :sudo, '-u', 'www-data-aulatp', '/usr/bin/php7.0', current_path.join('admin', 'cli', 'purge_caches.php')
  end
end


text:
Q: Approximating the 5 numbers making up an average. I'm looking at emails handled in the workplace and overall have worked out an average handling time of 387 seconds. There are 5 different types of emails that go into this average and there volumes are below;
Email 1 - 12,081
Email 2 - 7,453
Email 3 - 4,475
Email 4 - 2,808
Email 5 - 2,674
Now, assuming each type of email takes the same time to handle is there a way I can work backwards through this and calculate an average handling time for each type?
I know it would be a case of best fit and any help anyone could give me would be great.
Cheers in advance
Ben


text:
Q: How to handle form data by calling a PHP function in jQuery Mobile using Ajax? I am currently working no a 6-page form using jQuery Mobile and are having some problems handling my form results. What I want to do is get all data sent to a .php script so the .php script can print and/or save to my database.
I've often had problems with everchanging variable names as they seem like a pain to manipulate. Perhaps someone know a better way to do this as I am pretty new to jQuery and Ajax. I have attempted to explain how my thought process is underneath.
Has anyone done anything similar that can show me in the right direction? I am pretty much in the dark here as what to google. Perhaps a link to something relevant? I would post any code if I had some, but I haven't really found anything useful to try yet. My form is generated through a .php function however, but saving the results is sort of the opposite of that.
Demands:
 - No page reload
 - Having the possibility to use mysql_real_escape_string before saving to db
 - Submit method: POST
 - Target db table needs question_id, option_id, user_id, date and other (for possible comments)
HTML pseudo code (generated by .PHP) - Without spans/fieldsets/labels etc
     <form action="" method="POST" id="questions">
     <input type="radio" name="1[]" value="1"/>
     <input type="radio" name="1[]" value="2"/>
     <input type="radio" name="1[]" value="3"/>

     <input type="checkbox" name="2[]" value="1"/>
     <input type="checkbox" name="2[]" value="2"/>
     <input type="checkbox" name="2[]" value="3"/>
     <input type="checkbox" name="2[]" value="4"/>
     <textarea name="2[]" placeholder="Type here..."></textarea>

     Submit
     </form>

JavaScript Code:
     function formSubmit()
     {
     document.getElementById("questions").submit();
     }

Desired output in .php:
$answers = ("questionid" => "answerid", "questionid" => "answerid", "questionid => "answertext") for all checked checkboxes/radiobuttons and textfields != "".
Edit:
I've found out I probably need an id for my form so it shall hereby be named as questions.
The best way to do it would perhaps be by calling the .php script with an onclick on the submit button.

A: It sounds like you need help doing a simple AJAX submission but maybe there's some hidden question in here I've missed but I'll answer anyway.
So what you want is to look at this tutorial here http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
You set your URL to AJAX submit to a handler PHP script which will then do what you want with the data and return a status, success/failed etc.
Hope that helps.


text:
Q: Can we prepare latex document for Perfect binding? How to make huge number of pages to prepare for
Perfect binding in latex I got from from internet about perfect binding
Perfect binding is commonly used for catalogs, directories and paperback books that have a higher page count. Pages are glued together at the spine with a strong, flexible glue. The cover is wrapped around the glued pages, and the brochure or catalog is then trimmed to its finished size.
As for example if we look at the books of "The LaTeX Companion" the total page is 1120, then normal binding may not be feasible to make the hard binding, so in that case perfect binding will choose to make the hard binding of the required book. I don't have much idea about binding. As far as my concern each consist of bundle of sheets and each sheet contain two pages on one side and two  pages on another side of different page numbering. Thanking you in advance.

A: The word you need to know: imposition.
Imposition is the arrangement of pages on a piece of paper, so that they are in the correct places when the paper is cut and folded.
For example, a perfect bound 5.5in x 8.5in book might have 4 pages printed, double-side, on 8.5in x 11in paper. One side of the paper will have pages 1 and 4, each oriented sideways. The other side of the paper will have pages 2 and 3. When folded, the order becomes 1, 2, 3, 4.  This must be done for every group of four pages.
That is not a job for TeX. Doing it with TeX is theoretically possible, but would require a great deal of manual coding. It is a job for professional PDF software, intended for print production. You could probably do it in Adobe Reader, four pages at a time.
But that is all way beyond the scope of TeX.
And, I DO know how Perfect Binding works.
Edit: In view of following comments and answer, I note: When I wrote my original reply (above), I assumed that the OP was trying to obtain a book size that was essentially half the size of the unfolded paper. That's a common technique for do-it-yourself books where I live. But it is not applicable to every size book and paper. The actual situation could be simpler (if book size is paper size) or much more complicated (commercial press).

A: I'm no expert on binding techniques (I have but dabbled so far), so if I have misunderstood the problem, I apologize. But since it hasn't been mentioned yet: You can create signatures with the pdfpages package.
I have two documents:
.
├── child.tex
└── Main.tex

Child Document
child.tex contains your actual content. In this case, it is a simple article with the twoside option and some dummy text:
\documentclass[a4paper,11pt,twoside]{article}
\usepackage{lipsum}
\begin{document}
\section{First Page}
\lipsum[1]
\clearpage\section{Second Page}
\lipsum[2]
\clearpage\section{Third Page}
\lipsum[3]
\clearpage\section{Fourth Page}
\lipsum[4]
\clearpage\section{Fifth Page}
\lipsum[5]
\clearpage\section{Sixth Page}
\lipsum[6]
\clearpage\section{Seventh Page}
\lipsum[7]
\clearpage\section{Eighth Page}
\lipsum[8]
\clearpage\section{Ninth Page}
\lipsum[9]
\clearpage\section{Tenth Page}
\lipsum[10]
\clearpage\section{Eleventh Page}
\lipsum[11]
\clearpage\section{Twelfth Page}
\lipsum[12]
\clearpage\section{Thirteenth Page}
\lipsum[13]
\clearpage\section{Fourteenth Page}
\lipsum[14]
\clearpage\section{Fifteenth Page}
\lipsum[15]
\clearpage\section{Sixteenth Page}
\lipsum[16]
\clearpage\section{Seventeenth Page}
\lipsum[17]
\end{document}

After compiling child.tex, child.pdf can be included in Main.tex and signatures of the desired size can be created (in this case 8 pages, resulting in two sheets of paper per signature):
Main Document
\documentclass{article}
\usepackage[landscape,a3paper]{geometry}
\usepackage{pdfpages}
\begin{document}
\includepdf[pages=-,signature=8]{child.pdf}
\end{document}

The result can be printed double-side over the long edge. Note that empty pages will be inserted at the end if necessary to fill an entire signature (in this case, seven pages, leading to three additional sheets of paper).
I have used this technique a few times since creating booklets and signatures on Linux is a bit of a pain (just google the topic and you will get a lot of hits, many of which leading to rather cumbersome solutions, at least in my humble opinion). I used to use Acrobat Reader, but its Linux version was no longer maintained last I checked. This approach has worked quite well for me so far.
EDIT: Result, First Signature
Page 1 of Main.pdf (on first physical sheet): Contains Pages 1 and 8 of child.pdf:

Page 2 of Main.pdf (on first physical sheet): Contains pages 2 and 7 of child.pdf:

Page 3 of Main.pdf (on second physical sheet): Contains pages 3 and 6 of child.pdf:

Page 4 of Main.pdf (on second physical sheet): Contains pages 4 and 5 of child.pdf:


text:
Q: Unsure How to Properly Use Swing Layouts Sorry for vague title, couldn't think of anything better. I'm trying to create a jswing application that has 4 buttons, and three boxes for images. On the left would be four buttons. First "SalesTop", Second "SalesBottom", Third "Preliminary", and Fourth "Next". The right would have three boxes of equal size that I can insert an image into, along with being able to set text next to it to distinguish what each picture is. I have tried looking but I cannot seem to get the layouts to work as I wanted.
This is what I have so far.
private JButton salesTop, salesBottom, preliminary, next;
private JLabel current;
private JPanel salesTopEx, salesBottomEx, preliminaryEx, buttonPanel;
private JFrame mainFrame = new JFrame();

 public  int CreateJPANEL() {
    buttonPanel = new JPanel();
    buttonPanel.setPreferredSize(new Dimension(150, 1000));

    salesTop = new JButton("salesTop");
    salesBottom = new JButton("salesBottom");
    preliminary = new JButton("Preliminary");

    salesTop.addActionListener(new ButtonListener("salesTop"));
    salesBottom.addActionListener(new ButtonListener("salesBottom"));
    preliminary.addActionListener(new ButtonListener("Preliminary"));

    buttonPanel.add(salesTop);
    buttonPanel.add(salesBottom);
    buttonPanel.add(preliminary);

    mainFrame.setLayout(new BorderLayout());
    mainFrame.add(buttonPanel);
    mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    mainFrame.setVisible(true);
    mainFrame.getContentPane();

    return 0;
}

A: *

*Use a JPanel with BoxLayout for the JButtons. Set the BoxLayout to vertical.

*For the images, given the images are the same size, you can just add the ImageIcon to a JLabel, along with text. You can align the text with respect to the ImageIcon anywhere you like by using label.setHorizontalTextPosition and label.setVertialTextPosition. If the images are different size, you can search SO, there are a few good answers on how to scale ImageIcons. You can also use a JPanel with BoxLayout for these JLabel. Or maybe better a GridLayout

*Just wrap those two JPanel in another JPanel with BorderLayout. You can place either one at BorderLayout.CENTER and depending on which one is CENTER put the other one either WEST or EAST
The key is to take advantage of nesting JPanels with different layout managers. You can nest as many JPanel as you need.
See more at Laying out Components Within a Container
Here's an example

import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.*;

public class NestJPanels {

    ImageIcon icon;

    public NestJPanels() {
        try {
            icon = new ImageIcon(new URL("http://sstatic.net/programmers/img/apple-touch-icon.png"));
        } catch (MalformedURLException ex) {
            Logger.getLogger(NestJPanels.class.getName()).log(Level.SEVERE, null, ex);
        }

        Box box = Box.createVerticalBox();
        for (int i = 0; i < 4; i++) {
            box.add(Box.createVerticalStrut(10));
            box.add(new JButton("Button"));
        }

        JPanel imagePanel = new JPanel(new GridLayout(0, 1));
        for (int i = 0; i < 3; i++) {
            JLabel label = new JLabel(icon);
            label.setBorder(new MatteBorder(0, 0, 2, 0, Color.GRAY));
            label.setText("StackOverflow");
            imagePanel.add(label);
        }

        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));
        panel.add(box, BorderLayout.WEST);
        panel.add(imagePanel);

        JFrame frame = new JFrame();
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(NestJPanels.class.getName()).log(Level.SEVERE, null, ex);
                }
                new NestJPanels();
            }
        });
    }
}


text:
Q: Confused in regard to Thereom about ordinary point/analytic point I am having some trouble understand the implication of the theorem

$\mathbf{Theorem}:$ If $x_o$ is an ordinary point of the ODE $P(x)y''+Q(x)y'+R(x)y=0$, ( that is $Q/P$ and $R/P$ are analytic at $x_o$) then the general solution of the ODE is of the form
$$y=\sum_{n=0}^{\infty}a_n(x-x_o)^{n}=a_oy_1(x)+a_1y_2(x)$$

Now here is where I am confused, next it says,

notice $y_1(x)=1+b_2(x-x_o)^2+..$ and $y_2=(x-x_o)+c_2(x-x_o)^2+…$ where $b_2+c_2=a_2$, hence $y_1$ satisfies $y_1(x_o)=1$ and $y'_1(x_o)=0$ and $y_2(x_o)=0$ and $y'_2(x_o)=1$

I am really having trouble understand this. How did they deduce the form of the solutions, and how can they have known what the solutions satisfy?
Thanks

A: Please correct "analytic at $x_0$" to "analytic in a neighborhood $\mathcal{N}$ of $x_0$". Analyticity isn't a point property. If $x_0$ is a regular point of the differential equation, and if $A$, $B$ are constants, then there is a unique $y$ that is analytic in $\mathcal{N}$ and is a solution of
$$
          y''+\frac{Q}{P}y'+\frac{R}{P}y = 0,\\
            y(x_0)=A,\;\; y'(x_0)=B.
$$
This existence and uniqueness result can be obtained by Picard iteration in a complex neighbhorhood of $x_0$.
A basis of solutions is $\{ y_1, y_2\}$ which satisfy the equation and the conditions
$$
    y_1(x_0)=1,\; y_1'(x_0)=0 \\
    y_2(x_0)=0,\; y_2'(x_0)=1.
$$
To see why this is a basis, suppose $y$ is a solution of the equation. Then
$$
                      w(x)=y(x_0)y_1(x) + y'(x_0)y_2(x)
$$
is also a solution of the equation with $w(x_0)=y(x_0)$, $w'(x_0)=y'(x_0)$. By uniqueness, $w = y$.
Knowing that $y_1$ and $y_2$ have McClaurin series expansion about $x_0$, it is easy to verify that the constant coefficient in the series expansion of $y_2$ is $0$ because $y_2(x_0)=0$; and the coefficient of $(x-x_0)$ is $1$ because $y_2'(x_0)=1$. Likewise, the constant coefficient for $y_1$ is $1$ and the coefficient of $(x-x_0)$ for $y_1$ is $0$.


text:
Q: Birt script behaves differently via web viewer i'm having trouble running a birt report via web. The report behaves as expected when running in html, but some scripts are not working properly via web viewer. I've got this script running on the "initialize" phase of the report (i know that a lot of the lines are not neccessary, just want be sure I got rid of any possible scripting syntax errors):
var inc_number;
var inc_number_old;
var contador;
var grupo;
var proveedor;
var contador_no_encaminadas;
var contador_encaminadas;
var contador_cerradas;
var estado;
var cliente_nombre;
var cliente_apellido;
contador = 0;
contador_no_encaminadas = 0;
contador_encaminadas = 0;
contador_cerradas = 0;
inc_number_old = 0;

And then i've got another little script running in a table row, with onRender triggering:
inc_number =  row["Incident Number"];
grupo = row["Assigned Group"];
proveedor = row["Vendor Name"];
estado = row["Status"];
cliente_nombre = row["First Name"];
cliente_apellido = row["Last Name"];

if (inc_number != inc_number_old){

    contador++;

    if (proveedor != null && grupo != "SIGMA")
        contador_encaminadas++;

    if ((proveedor == null || proveedor == "") && (grupo == "SIGMA") && (estado != "Resolved" && estado != "Closed"))
        contador_no_encaminadas++;

    if (estado == "Resolved" || estado == "Closed")
        contador_cerradas++;
}

inc_number_old = inc_number;

vars["contador_cerradas"] = contador_cerradas;
vars["contador_incidencias"] = contador;
vars["contador_no_encaminadas"] = contador_no_encaminadas;
vars["contador_encaminadas"] = contador_encaminadas;

As you may have noticed, all of this is just for displaying different sets of counts. I set some Data fields in a table calling for this variables (last four lines of the previous code block) so the report shows this counts. Well, all of this works perfectly when running via the preview tab in the workspace, or hitting the html option in the "Run" menu,  but when I try to run it via web viewer, all of the counts display 0 (probably the default value of the variables). I'd be very thankful if anyone could give me some help in this. Somehow I've got some other scripts running on cells, onRender too, that are working ok regardless the preview option I choose.
p.s. I'm working with Birt v2.5.1, I know it's a bit old, but it's the only supported version to integrate with BMC Remedy ARS, and that's what I need it for. Thanks!!

A: BIRT has different script flows for "direct" output and different for Web Viewer. There are two report creation phases: "generation" and "presentation", see BIRT events flow diagrams. In "direct" generation onCreate and onRender events are mixed and triggered together through generation phase (onCreate row 1 ; onRender row 1 ; onCreate row 2 ; onRender row 2 etc.). initialize script is exeuted once, before all.
In opposite, Web Viewer has split generation and presentation phases: first all onCreate are executed, then report is virtually closed (think "all script data is lost"), then all onRender are executed. initialize is executed twice, first time before generation phase (onCreate), second time before presentation phase (onRender). onRender may not have access to row['...'] variables, but have access to it's report element attributes, like this.foo.
It is good to have all data manipulation in onCreate rather than onRender script, because script variables are kept in one consistent phase. Presentation, for some pages may be ommited (I'm not sure), so you may have wrong results when jumping between pages in web viewer.
If you have to pass some data between generation and presentation phase, you have to store it in persistent global variable:
setPersistentGlobalVariable("name", value); //in generation phase
...
var value = getPersistentGlobalVariable("name"); //in presentation phase

There is no need to define that variable in Report Designer, just use functions above. Only one small trap may be encountered when using persistent global variables - they must be serializable in Java (it is not obvious feature for some Java data types).


text:
Q: Replace everything within the parenthesis in SQL Server **We have a user filed in our SQL server database that is stored as LastName, FirstName and an associated address as shown below.
   LastName, Firstname (Address)
I would like to select the above user field without the address. What would be the best way to accomplish a format as
    LastName, Firsname.
**

A: You have only two options for this type of problem
If you have only single ( and ), in your entity value then you can deal with using  with CHARINDEX, PATINDEX and REPLACE.
If you have more then you will have to use CLR code to support regexp
Reading

A: Try this logic
Declare @str varchar(65) = 'amol kshirsagar(thane)'
select LEFT(@str,CHARINDEX('(',@str) - 1),Right(@str,len(@str) - CHARINDEX('(',@str) + 1)


text:
Q: Data transformer- Can't Create an Object- Cannot create an instance from serialized data I'm trying to create an object in Symfony PHP.
it returns me:
"Cannot create an instance of Foo from serialized data because its constructor requires parameter \"id\" to be present."

the body request:
{
    "name": "aaa bbb",
    "id": "e5f348a0-11d5-4d49-a5bc-2c9b5abf3ad7",
    "type": "1",
}

my endpoint:
'copy_object' => [
            'method' => 'POST',
            'path' => '/api/copy_object',
            'input' => Foo::class,
        ]

my transform function:
    /**
     * @var Foo
     *                  {@inheritdoc}
     */
    public function transform($data, string $to, array $context = [])
    {

        $this->validator->validate($data);
        /** @var Foo $data */
        return $data->createNewBasedOnThat();
    }

my constructor:
    private function __construct(
        /**
         * @var string
         * @ORM\Id()
         * @ORM\Column(type="guid", unique=true)
         */
        private string $id,
        /**
         * @ORM\Column(type="string", length=255)
         */
        private string $name,

        TypeEnum $type,
    )

Maybe someone knows this problem?
Thank you!!


text:
Q: What does this underscore mean in node js I saw the following line in a node js code base.
_ => { return resolve(abc);}

Can any one give me some hint on what this _ means?
I know => is fat arrow function. This line is from a snippet of promise.

A: At the coaxing of a discussion elsewhere in this question, I'll turn my comments into an answer.
First off, I assume you aren't asking about arrow functions in general, but are just curious about the _ in  your code sample.
There is a convention (used by some) to declare and name a parameter to a callback function that you know is passed, but you are not going to be using with an underscore as a sort of placeholder.  It's a signal to people reading the code that there is an argument being passed to this callback, but you don't plan on using it in this particular invocation.  It's presence is not functional, but more for
Now, without knowing what was in the head of the developer who wrote the line of code you asked about, we can't know for sure what the underscore means, but it does appear to match that previously described convention.  There is one argument to the callback and it is not used in the implementation of the callback.
So, if our guess that this is a use of that convention is true, then in the arrow function that you show:
_ => { return resolve(abc);}

It is likely expecting one argument, but this particular use of that callback does not plan on using it, thus they named it with an _ just to signal that.

Now, there is no particular reason in Javascript that the callback needs to even define a single argument like this that be used.  The callback could just as well have been defined as:
() => { return resolve(abc);}

since there's no requirement in Javascript that you declare arguments you aren't going to use.
If the callback took two arguments and it was the first one that you weren't going to use, then it does have to be declared as something in order to allow access to the second argument:
(_, secondArg) => { return resolve(secondArg);}

A: It means that the arrow function argument is not used. They use _ as argument name for the arrow function.

A: Doesn't this mean something like this?
function(_){
    return resolve(abc);
}

A: What's happening here is that the code is using (some of) the concise syntax for arrow functions. To do this you'd write a function like this:
var f = x => x*x;

according to the docs
So with your example, the argument x is named with an _ (a valid character for variable names):
var f = _ => {return resolve(abc)}

But, it doesn't need the return or the brackets, either. It could be just:
_ => resolve(abc);

Perhaps a more readable way to write it would be with the parathesis:
() => resolve(abc);


text:
Q: Are the C++ member classes constructed before parent classes? In the scenario:
class A : public B {
private:
   C m_C;
public:
   A();
}

is
A::A() :
   m_C(5),
   B(m_C)
{}

legal? Would B::B(m_C) be invoked after C::C(int)? If so, what should I do to avoid it?

How did this came about in practice:
class MyValidator : public QRegExpValidator {
private:
    QRegExp myRegExp;
public:
    MyValidator();
    virtual void fixup(QString &f);
}

MyValidator::MyValidator()
    QRegExpValidator(QRegExp("foo"));
{}

void MyValidator::fixup(QString &f){
    // A QRegExp("foo") is also needed here.
}

I already discovered the
const QRegExp & QRegExpValidator::regExp() const;

Which alleviates the need to keep my own reference to myRegExp, so my particular problem is solved..
what remains, is what would be the best pattern if QRegExpValidator did not have such feature to retrieve it's initializer.. manually plumbing all the functions to a member class, instead of inheritance?

A: This is what the C++11 Standard has to say ([class.base.init]/10):

In a non-delegating constructor, initialization proceeds in the following order:
  — First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where "left-to-right" is the order of appearance of the base classes in the derived class base-specifier-list.
  — Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
  — Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
  — Finally, the compound-statement of the constructor body is executed.
  [ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. — end note ]

So, the base class is initialized before non-static data members. Your code may invoke undefined behavior if it actually uses the uninitialized data in any way.

In comments, we discussed one possible solution to your design problem is to use has-a rather than is-a. You worried that has-a would violate DRY (don't repeat yourself).
There are two ways I use to avoid WET (write everything (at least) twice) when using has-a. One is using conversion operators that allow your object to be passed to a function expecting your "derived" type.  The other is using a delegation operator.
class Object { /* ... */ };

class FakeDerivedObject {
    Foo foo;
    Object obj;
    //...

    // conversions
    operator Object & () { return obj; }
    operator const Object & () const { return obj; }
    operator Object * () { return &obj; }
    operator const Object * () const { return &obj; }

    // delegation
    Object * operator -> () { return &obj; }
    const Object * operator -> () const { return &obj; }
};

This way, you do not have to "re-implement" the interface of the underlying object.
FakeDerivedObject d;

d->SomeMethodOfUnderlyingObject();
SomeFunctionThatExpectsUnderlyingObject(d);

A:
Is
A::A() :     m_C(5),    B(m_C)  {}
legal?

Yes.  You can list initializers in any order you choose.

Would B::B(m_C) be invoked after C::C(int)

No.  The compiler will ignore the order you listed the initializers, and initialize bases first in the order they are listed in the class declaration, followed by members in the order they are declared in the class declaration.
Note that most compilers have a warning level which will warn you when initializers are listed in an order other than that matching how the initializers will actually be invoked.  According to some coding standards, it is required to list the initializers in the order in which they will be invoked.

A: Example:
class Base {
public:
    Base(){}
};

class Derived: public Base {
public:
    Derived();

private:
    int _v1;
    int _v2;
};

The construction order will be ever Base --> _v1 --> _v2


text:
Q: Bookdown does not print table No reproducible example here as bookdown has too many dependencies, so I hope the description is enough. With current versions of bookdown, the new furniture package, etc and related packages, the following fails to generate a table in the HTML bookdown output, but the code works fine in Rmarkdown.
Here is the Rmd call:
```{r table 1, results='asis'}
```

and the associated Rchunk is:
 # --- table 1 ----

table1(research,
       seqquarter,
       MAIN_ORDER_MNEMONIC,
       splitby = ~new_Priority, output='markdown'
)

The wrapping text is all there, just no table.
I would welcome suggestions. Thanks,

A: The fault (of course) was mine .
The Rchunk had three dashes on the left side, not four.
Four is the magic number for Rchunks.
The table was printed (quite nicely, actually) in a different section of the report.