text:
Q: Random Number generator printing a pattern I am trying to create a Dice Roll game where the user can roll up to 6 dice at a time. I am attempting to accomplish this by integrating pointers into my code. I am getting an output, with the desired amount of rolls as given by the user, but the output is incorrect. It is printing a pattern instead of printing random numbers. Any help is appreciated.
How many dice would you like to roll?
user input: 4
output: 3 0 3 0
How many dice would you like to roll?
user input: 5
output: 4 0 4 0 4
#include <stdio.h>
#include <stdlib.h>

void tossDie(int []);

int main() {

int diceArray[6] = { 0 };
int num = 0;
int x;

do {
    printf("\nHow many dice would you like to roll? Please enter here: ");
    scanf_s("%d", &num);//user enters amount of dice they want to roll)

    if (num < 1 || num > 6) {
        printf("\n\nPlease enter a number between 1 and 6.\n\n");
    }
} while (num < 1 || num > 6);

tossDie(diceArray);

//print dice roll numbers
for (x = 0; x < num; x++) {
    printf("%d ", diceArray[x]);
  }

  return 0;
}

 void tossDie(int numbers[]){

  int randomNum;
  int x;

  srand(time(NULL));
  randomNum = (rand() % 6) + 1;  //random # between 1 - 6

  for (x = 0; x < 6; x++){
      numbers[x] += randomNum;
      x++;
    }
  };

A: *

*Move srand(time(NULL)); to main().  Only needed once.

*Only call x++ only per loop, not twice, to assigned all 6 elements of the array.

*Move randomNum = (rand() % 6) + 1; to inside for loop to get different values.

*Check return value of scanf_s("%d", &num); against 1, before using num.
Tip: Use an auto-formatter to save time and improve code presentation.
Design:  I'd expect tossDie(int numbers[]) to also receive a  num to indicate numbers[] width.

A: Before I answer, please note that I don't program in C, so there may be some language-specific things that I am missing.
In your tossDie() function, you set the value of randomNum once, but don't reassign it after that. Therefore, your output should return the same number for all values in the array, like such:
Input: 5
Output: 3 3 3 3 3
To fix that, you should put the variable declaration in the for loop (if you want to use a variable at all).
Additionally, you initialise the random variable every time you run the method. Instead, you should declare it once, in the main method.
Also, there's a little issue in this block of code:
for (x = 0; x < 6; x++){
  numbers[x] += randomNum;
  x++;
 }
};

You increase x twice in here: both in the first line and the third line. Instead, you should delete the x++ in the third line and have just the x++ in the first line.
Let me know if you have further questions or if there are still problems.


text:
Q: Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' I tried to Identity service on autofac but I have got that error.
I am using .NET CORE 3.1.1 version.

Autofac.Core.DependencyResolutionException: An exception was thrown while activating Business.Concrete.AuthManager -> Microsoft.AspNetCore.Identity.UserManager1[[Core.Entities.Concrete.ApplicationUser, Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore9[[Core.Entities.Concrete.ApplicationUser, Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Microsoft.AspNetCore.Identity.IdentityRole, Microsoft.Extensions.Identity.Stores, Version=3.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[DataAccess.Concrete.EntityFramework.Context.MyApplicationDbContext, DataAccess, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[Microsoft.AspNetCore.Identity.IdentityUserClaim1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], Microsoft.Extensions.Identity.Stores, Version=3.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[Microsoft.AspNetCore.Identity.IdentityUserRole1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], Microsoft.Extensions.Identity.Stores, Version=3.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[Microsoft.AspNetCore.Identity.IdentityUserLogin1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], Microsoft.Extensions.Identity.Stores, Version=3.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[Microsoft.AspNetCore.Identity.IdentityUserToken1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], Microsoft.Extensions.Identity.Stores, Version=3.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[Microsoft.AspNetCore.Identity.IdentityRoleClaim1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], Microsoft.Extensions.Identity.Stores, Version=3.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].
   ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore9[Core.Entities.Concrete.ApplicationUser,Microsoft.AspNetCore.Identity.IdentityRole,DataAccess.Concrete.EntityFramework.Context.MyApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserRole1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String],Microsoft.AspNetCore.Identity.IdentityRoleClaim1[System.String]]' can be invoked with the available services and parameters:
  Cannot resolve parameter 'DataAccess.Concrete.EntityFramework.Context.MyApplicationDbContextcontext' of constructor 'Void .ctor(DataAccess.Concrete.EntityFramework.Context.MyApplicationDbContext, Microsoft.AspNetCore.Identity.IdentityErrorDescriber)'.
     at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable1 parameters)
     at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters)
     at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget)
     --- End of inner exception stack trace ---
     at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget)
     at Autofac.Core.Resolving.InstanceLookup.Execute()
     at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters)
     at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable1 parameters)
     at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable1 parameters)
     at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable1 parameters)
     at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable1 parameters, Object& instance)
     at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable1 parameters)
     at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable1 parameters)
     at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType)
     at Autofac.Extensions.DependencyInjection.AutofacServiceProvider.GetService(Type serviceType)
     at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
     at lambda_method(Closure , IServiceProvider , Object[] )
     at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.b__0(ControllerContext controllerContext)
     at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.g__CreateController|0(ControllerContext controllerContext)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
  --- End of stack trace from previous location where exception was thrown ---
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
     at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
     at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

This is my AutofacBusinessModule.cs
namespace Business.DependencyResolvers.Autofac
{
    public class AutofacBusinessModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {

            builder.RegisterType<AuthManager>().As<IAuthService>();
            builder.RegisterType<UserServiceManager>().As<IUserService>();

            builder.RegisterType<JwtHelper>().As<ITokenHelper>();

            // ------  What should I write in this part for Identity implementation? -------

        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: TabHost in a fragment with NavigationDrawer Well, I'm trying to create a TabHostFragment inside a Fragment, the problem that I'm facing is that I can't implement it because I'm using already a drawer navigation. I was looking for some answers here in SO, but I didn't find the best way to do it.
I'm using this Navigation drawer example, but I've added more fragments and more items, the thing is that I tried to implement this code of this example, but it doesn't work. I know it can be possible because Google Play, YouTube, Play Music... all of those app have a drawer navigation with Tabs inside.

The problem is that one of the all things I've tried is create a TabHostFragment adapter like in the example of the answer and then at the time to do this :
private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;

    switch (position) {
    case 0:
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);

        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
                MisOfertasFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
                RecomendacionesFragment.class, null);
        break;

I don't know if it's the correct way to do this but I tried, this case it's where it controls what item of the navigation drawer is clicked, then when the user clicks on the first item it should show the TabHost.
LogCat error looks like :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.widget.TabHost$TabSpec android.support.v4.app.FragmentTabHost.newTabSpec(java.lang.String)' on a null object reference

The line where is pointed this error is :
 mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),

and in displayView(0):
    if (savedInstanceState == null) {
        // on first time display view for first nav item
        displayView(0);
    }

I know this is not the best idea to go the FragmentTabHost (implement this on the switch case), but I tried also creating a new class like the exmaple of the answer and cann on this case fragment = new ClassWithTabs and it give to me the same error.
Please tell me what I'm missunderstanding or doing wrong, because I don't get what I'm doing wrong.
If you guys need more code you can ask to me and I'll post it as fast as I can.
EDIT
I've changed the import, I had import android.app.FragmentManager; and I changed to import android.support.v4.app.FragmentManager;, and only is giving me one error that is in this bunch of code :
if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit(); //here's the error

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);

Error --> Error:(253, 37) error: incompatible types: android.app.Fragment cannot be converted to android.support.v4.app.Fragment
EDIT2
package info.androidhive.slidingmenu;
import info.androidhive.slidingmenu.adapter.NavDrawerListAdapter;
import info.androidhive.slidingmenu.model.NavDrawerItem;
import java.util.ArrayList;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

    public class MainActivity extends FragmentActivity {
        private DrawerLayout mDrawerLayout;
        private ListView mDrawerList;
        private ActionBarDrawerToggle mDrawerToggle;
        // saber si esta abierto
        public boolean mDrawerOpened;
        // nav drawer title
        private CharSequence mDrawerTitle;

        // used to store app title
        private CharSequence mTitle;

        //para ponerlo visible
        public MenuItem mi;

        // slide menu items
        private String[] navMenuTitles;
        private TypedArray navMenuIcons;

        private ArrayList<NavDrawerItem> navDrawerItems;
        private NavDrawerListAdapter adapter;

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

            mTitle = mDrawerTitle = getTitle();

            // load slide menu items
            navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

            // nav drawer icons from resources
            navMenuIcons = getResources()
                    .obtainTypedArray(R.array.nav_drawer_icons);

            mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

            navDrawerItems = new ArrayList<NavDrawerItem>();

            // adding nav drawer items to array
            // Home
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
            // Find People
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
            // Photos
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
            // Communities, Will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
            // Pages
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
            // What's hot, We  will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
            //AyudaSugerencias
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));

            // Recycle the typed array
            navMenuIcons.recycle();

            mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

            // setting the nav drawer list adapter
            adapter = new NavDrawerListAdapter(getApplicationContext(),
                    navDrawerItems);
            mDrawerList.setAdapter(adapter);

            // enabling action bar app icon and behaving it as toggle button

            getActionBar().setDisplayHomeAsUpEnabled(true);
            getActionBar().setBackgroundDrawable(new ColorDrawable(0xff1d97dd));
            getActionBar().setHomeButtonEnabled(true);

            mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                    R.drawable.ic_drawer, //nav menu toggle icon
                    R.string.app_name, // nav drawer open - description for accessibility
                    R.string.app_name // nav drawer close - description for accessibility
            ) {
                public void onDrawerClosed(View view) {
                    getActionBar().setTitle(
                            Html.fromHtml(""
                                    + mTitle + ""));

                    // calling onPrepareOptionsMenu() to show action bar icons
                    invalidateOptionsMenu();
                    mDrawerOpened = false;
                    syncState();

                }

                public void onDrawerOpened(View drawerView) {
                    getActionBar().setTitle(
                            Html.fromHtml(""
                                    + mDrawerTitle + ""));

                    // calling onPrepareOptionsMenu() to hide action bar icons
                    invalidateOptionsMenu();
                    mDrawerOpened = true;
                    syncState();
                }
            };
            mDrawerLayout.setDrawerListener(mDrawerToggle);

            if (savedInstanceState == null) {
                // on first time display view for first nav item
                displayView(0);
            }
        }

        /**
         * Slide menu item click listener
         * */
        private class SlideMenuClickListener implements
                ListView.OnItemClickListener {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                // display view for selected nav drawer item
                displayView(position);
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            getMenuInflater().inflate(R.menu.main, menu);

            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            Fragment fragment = null;
            // toggle nav drawer on selecting action bar app icon/title
            if (mDrawerToggle.onOptionsItemSelected(item)) {
                return true;
            }
            // Handle action bar actions click
            switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
                case R.id.ofertasRefresh:
                    return true;
                case R.id.menu_search:
                    return true;
                case R.id.newOffer:
                    getFragmentManager().beginTransaction().replace(R.id.frame_container, new TipusNouProducte()).commit();
                    return true;
            default:
                return super.onOptionsItemSelected(item);
            }
        }

        /* *
         * Called when invalidateOptionsMenu() is triggered
         */
        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            // if nav drawer is opened, hide the action items
            boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
            menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
            if (mDrawerOpened) { menu.removeItem(R.id.ofertasRefresh);
            menu.removeItem(R.id.menu_search);menu.removeItem(R.id.newOffer);}
            if (!mDrawerOpened) { menu.add(Menu.NONE, R.id.ofertasRefresh, Menu.NONE, mTitle); }
            return super.onPrepareOptionsMenu(menu);

        }

        /**
         * Diplaying fragment view for selected nav drawer list item
         * */
        private void displayView(int position) {
            //Fragment fragment = null;  ---Removed for test, because if I don't remove this line couldn't execute the app because fragment can not call a FragmentActivity....
            FragmentActivity fragment = null;

            switch (position) {
                case 0:
                    fragment = new TabHostFragment();
                    break;

                default:
                break;

                if (fragment != null) {
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, fragment).commit(); /// here says that replace android.app.Fragment in FragmentTransaction cannot be applied...

                    // update selected item and title, then close the drawer
                    mDrawerList.setItemChecked(position, true);
                    mDrawerList.setSelection(position);
                    setTitle(navMenuTitles[position]);
                    mDrawerLayout.closeDrawer(mDrawerList);
                } else {
                    // error in creating fragment
                    Log.e("MainActivity", "Error in creating fragment");
                }
            }
        }

        @Override
        public void setTitle(CharSequence title) {
            mTitle = title;
            getActionBar().setTitle(mTitle);

        }

        /**
         * When using the ActionBarDrawerToggle, you must call it during
         * onPostCreate() and onConfigurationChanged()...
         */

        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            // Sync the toggle state after onRestoreInstanceState has occurred.
            mDrawerToggle.syncState();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            // Pass any configuration change to the drawer toggls
            mDrawerToggle.onConfigurationChanged(newConfig);
        }

    }

This is the error

This is the TabHostFragment.class
    package info.androidhive.slidingmenu;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;

/**
 * Created by Joan on 26/02/2015.
 */
public class TabHostFragment extends FragmentActivity {
    // Fragment TabHost as mTabHost
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabhost);

        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
                MisOfertasFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
                RecomendacionesFragment.class, null);

    }
}

EDIT3
 private void displayView(int position) {
    //Fragment fragment = null;  ---Removed for test, because if I don't remove this line couldn't execute the app because fragment can not call a FragmentActivity....

    if(position == 0){

        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
        setContentView(R.layout.tabhost);

        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Mis ofertas"),
                MisOfertasFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Recomendaciones"),
                RecomendacionesFragment.class, null);
    }
    else
    {
        Fragment fragment = null;

        switch (position) {
            case 1:
                fragment = new RecomendacionesFragment();
                break;
            case 2:
                fragment = new LocalizacionFragment();
                break;
            case 3:
                fragment = new ListaProductosFragment();
                break;
            case 4:
                fragment = new ConfiguracionFragment();
                break;
            case 5:
                fragment = new AyudaSugerenciasFragment();
                break;
            case 6:
                fragment = new AyudaSugerencias();
                break;

            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit(); /// here says that replace android.app.Fragment in FragmentTransaction cannot be applied...

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }
}

EDIT4 LogCatError
Process: info.androidhive.slidingmenu, PID: 2495
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.slidingmenu/info.androidhive.slidingmenu.MainActivity}: android.content.ActivityNotFoundException: Unable to find explicit activity class {info.androidhive.slidingmenu/info.androidhive.slidingmenu.TabHostFragment}; have you declared this activity in your AndroidManifest.xml?
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    at android.app.ActivityThread.access$800(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {info.androidhive.slidingmenu/info.androidhive.slidingmenu.TabHostFragment}; have you declared this activity in your AndroidManifest.xml?
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1761)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
    at android.app.Activity.startActivityForResult(Activity.java:3736)
    at android.app.Activity.startActivityForResult(Activity.java:3697)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:817)
    at android.app.Activity.startActivity(Activity.java:4007)
    at android.app.Activity.startActivity(Activity.java:3975)
    at info.androidhive.slidingmenu.MainActivity.displayView(MainActivity.java:221)
    at info.androidhive.slidingmenu.MainActivity.onCreate(MainActivity.java:138)
    at android.app.Activity.performCreate(Activity.java:5933)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    at android.app.ActivityThread.access$800(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

A: You have forgotten to call
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

Add the above in your displayView() method immediately after calling findViewById().
EDIT:
1. Extend your MainActivity from FragmentActivity and not from Activity.
2. Make sure your FragmentManager is imported as
import android.support.v4.app.FragmentManager;

and not as
import android.app.FragmentManager;

EDIT 2:
Make sure your Fragment is imported as
import android.support.v4.app.Fragment;

and not as
import android.app.Fragment;

EDIT 3:
Your displayView() method should be:
private void displayView(int position) {
        //Fragment fragment = null;  ---Removed for test, because if I don't remove this line couldn't execute the app because fragment can not call a FragmentActivity....

    if(position == 0){

        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
        Intent intent = new Intent(MainActivity.this, TabHostFragment.class);
        startActivity(intent);
    }
    else
    {
        Fragment fragment = null;

        switch (position) {
        case 1:
            fragment = new RecomendacionesFragment();
            break;
        case 2:
            fragment = new LocalizacionFragment();
            break;
        case 3:
            fragment = new ListaProductosFragment();
            break;
        case 4:
            fragment = new ConfiguracionFragment();
            break;
        case 5:
            fragment = new AyudaSugerenciasFragment();
            break;
            case 6:
                fragment = new AyudaSugerencias();
                break;

            default:
            break;
         }

            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment).commit(); /// here says that replace android.app.Fragment in FragmentTransaction cannot be applied...

                // update selected item and title, then close the drawer
                mDrawerList.setItemChecked(position, true);
                mDrawerList.setSelection(position);
                setTitle(navMenuTitles[position]);
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                // error in creating fragment
                Log.e("MainActivity", "Error in creating fragment");
            }
        }
        }
    }


text:
Q: IntelliJ doesn't print scala hello word? I installed IntelliJ and scala. And I created a Scala console program.
object  Hello {
  def main(args: Array[String]): Unit = {
    println("Test")
  }
}

However, it doesn't show anything after I clicked the Run menu item.

"C:\Program Files (x86)\Java\jdk1.8.0_121\bin\java" -Djline.terminal=NONE "-javaagent:C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2017.1\lib\idea_rt.jar=42884:C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2017.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\scala\lib\scala-compiler.jar;C:\Program Files (x86)\scala\lib\scala-library.jar;C:\Program Files (x86)\scala\lib\scala-reflect.jar;C:\Users\....\.IdeaIC2017.1\config\plugins\Scala\lib\scala-plugin-runners.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\charsets.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\deploy.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\access-bridge-32.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\cldrdata.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\dnsns.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\jaccess.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\jfxrt.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\localedata.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\nashorn.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\sunec.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\sunjce_provider.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\sunmscapi.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\sunpkcs11.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\ext\zipfs.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\javaws.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\jce.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\jfr.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\jfxswt.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\jsse.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\management-agent.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\plugin.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\resources.jar;C:\Program Files (x86)\Java\jdk1.8.0_121\jre\lib\rt.jar;C:\Program Files (x86)\scala\lib\scala-parser-combinators_2.12-1.0.4.jar;C:\Program Files (x86)\scala\lib\scala-swing_2.12-2.0.0-M2.jar;C:\Program Files (x86)\scala\lib\scala-xml_2.12-1.0.6.jar" org.jetbrains.plugins.scala.compiler.rt.ConsoleRunner -usejavacp
Welcome to Scala 2.12.1 (Java HotSpot(TM) Client VM, Java 1.8.0_121).
Type in expressions for evaluation. Or try :help.

scala>

A: You ran scala console and not your script. Do no forget to install the scala plugin for intelliJ as well.
Here is explained how to install it : https://www.jetbrains.com/help/idea/2017.1/creating-and-running-your-scala-application.html


text:
Q: Define Path for secret in Hashicorp not work with Quarkus I have this error when I deploy my app:

My properties are these:

quarkus.vault.secret-config-kv-path=kv2/dev/test/test/getting-started-v1
quarkus.vault.kv-secret-engine-version=2
quarkus.vault.authentication.kubernetes.role=getting-started-v1

My policy in hashicorp is the same and the role is attached for this policie.
When I disabled this property: quarkus.vault.secret-config-kv-path the app running but not load any secrets this is the console message:

I have used this documentation
Any help or idea for get the values for hashicorp, probably other method programmatic

A: This could be a typical issue with kv ver 1 vs 2. Ver 2 has different path. You should consider it in your settings and policy, check the document: https://developer.hashicorp.com/vault/tutorials/secrets-management/versioned-kv#compare-kv-v1-and-kv-v2
In most cases you need to add data after a mount point in the path: kv2/data/dev/test/test...


text:
Q: SalesforceDX: Log in to sandbox by username/password from command line without browser involved Is it possible to log in from sfdx CLI to already existent sandbox having username/password combination?
Reading through documentation I see bunch of ways how to authorize - through browser, by providing JWT token and consumer key, using existent access token etc. But cannot find a simple way how to do it in a browserless way just by providing username & password right in command line.
We just need to deploy code and run tests against our qa sandbox from CI pipeline - need to authorize an org somehow without human being involved. Is there a simpler way than following whole JWT authorization flow, i.e. creating connected app on each sandbox, upload certificate etc.
Any help would be appreciated.

A: sfdx force:auth only provides the JWT and web OAuth login methods:
sfdx force:auth commands: (get help with sfdx help force:auth:COMMAND)
 force:auth:jwt:grant      authorize an org using the JWT flow
 force:auth:logout         log out from authorized orgs
 force:auth:sfdxurl:store  authorize an org using an SFDX auth URL
 force:auth:web:login      authorize an org using the web login flow

But... there's a couple of different ways around the lack of a direct username/password login option.
One's to use sfdx force:source:convert to build a Metadata API package. Provided you have configured your sandbox so that CLI access doesn't require completing the verification code (or you're logging in with a security token), you can then use any existing Metadata API deployment tool (Force.com Migration Tool, Force.com CLI, etc) to perform the deploy using the username and password alone.
Another route is to login to the sandbox by hand once, locally, via force:auth:web:login. Then do sfdx force:org:display -u <username> --verbose to get the SFDX authentication URL, which starts with force:// and includes the OAuth refresh token (not the session id). You can store that securely in an encrypted file and later load it into SFDX with sfdx force:auth:sfdxurl:store -f <thefile>. (Credit to CRMScience for documenting this approach).

A: You could use the auth command from the sfpowerkit plugin:
sfpowerkit auth:login
https://github.com/Accenture/sfpowerkit
It supports login with username-password combination (probably will need security token as well). A functionality that the standard CLI lacks


text:
Q: Make all properties in an array observable I have an array coming back from an ajax request. I bind this array to an observableArray in knockout. I would like to know how I can iterate over the array prefixeData and make each of the element's properties observable. Is this possible?
var viewModel = {
            name: "Editor",
            prefixeData: ko.observableArray([]),
            getPrefixes: function (prefix) {

                var params = {
                    "prefix": prefix
                };

                $.ajax({

                    type: "POST",
                    url: "XXXX.aspx/GetPrefixes",
                    data: JSON.stringify(params),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        var trans = data.d;
                        if (trans.Successful) {

                          viewModel.prefixeData(trans.ResultObject);
                            // this doesnt work
                          viewModel.prefixeData().forEach(function(data) {
                                data.LevelName=ko.observable(data.LevelName);

                            });
                        } else {
                            //todo
                        }

                    },
                    error: function (xhr, textStatus, err) {

                        alert("Status: " + textStatus); alert("Error: " + err);

                    }

                });
            }
        };

A: u need import knockout.mapping knockout.mapping
and edit your code like:
success: function (data) {
                        var trans = data.d;
                        if (trans.Successful) {
                         var observableArray = ko.mapping.fromJS(trans.ResultObject);
                         viewModel.prefixeData(observableArray());
                        //viewModel.prefixeData now is observableArray, you can call foreach : viewModel.prefixeData at html
                        } else {
                            //todo
                        }

                    },


text:
Q: How to fix local.ERROR: failed loading cafile stream using Laravel I have problem regarding on local.ERROR: failed loading cafile stream: `C:\xampp\apache\bin\curl-ca-bundle.crt', before that Currently I'm developing new system Cron Job is an daily email scheduling. now I just create a basic concept of emailing. and I use Laravel to create this system.
I just follow this instruction failed loading cafile stream: `C:\xampp\apache\bin\curl-ca-bundle.crt'
however, on my laravel logs still shows
    [2019-07-29 05:21:55] local.ERROR: failed loading cafile stream: `C:\xampp\apache\bin\curl-ca-bundle.crt' {"exception":"[object] (ErrorException(code: 0): failed loading cafile stream: `C:\\xampp\\apache\\bin\\curl-ca-bundle.crt' at C:\\xampp\\htdocs\\CronSystem\\vendor\\swiftmailer\\swiftmailer\\lib\\classes\\Swift\\Transport\\StreamBuffer.php:94)
[stacktrace]

I will share to you guys my codes.
On my Mail Folder
    <?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendMailApplication extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('Emailing')
        ->to('hiddeeeee@gmail.com','hideeee')
        ->from('noreplyhideee@gmail.com', 'New Applicant');
    }
}

My Command:
    <?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use App\User;
use App\Mail\SendMailApplication;

class Emailing extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'emailing:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Ready to fire emailing each user...';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        \Mail::send(new SendMailApplication());

        // $users = User::all();

        // foreach($users as $user) {

        //     // Create a unique 8 character promo code for user
        //     // $new_promo_code = new PromoCode([
        //     //     'promo_code' => str_random(8),
        //     // ]);

        //     // $user->promo_code()->save($new_promo_code);

        //     // Send the email to user
        //     Mail::send('emailing', ['user' => $user], function ($mail) use ($user) {
        //         $mail->to($user['email'])
        //             ->from('noreplyhfiofi@gmail.com', 'Company')
        //             ->subject('Happy Birthday!');
        //     });

        // }

        // $this->info('Birthday messages sent successfully!');
        // // \Log::info("Email sent!");
        // //script which you have run in cron
    }
}

My Kernel:
    <?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
        'App\Console\Commands\Emailing',
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        //Schedule happen here...

        $schedule->command('emailing:cron')
                 ->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

.env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=noreplyhfiofi@gmail.com
MAIL_PASSWORD=hiflyer123
MAIL_ENCRYPTION=tls


text:
Q: squad2.0 training error: THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=50 error=100 : no CUDA-capable device is detected !python -m torch.distributed.launch --nproc_per_node=8 /root/examples/run_squad.py \
    --model_type bert \
    --model_name_or_path bert-large-uncased-whole-word-masking \
    --do_train \
    --do_eval \
    --do_lower_case \
    --train_file /root/DATA/train-v2.0.json \
    --predict_file /root/DATA/dev-v2.0.json \
    --learning_rate 3e-5 \
    --num_train_epochs 2 \
    --max_seq_length 384 \
    --doc_stride 128 \
    --output_dir ../root/result/ \
    --per_gpu_eval_batch_size=3   \
    --per_gpu_train_batch_size=3   \

I'm using google colab and I want to training my A&Q dataset which downloaded from SQuad website.
But when I run the code above it return me an error.
Can some one help me fix this problem?The full error msg as following and I'll appreciate any suggestions:
this is error msg:
    [THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=50 error=100 : no CUDA-capable device is detected
    THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=50 error=100 : no CUDA-capable device is detected
    Traceback (most recent call last):
      File "/root/examples/run_squad.py", line 575, in
        main()
      File "/root/examples/run_squad.py", line 469, in main
        torch.cuda.set_device(args.local_rank)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 300, in set_device
        torch._C._cuda_setDevice(device)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 193, in _lazy_init
        torch._C._cuda_init()
    RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50
    Traceback (most recent call last):
      File "/root/examples/run_squad.py", line 575, in
    THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=50 error=100 : no CUDA-capable device is detected
        main()
    THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=50 error=100 : no CUDA-capable device is detected
    THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=50 error=100 : no CUDA-capable device is detected
    Traceback (most recent call last):
      File "/root/examples/run_squad.py", line 575, in
        main()
    THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=50 error=100 : no CUDA-capable device is detected
      File "/root/examples/run_squad.py", line 469, in main
    Traceback (most recent call last):
      File "/root/examples/run_squad.py", line 469, in main
        torch.cuda.set_device(args.local_rank)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 300, in set_device
        torch.cuda.set_device(args.local_rank)
        torch._C._cuda_setDevice(device)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 193, in _lazy_init
        torch._C._cuda_init()
    Traceback (most recent call last):
      File "/root/examples/run_squad.py", line 575, in
        main()
    RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 300, in set_device
        torch._C._cuda_setDevice(device)
      File "/root/examples/run_squad.py", line 575, in
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 193, in _lazy_init
      File "/root/examples/run_squad.py", line 469, in main
        torch._C._cuda_init()
        main()
        torch.cuda.set_device(args.local_rank)
    RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 300, in set_device
        torch._C._cuda_setDevice(device)
      File "/root/examples/run_squad.py", line 469, in main
        torch.cuda.set_device(args.local_rank)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 193, in _lazy_init
        torch._C._cuda_init()
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 300, in set_device
        torch._C._cuda_setDevice(device)
    RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 193, in _lazy_init
        torch._C._cuda_init()
    RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50
    Traceback (most recent call last):
      File "/root/examples/run_squad.py", line 575, in
        main()
      File "/root/examples/run_squad.py", line 469, in main
        torch.cuda.set_device(args.local_rank)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 300, in set_device
        torch._C._cuda_setDevice(device)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 193, in _lazy_init
        torch._C._cuda_init()
    RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50
    THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=50 error=100 : no CUDA-capable device is detected
    Traceback (most recent call last):
      File "/root/examples/run_squad.py", line 575, in
        main()
      File "/root/examples/run_squad.py", line 469, in main
        torch.cuda.set_device(args.local_rank)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 300, in set_device
        torch._C._cuda_setDevice(device)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 193, in _lazy_init
        torch._C._cuda_init()
    RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50
    THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=50 error=100 : no CUDA-capable device is detected
    Traceback (most recent call last):
      File "/root/examples/run_squad.py", line 575, in
        main()
      File "/root/examples/run_squad.py", line 469, in main
        torch.cuda.set_device(args.local_rank)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 300, in set_device
        torch._C._cuda_setDevice(device)
      File "/usr/local/lib/python3.6/dist-packages/torch/cuda/init.py", line 193, in _lazy_init
        torch._C._cuda_init()
    RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50
    Traceback (most recent call last):
      File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
        "main", mod_spec)
      File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
        exec(code, run_globals)
      File "/usr/local/lib/python3.6/dist-packages/torch/distributed/launch.py", line 253, in
        main()
      File "/usr/local/lib/python3.6/dist-packages/torch/distributed/launch.py", line 249, in main
        cmd=cmd)
    subprocess.CalledProcessError: Command '['/usr/bin/python3', '-u', '/root/examples/run_squad.py', '--local_rank=7', '--model_type', 'bert', '--model_name_or_path', 'bert-large-uncased-whole-word-masking', '--do_train', '--do_eval', '--do_lower_case', '--train_file', '/root/DATA/train-v2.0.json', '--predict_file', '/root/DATA/dev-v2.0.json', '--learning_rate', '3e-5', '--num_train_epochs', '2', '--max_seq_length', '384', '--doc_stride', '128', '--output_dir', '../root/result/', '--per_gpu_eval_batch_size=3', '--per_gpu_train_batch_size=3']' returned non-zero exit status 1.]


text:
Q: An inverse Laplace transform involving Error function Dear MOs,
I need to calculate the inverse Laplace transform of the following function
$$
g_a(z) = \frac{e^{a z}\: \text{erfc}(\sqrt{a z})}{\sqrt{z}-2},\quad a>0.
$$
I have checked, among many others, the book "Table of Integral Transform, Vol. I". In P.267, Eq. (14) is for
$$
g(z) = \frac{e^{a z}\: \text{erfc}(\sqrt{a z})}{\sqrt{z}}
$$
which is almost what I need. Other than this formula, I didn't find the one that I need. I have tried mathematica, which couldn't give an answer. I think the hope to find out the solution is quite small.
EIDT: here is some motivation of the problem.
Suppose the inverse transform gives us a function $f_a(t)$. I want to see the limit $$\lim_{a\rightarrow 0_+} f_a(t)=?$$
Can I simply do this:
$$
\lim_{a \rightarrow 0_+} \mathcal{L}^{-1}\left(g_a\right)(t) \stackrel{?}{=}  \mathcal{L}^{-1}\left(\lim_{a\rightarrow 0_+} g_a\right)(t) =
\mathcal{L}^{-1}\left(g_0\right)(t) =\frac{1}{\sqrt{\pi t}} +  2 e^{4t} \text{erfc}(-2\sqrt{t})
$$
Are there some Lebesgue's dominated convergence theorems to use in complex analysis?
Thank you very much for any hints!
Anand


text:
Q: UINavigationBar Rounded Two Corners I want to round the top right and top left of the UINavigationBar.
I know that there are functions for changing the views corner radius, but is it possible to do something similar to the standard UINavigationBar?
If you don't know what I'm talking about, check out this:

Thanks!

A: the following code works for me (tested on iOS5).
The following code rounds the top left/right corners of the main navigation bar. Additionally, it adds a shadow to it:
CALayer *capa = [self.navigationController navigationBar].layer;
[capa setShadowColor: [[UIColor blackColor] CGColor]];
[capa setShadowOpacity:0.85f];
[capa setShadowOffset: CGSizeMake(0.0f, 1.5f)];
[capa setShadowRadius:2.0f];
[capa setShouldRasterize:YES];

//Round
CGRect bounds = capa.bounds;
bounds.size.height += 10.0f;    //I'm reserving enough room for the shadow
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds
                                               byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
                                                     cornerRadii:CGSizeMake(10.0, 10.0)];

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = bounds;
maskLayer.path = maskPath.CGPath;

[capa addSublayer:maskLayer];
capa.mask = maskLayer;

A: The best way is to override drawRect in UINavigationBar and use a custom image.

A: You might find this helpful. Maybe you could also do some kind of masking with CoreAnim/Image? I'm not very knowledgeable about the Core* family...
http://foobarpig.com/iphone/uinavigationbar-with-solid-color-or-image-background.html


text:
Q: need to separate the key in associative array i need help to find best practice answer for current code.
ill be thankful for you help.
how can i loop through this array in the best way:
$data = [
    'element1.child.property1'  => 1,
    'element1.child.property2'  => 2,
    'element2.child.name'       => 3,
    'element2.child2.name'      => 4,
    'element2.child2.position'  => 5,
    'element3.child3.position'  => 6,
];

to get answer like that
$result = [
    'element1' => [
        'child' => [
            'property1' => 1,
            'property2' => 2,
        ]
    ],
    'element2' => [
        'child' => [
            'name' => 3
        ],
        'child2' => [
            'name' => 4,
            'position' => 5
        ]
    ],
    'element3' => [
        'child3' => [
            'position' => 6
        ]
    ],
];

A: You can loop through the array and explode the key of each element by ".", and then populate your new array:
<?php

$data = [
    'element1.child.property1'  => 1,
    'element1.child.property2'  => 2,
    'element2.child.name'       => 3,
    'element2.child2.name'      => 4,
    'element2.child2.position'  => 5,
    'element3.child3.position'  => 6,
];

foreach ($data as $key => $value) {
    $key = explode(".", $key);
    $newData[$key[0]][$key[1]][$key[2]] = $value;
}

print_r($newData);
?>

Which gives you this:
Array
    (
    [element1] => Array
        (
            [child] => Array
                (
                    [property1] => 1
                    [property2] => 2
                )

        )

    [element2] => Array
        (
            [child] => Array
                (
                    [name] => 3
                )

            [child2] => Array
                (
                    [name] => 4
                    [position] => 5
                )

        )

    [element3] => Array
        (
            [child3] => Array
                (
                    [position] => 6
                )

        )

)

A: Here is your array :
$data = [
    'element1.child.property1'  => 1,
    'element1.child.property2'  => 2,
    'element2.child.name'       => 3,
    'element2.child2.name'      => 4,
    'element2.child2.position'  => 5,
    'element3.child3.position'  => 6,
];

1/ First, create a result array :
$result = array();

2/ Then you will loop through your array and build the desired output:
foreach ($data as $key => $value) {
    $elt = explode(".", $key);

    // Here you will have :
    // $elt[0] = "elementX";
    // $elt[1] = "child";
    // $elt[2] = "property1"; (OR "name" OR "position"...)

    $result[$elt[0]][$elt[1]][$elt[2]] = $value;
}

3/ Now if you look the result he looks like the output you want:
var_dump($result);

$result = [
    'element1' => [
        'child' => [
            'property1' => 1,
            'property2' => 2,
        ]
    ],
    'element2' => [
        'child' => [
            'name' => 3
        ],
        'child2' => [
            'name' => 4,
            'position' => 5
        ]
    ],
    'element3' => [
        'child3' => [
            'position' => 6
        ]
    ],
];

Hope it helps

A: More dynamic for variable lengths and deeper or shallower nesting.  You can use this function and loop your array using the keys as the path and value as the value.  Result will be in $result:
function set($path, &$array=array(), $value=null) {
    $path = explode('.', $path);
    $temp =& $array;

    foreach($path as $key) {
        $temp =& $temp[$key];
    }
    $temp = $value;
}

foreach($data as $path => $value) {
    set($path, $result, $value);
}

See How to access and manipulate multi-dimensional array by key names / path? for other uses.


text:
Q: What are the downsides of overriding `equals()` in this way? Consider the usual example of the immutable ComplexNumber class for Java (which doesn't have a ComplexNumber struct like C# does). Of course it's necessary to override toString(), equals() and hashCode().
Unlike Scala, we can't do type matching with smart casts (that's IntelliJ Kotlin terminology). This line of thought led me to write this equals() override:
    public boolean equals(ComplexNumber other) {
        if (other == null) return false; // Thanks, Andreas
        if (Double.doubleToLongBits(this.real) != Double.doubleToLongBits(other.real)) return false;
        return Double.doubleToLongBits(this.imag) == Double.doubleToLongBits(other.imag);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (this.getClass() != obj.getClass()) return false;
        return (this.equals((ComplexNumber) obj));
    }

For now I'm not too concerned about giving any tolerance for loss of machine precision.
In Mathematica, defining things in the wrong order can cause unexpected problems. Not so much in Java. I switched the order of the two equals(), added print lines and ran the tests.
equals(Object) invoked
equals(ComplexNumber) invoked
div
minus
times
plus
toString
equals(Object) invoked
equals(Object) invoked
equals(ComplexNumber) invoked
getRealPart
getImagPart
equals(Object) invoked
equals(ComplexNumber) invoked
equals(Object) invoked
equals(ComplexNumber) invoked
hashCode
equals(Object) invoked
equals(ComplexNumber) invoked
equals(Object) invoked
equals(ComplexNumber) invoked
equals(Object) invoked
equals(Object) invoked
equals(ComplexNumber) invoked
equals

Regardless of order, it passes all the relevant tests in my test class, but I get the feeling I'm not testing for something that becomes an issue if I do it this way. There's no need to create a final copy, but instead there's a need for one more thing on the call stack, so performance-wise this might be a wash if it's not an actual drain. I also get the feeling this might be a problem in the Scala REPL.
On a purely practical level, I'm perfectly content to pretty much use the standard generated equals() override on this one. But I am curious as to the disadvantages of doing it this way, besides that it doesn't feel idiomatic.

A: This is a good implementation. Eric Evans in his book "domain driven design" has implemented equality of an ValueObject this way. He called the 'equals' as 'sameValuAs' to distinguish between them and overridden equals() calls sameValueAs similar to your implication.
I will advice to modify equals method to return false when the class type is not of type ComplexNumber using instanceof method. Here is an example -
    public boolean sameValueAs(ComplexNumber other) {
        if (other == null) return false;
        if (Double.doubleToLongBits(this.real) != Double.doubleToLongBits(other.real)) return false;
        return Double.doubleToLongBits(this.imag) == Double.doubleToLongBits(other.imag);
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj) return true;
        if (!(obj instanceof ComplexNumber)) return false;
        return sameValueAs((ComplexNumber) obj));
    }


text:
Q: Trigonometry Question - find the width of the river and height of the post A river running due east has straight parallel banks. A vertical post stands with its base, $P$, on the north side of the river. On the south bank are two surveyors, $A$ who is to the east and $B$ who is to the west of the post. $A$ and $B$ are at a distance $2a/7$ apart and the angle $APB = 150^\circ$. The angles of elevation from $A$ and $B$ of the top $Q$, of the post are $45^\circ$ and $30^\circ$. Find in terms of $a$, the width of the river and the height of the post.

A: See the image of my work.
Is this correct?


text:
Q: Can I / How to implement object recognition in app? our aim is to develop an automotive app which automates and standardizes photo shooting of newly arrived cars at dealership. Basically, our Mavic 2 Pro takes off, orbits the vehicle and shoots photo every 90 degrees and than lands to its original position. The orbiting radius is app 4.5 m.
Since the scene of shooting is small (or when shooting indoor, GPS might not be available), we would like to rely more on built in object recognition as implemented in activetrack missions. We have currently an app based on waypoint mission, but it is not accurate. So my questions are:
1, Can anyone point us in direction how to implement object recognition in our app?
2, If recognition is not available, how to ensure consistency of output? While testing, sometimes the output exif info of photos show compass deviation up to 4 degrees, which results in object being out of view.
Thanks for advice,
Mirek

A: What you need is object recognition and tracking like YOLO.
The resources are here.
https://pjreddie.com/darknet/yolo/
Then you need to train the model to recognize cars, so you need a bunch of labeled photos where the car bounding box has been already given correctly.
Downstream you want then have the camera connect to a computer and stream the video, have the tracking algorithm recognize the bonding box of the car and, depending on center and size, maneuver the drone accordingly.


text:
Q: How to code a custom segue that "slides" between View Controllers? I built a app with storyboard, with an initial view controller, connected to many  subsequent view controllers, connected sequentially, using cross dissolve segue. These work one swipes.  All works fine.  However,  instead of being forced to use the basic segues, I want to have a custom segue that will slide the view controller content on and off the screen, much like the push for navigationControllers, but, being enabled to go left and right depending if one is going forward or backwards in the app.
I have set the segue to custom, and have created and saved a MySegue.h file. HOWEVER, I don't know how to code a custom segue that will slide one viewcontroller off the screen as the other slides on and back and forth as I move between view controllers.
Can anyone please provide me with come coding (it should be easy!) for a custom segue to move from one view controller to the next and back by sliding the screen on and off so I don't have to use the basic cross dissolve or standard flips offered in Xcode 4.2? I would be most grateful.

A: I was running into the same issue here, but I was using swipe gestures to go from one view controller to the next. Using the storyboard itself to set up segues was working fine, but when I needed a swipe to "go back" to the previous view controller, the animation went from right-to-left, instead of left-to-right. To fix that issue I did the following:

*

*Embedded a Navigation Controller in the root view controller.

*Used segues to push new view controllers.

*When I wanted to "go back" to the previous view controller, I did not add a segue to the storyboard to push the previous view controller. Instead, I called the Navigation Controller's popViewControllerAnimated method whenever a back swipe occurred.

A: To create a custom segue that slides view controllers first create a class that extends UIStoryboardSegue, then override the perform selector. I just made something like this and it should work for you too. Here's my code:
#define kAnimationDuration 0.5

#import "CustomSlideSegue.h"

@implementation CustomSlideSegue

- (void)perform
{
    UIViewController *sourceViewController = (UIViewController *) self.sourceViewController;
    UIViewController *destinationViewController = (UIViewController *) self.destinationViewController;

    [sourceViewController.view addSubview:destinationViewController.view];
    [destinationViewController.view setFrame:sourceViewController.view.window.frame];

    [destinationViewController.view setBounds:sourceViewController.view.bounds];
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;

    if ( !self.slideLeft ) {
        [UIView animateWithDuration:kAnimationDuration
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             [destinationViewController.view setCenter:CGPointMake(screenSize.height + screenSize.height/2, screenSize.height/2 - 138)];
                             [destinationViewController.view setCenter:CGPointMake(screenSize.width/2 + 127, screenSize.height/2 - 138)];
                         }
                         completion:^(BOOL finished){
                             [destinationViewController.view removeFromSuperview];
                             [sourceViewController presentViewController:destinationViewController animated:NO completion:nil];
                         }];
    } else {
        [UIView animateWithDuration:kAnimationDuration
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             [destinationViewController.view setCenter:CGPointMake(-1*screenSize.height/2, screenSize.height/2 - 138)];
                             [destinationViewController.view setCenter:CGPointMake(screenSize.width/2 + 127, screenSize.height/2 - 138)];
                         }
                         completion:^(BOOL finished){
                             [destinationViewController.view removeFromSuperview];
                             [sourceViewController presentViewController:destinationViewController animated:NO completion:nil];
                         }];
    }
}

Then when you want to perform the segue use this code:
   UIViewController *destination = [self.storyboard instantiateViewControllerWithIdentifier:@"some identifier"];
   CustomZoomSegue *segue = [[CustomZoomSegue alloc] initWithIdentifier:@"segue vc identifier" source:self destination:destination];
   [self prepareForSegue:segue sender:self];
   [segue perform];

The CGPointMake calls are custom to my code (I used landscape orientation) but you should be able to change it to fit your needs. If you need further clarification or have any question let me know and I will try to answer.
NOTE: I use storyboards with no segue lines between the view controllers.

A: Why not just use a UINavigationController? This seems to be exactly what they're designed for.


text:
Q: Adding custom field to DocumentInfoValidators I want to use a custom field in my PDF metadata. When the PDF loads with pdf.js and examine the contents of getMetadata() the field is missing, because it isn't included in the list of valid fields DocumentInfoValidators.
If I add my field directly in the pdf.js source I can see my field - but is there a proper way to add a custom field name, or is it usual to modify and build my own version?
I'm using pdfjs@1.7.312.
I can see the definition in pdf.worker.js around line 39125, in the definition of PDFDocument; then it gets used later in documentInfo()
var DocumentInfoValidators = {
  get entries() {
   return shadow(this, 'entries', {
    Title: isString,
    Author: isString,
    Subject: isString,
    Keywords: isString,
    Creator: isString,
    Producer: isString,
    CreationDate: isString,
    ModDate: isString,
    Trapped: isName
   });
  }
 };


text:
Q: R : Remove words with 3 or more repeating letters using GSUB I need to remove words with 3 or more repeating letters from a string using gsub. Example:
"It has been raining verrrry badly heeere last few days"
I need to to get the following using gsub function:
"It has been raining badly last few days". 'verrrry' and 'heeere' words are removed from the string.

A: Option 1
x <- "It has been raining verrrry badly heeere last few days"
m <- gregexpr('\\s\\b\\w*(\\w)\\1{2,}\\w*\\b\\s', x, perl = TRUE)
regmatches(x, m) <- ' '
x
# [1] "It has been raining badly last few days"

Option 2
x <- "It has been raining verrrry badly heeere last few days"
sp <- strsplit(x, ' ')[[1]]
s <- sp[!sapply(sp, function(y) any(rle(strsplit(y, '')[[1]])$lengths >= 3))]
paste(s, collapse = ' ')
# [1] "It has been raining badly last few days"

A: A possible solution by constructing a regular expression for your case firstly.
regExp <- paste(sapply(letters, paste, "{3,}", sep = ""), collapse = "|")
> regExp

"a{3,}|b{3,}|c{3,}|d{3,}|e{3,}|f{3,}|g{3,}|h{3,}|i{3,}|j{3,}|k{3,}|l{3,}|m{3,}|n{3,}|o{3,}|p{3,}|q{3,}|r{3,}|s{3,}|t{3,}|u{3,}|v{3,}|w{3,}|x{3,}|y{3,}|z{3,}"

words <- unlist(strsplit(origStr, "\\s+"))
cleanStr <- paste(words[!grepl(regExp, words)], collapse = " ")
cleanStr
[1] "It has been raining badly last few days"

A: A quick search brought up this SO answer. Using that you can do something like:
## string with repeated letters
s <- "It has been raining verrrry badly heeere last few days"

## split string into vector of words to select
svec <- unlist(strsplit(s, " "))

## find words with 3 or more repeated letters/numbers
## (for any general symbol use '.' instead of '\\w')
rmword <- grep("(\\w)\\1{2, }", svec)

## join words into single string again, removing the unwanted ones
paste(svec[-rmword], collapse = " ")

## output:
[1] "It has been raining badly last few days"

EDIT to answer the follow-up request
. Also changed grep to grepl
First let's wrap the code into a function:
rm.repeatLetters <- function(x){
  xvec <- unlist(strsplit(x, " "))
  rmword <- grepl("(\\w)\\1{2, }", xvec)
  return(paste(xvec[!rmword], collapse = " "))
}

Then to use it on a data frame:
df <- data.frame(id=c(1, 2, 3), text=c(s, s, s), stringsAsFactors=FALSE)
## > df
##   id                                                   text
## 1  1 It has been raining verrrry badly heeere last few days
## 2  2 It has been raining verrrry badly heeere last few days
## 3  3 It has been raining verrrry badly heeere last few days

df$text <- sapply(df$text, rm.repeatLetters)
## > df
##   id                                    text
## 1  1 It has been raining badly last few days
## 2  2 It has been raining badly last few days
## 3  3 It has been raining badly last few days

A: This looks like the output string you're aiming at:
origStr = "It has been raining verrrry badly heeere last few days"

newStr <- gsub("e{3,}","e", origStr ) # replaces e's greater than 2 repeat
(newStr <- gsub("r{3,}","r", newStr )) # replaces r's greater than 2 repeat

# [1] "It has been raining very badly here last few days"

A: Here's one way:
library(tm)
data("acq")
acq[[12]]$content -> sometext
tm::MC_tokenizer(x = sometext) -> q
q[131] <- "eeee"

sapply(letters, FUN = function(x) {
    grepl(paste0(x, "{3,}"), x = q, ignore.case = TRUE) -> k
    k
}) -> zz

apply(X = zz, 1, sum) -> flag
q[ifelse(flag == 1, FALSE, TRUE)] -> newq
paste(newq, collapse = " ") -> final


text:
Q: Handshake entre aplicación y servidor No encontré palabras para poner al título, les explico.
Tengo una aplicación web que utilizamos en la empresa, la tengo programada en el evento OnBlur para que vaya a la base de datos y guarde la información que se ingresó.
Desafortunadamente el día de hoy se fue la luz en el servidor y no entró tan rápido la planta y se apagó. Pero nadie se dió cuenta pues la página seguía funcionando. (En RAM)
Una persona le dió F5 a su máquina y por obvias razones no guardó su proceso, ya implementé que la gente triggeree el evento OnBlur en todos los campos, para que dicha información se guarde.
Me gustaría saber si hay alguna función que, cuando el servidor se apague, marque error en la parte operativa y no les permita continuar, algo como lifeping cada minuto entre el back-end y el front-end
Uso Jquery, AJAX y Bootstrap del lado del cliente.
PHP y Apache del lado del servidor.
Agradezco sus sugerencias y apoyo.

A: Has visto LocalStorage de HTML5? Eso podría ser una 'alternativa' para mantener la data guardada localmente en el navegador para luego ser enviada al servidor.
Con lo que publicas, veo un potencial problema de consistencia de datos... Por otro lado, lo que podrías hacer es un AJAX cada minuto con un set interval que genere un GET de un recurso por ejemplo una imagen. Si el recurso marca error (porque el server se apagó) entonces que deshabilite el botón siguiente/enviar o cualquier otro que impida continuar con su trabajo.


text:
Q: Angular 2.0 lifecycle and Typescript I have an Angular 2.0 component and I wanted to add lifecycle events to it (Angular 2.0 Alfa 35).
I was looking at this post as a reference, but Typescript gave me errors for using the
import {Component, View, EventEmitter, onInit} from 'angular2/angular2';
(error on onInit). A quick look at Angular2 code revealed that the export uses OnInit (with capital O). I changed the import code but the lifecycle event itself is still onInit. This is my component (I cannot make onInit event happen):
import {Component, View, EventEmitter, OnInit} from 'angular2/angular2';

@Component({
  selector: 'theme-preview-panel-component',
  properties: ['fontSize'],
  lifecycle: [onInit]
})
@View({
    templateUrl: '../components/theme-preview-panel-component/theme-preview-panel-component.tpl.html',
})
export class ThemePreviewPanelComponent {
  fontSize: string;
  constructor() {
  }

  onInit() {
    //This code is not being called
  }
}

EDIT
As @Eric Martinez mentioned below, the solution is:
import {Component, View, EventEmitter, LifecycleEvent} from 'angular2/angular2';

    @Component({
      selector: 'theme-preview-panel-component',
      properties: ['fontSize'],
      lifecycle: [LifecycleEvent.onInit]
    })
    @View({
        templateUrl: '../components/theme-preview-panel-component/theme-preview-panel-component.tpl.html',
    })
    export class ThemePreviewPanelComponent {
      fontSize: string;
      constructor() {
      }

      onInit() {
        //Now this code is being called
      }
    }


text:
Q: Ongoing confusion about ivars and properties in objective C After almost 8 months being in ios programming, I am again confused about the right approach. Maybe it is not the language but some OOP principle I am confused about. I don't know..
I was trying C# a few years back. There were fields (private variables, private data in an object), there were getters and setters (methods which exposed something to the world), and properties which was THE exposed thing. I liked the elegance of the solution, for example
there could be a class that would have a property called DailyRevenue...a float...but there was no private variable called dailyRevenue, there was only a field - an array of single transaction revenues... and the getter for DailyRevenue property calculated the revenue transparently.
If somehow the internals of daily revenue calculation would change, it would not affect somebody who consumed my DailyRevenue property in any way, since he would be shielded from getter implementation.
I understood that sometimes there was, and sometimes there wasn't a 1-1 relationship between fields and properties. Depending on the requirements. It seemed ok in my opinion. And that properties are THE way to access the data in object.
I know the difference betweeen private, protected, and public keyword.
Now lets get to Objective-C.
On what factor should I base my decision about making something only an ivar or making it as a property? Is the mental model the same as I describe above? I know that ivars are "protected" by default, not "private" as in C#.. But thats ok I think, no big deal for my present level of understanding the whole iOS development. The point is ivars are not accessible from outside (given I don't make them public.. but I won't).
The thing that clouds my clear understanding is that I can have IBOutlets from ivars. Why am I seeing internal object data in the UI? *Why is it ok?* On the other hand, if I make an IBOutlet from property, and I do not make it readonly, anybody can change it. Is this ok too?
Let's say I have a ParseManager object. This object would use a built in Foundation framework class called NSXMLParser. Obviously my ParseManager will utilize this NSXMLParser's capabilities but will also do some additional work. Now my question is, who should initialize this NSXMLParser object and in which way should I make a reference to it from the ParseManager object, when there is a need to parse something.
A) the ParseManager
-1) in its default init method (possible here ivar  - or - ivar+ppty)
-2) with lazyloading in getter (required a ppty here)
B) Some other object - who will pass a reference to NSXMLParser object to the ParseManager object.
-1) in some custom initializer (initWithParser:(NSXMLPArser *)parser) when creating the ParseManager object..
A1 - the problem is, we create a parser and waste memory while it is not yet needed. However, we can be sure that all methods that are part of ParserManager object, can use the ivar safely, since it exists.
A2 - the problem is, the NSXMLParser is exposed to outside world, although it could be read-only. Would we want a parser to be exposed in some scenario?
B1 - this could maybe be useful when we would want to use more types of parsers.. I don't know...
I understand that architectural requirements and language is not the same. But clearly the two are in relation.
How to get out of that mess of my?
Please bear with me, I wasn't able to come up with a single ultimate question. And secondly, it's better to not scare me with some superadvanced newspeak that talks about some crazy internals (what the compiler does) and edge cases.

A: First, I think you're asking many questions, not one.
And half of the answers of these questions is the ever correct "It depends".
In general, exposing object ivars directly is discouraged if you're aiming for looser coupling (obviously). Although I think when it comes to IBOutlets it is an acceptable practice, since after all the Interface Builder is tasked with the creation of the object.
On the other hand, a readwrite property for an NSInteger makes little sense, unless you're doing something very funky, and you can easily use an ivar instead.
Once upon a time, in pre-ARC ages, there were some people, who advocated always using properties for objects, since then you don't need to care about retain/release. However now that ARC is widely used, this makes almost no difference and it is mostly a cosmetical thing.
A final piece of advice: aim for consistency project-wide.
EDIT: I'm not the greatest fan imaginable of Design Patterns, but it seems that most of your questions would find the best answer in this book.

A: Well, as mentioned above, there're so many questions :)
First of all, you should read more about properties and the whole Objective-C principles. In modern Objective-C style you should not use ivars at all. Only properties with some very rare exceptions. For private properties there's some unusual trick: class extensions. You definitely should read about categories and extensions since they are very powerful and useful mechanics. You just keep your private properties and all outlets in the class extension and no one will see it outside your class implementation. But you'll be still able to access your outlets in Interface Builder! It's amazing solution I use everyday and feels good.
Now for your question about ParserManager. As said above, it depends. If you don't want the actual NSXMLParser be accessed directly outside the manager (you'd better don't :)), just leave it inside and create in the manager. I'd recommend to create it in the init method because of quite heavy and continuos initialization of such huge object. Yes, you're waste some memory for it much earlier you actually need it, but you'll get much faster access when the time's come.

A: You usually have a property and a variable backing it. You keep the backing variable hidden. But it lets you do things like taking actions if a setter actually changes the property. Or for cached properties, you set the variable to nil and the getter stored the correct value on the first call. Or setters and getters read from a database and so on.
Sometimes you have properties like the center of a view that can be read by calculating the center from left and width, or where the setter moves the view so it's center is where the setter wanted it.


text:
Q: Angular 2 Observable.forkJoin results I have following code in my component:
public user: User;
public roles: Role[];
public organizations: Organization[];

public ngOnInit() {
  this.user$ = this.userService.getUser(1).share();
  this.roles$ = this.roleService.getRoles().share();
  this.organizations$ = this.organizationService.getOrganizations().share();

  Observable.forkJoin([this.user$, this.roles$, this.organizations$]).subscribe(data => {
    this.user = data[0];
    this.roles = data[1];
    this.organizations = data[2];
  });
}

This should work I think but I am getting error in IDEA and it wont even compile, I am stuck on this for some time now, can anyone help?

Service methods looks like this:
public getRoles(): Observable<Role[]> {
        return this.http.get(this.API_URL).map(res => res.json());
 }


text:
Q: At what cosmological redshift $z$, does the recession speed equal the speed of light? How is it calculated? At what cosmological redshift $z$, does the recession speed equal the speed of light?
What equations are used to calculate this number (since at large redshifts, $z=\dfrac{v}{c}$ won't apply)?

A: The exact number depends on the cosmological model and its parameters. In special relativistic models (e.g. the Milne model), the redshift at the speed of light is of course infinite. However, in all viable cosmological models, recession velocities exceed the speed of light for objects with redshifts greater than $z\sim 1.5$.
The general relativistic relation between recession velocity and cosmological redshift is:
$$ v_{rec}(t,z)=c\dfrac{\dot{R(t)}}{R(0)}\int_0^z{\dfrac{dz^{'}}{H(z^{'})}} $$

The solid dark lines and gray shading in the graph show a range of FLRW models.
For more details, please see: Expanding Confusion:
common misconceptions of cosmological horizons and the superluminal expansion of the universe.

A: If you have a redshift associated with a comoving object you get two answers; one for the recessional velocity it had when it emmited its light, and one for the recessional velocity it has now when its light reaches you.
One is calculated by the present distance times the Hubble constant, and the other by multiplying the former distance with the Hubble parameter at that time.
The higher the redshift, the larger the difference (for example, the last scattering surface with z=1089 had a recessional velocity of 63c when it emmited its light, and now has around 3c, since the Hubble parameter was higher in the past).
On this plot the red curve is the recessional velocity when the light was emmited, and the brown curve when the light reaches the observer (as you can see at z=10 there is already a difference of a factor ≈2, and like the previous speakers already mentioned c is at z≈1.5
At z≈1.9 the curves cross and it was the same recessional velocity then as it is now again, so objects with z<1.9 are faster now than they were then, and objects with z>1.9 are slower now then they were at the time they emmited their light:

x-axis: redshift, y-axis: recessional velocity, parameters: Planck 2013

A: From Friedmann Equation, distance as a function of redshift is:
$$d(z)=\frac{c}{H_0}\int_0^z \frac{dx}{\sqrt{\Omega_{R_0}(1+x)^4+\Omega_{M_0}(1+x)^3+\Omega_{K_0}(1+x)^2+\Omega_{\Lambda_0}}}$$
The Hubble-Lemaître Law:
$$v=H_0 \cdot d$$
We want $\boxed{v=c}$ now. The distance that fulfils this condition is known as current Hubble Distance, (or Hubble Radius, or Hubble Length):
$$d_{H_0}=\frac{c}{H_0}$$
Combining both, we obtain the condition:
$$\int_0^z \frac{dx}{\sqrt{\Omega_{R_0}(1+x)^4+\Omega_{M_0}(1+x)^3+\Omega_{K_0}(1+x)^2+\Omega_{\Lambda_0}}}=1$$
For $\Omega_{R_0}\approx 0 \quad \Omega_{K_0}\approx 0 \quad \Omega_{M_0}\approx 0.31 \quad \Omega_{\Lambda_0}\approx 0.69$
The condition is:
$$\int_0^z \frac{dx}{\sqrt{0.31(1+x)^3+0.69}}=1$$
Searching by trial and error, we find that the value of redshift that fulfils the condition is $z=1.474 \approx 1.5$
Best regards.


text:
Q: Making a Stock Options Database in Mathematica I am trying to use Mathematica to create a stock options database of sorts. That is I wish to write a function that imports the option chain of a given stock. Unfortunately Wolfram has yet to put stock options on the data server associated with FinancialData[] so I decided to obtain the necessary data from Yahoo Finance. Here is the function I wrote to do this:
rules = {"Jan" -> "01", "Feb" -> "02", "Mar" -> "03", "Apr" -> "04",
"May" -> "05", "Jun" -> "06", "Jul" -> "07", "Aug" -> "08",
"Sep" -> "09", "Oct" -> "10", "Nov" -> "11", "Dec" -> "12"};

acquireOptions[stock_String] :=
Module[{z =
StringSplit[Import["http://finance.yahoo.com/q/op?s=" <> stock <>"+Options"]],index1, index2},
index1 = Position[z, "Expiration:"][[1, 1]] + 1;
index2 = Position[z, "Call"][[1, 1]] - 1;
ArrayFlatten[(Partition[(DeleteCases[z[[index1 ;; index2]], "|"] /.
     rules), 2] /. {x_String,
    y_String} :> {"20" <> y <> "-" <> x}) /. {x_String :>
  Cases[Import[
    "http://finance.yahoo.com/q/op?s=" <> stock <> "&m=" <> x,
    "Data"], {_?NumberQ, _String, __?NumberQ}, \[Infinity]]}]]

I should note that I had to study the structure of the Yahoo Finance website hard core to make this work. Although it is functional the problem I have is that it is simply too slow. Running this function for a single stock takes about 30 seconds. Lets assume there are 1000 stocks that have options that I would want to acquire (there are probably a lot more than 1000, I would literally want to be able to acquire every last option). This would take about 8 and a half hours which is just too long. So I'm interested in how I can do this more efficiently. If I used parallel table on my 8 core machine could I expect this to only take about 2 hours?
Besides for the code I've written, I saw that Yahoo has a query language YQL that can be used to pull data off their servers. I then saw that Mathematica has Database Link SQL operations. I don't know much about SQL/YQL but would this have been a better direction to go in? If so would anyone be able to show how to link Mathematica and YQL and provide an example where YQL is used in Mathematica to obtain options data?
Oh and in case anyone was wondering why I am doing this, it is for an investment model I'm working on.
Thanks

A: I implemented this function using YQL:
acquireOptions[stock_String, expiration_, type_] :=
Module[{options, list, data},
options =
Cases[Import[
  "http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20yahoo.finance.option_chain%20WHERE%20symbol%3D'"
  <> stock <> "'%20AND%20expiration%3D'"
  <> expiration <> "'%20and%20type%3D'"
  <> type <> "'&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=", "JSON"] /.
   Rule -> List, {"sym", x_} -> x, Infinity];
list = "\"" <> StringJoin @@ Riffle[options, "\"%2C%20\""] <> "\"";
data = Import["http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20yahoo.finance.oquote%20WHERE%20symbol%20IN%20("
  <> list <> ")&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=", "JSON"] /. Rule -> List;
Transpose[#][[2]] & /@
Cases[data, {"option", __}, Infinity][[1, 2, All]]]

For example,
acquireOptions["MSFT", "2013-07", "C"]//TableForm

yields a long list with all the option data for MSFT. It displays better here as a table:

If you want to experiment with YQL you should use the YQL console.
My function is optimized for one stock but you want to get data for several different stocks. The fastest way to do this is not to use this function on each stock, rather it's to rewrite the first YQL query the way my second query is written. Using the way my second query is written, with in, you may acquire the stock option symbols for many stocks at once. In principle what you want to do you should be able to do with only two HTTP calls (two Import). One that acquires all the stock option symbols, and one that acquires the data. Since most of your time was spent on waiting for HTTP responses, this should give you an incredible speed boost.
Here's an example of how to get stock option names for many stocks at once in YQL. The console will give you the URL that you need to use:
SELECT * FROM yahoo.finance.option_chain WHERE symbol in ("YHOO","AAPL","GOOG","MSFT") AND expiration='2013-07' and type='C'

If you're wondering which element is which in the list acquireOptions returns, you may consult the table above where the elements are in the right order. For your convenience, here's a list with the corresponding elements as well:
{"ask", "bid", "change", "expire", "open", "openInterest", "prevClose", "price", "strike", "sym", "volume"}

As a final note I will add that YQL is a wrapper for an underlying API and it might be even faster to use it directly, it is described here for stock data. But it's not official and I can't find a reference with the right symbols to use for finding stock option data. Sal Mangano finds stock option data this way, however, in the Mathematica Coobook and seems to have figured it all out. But he does not include enough information to do what you want; the link he provides for more information on the Yahoo Finance API is now broken.


text:
Q: Replacing BeanUtils.setProperty with JSP/JSF EL (expression language) Is there a way I can explicitly invoke the JSP/JSF expression language (EL) as a replacement for something I might do with BeanUtils.setProperty for setting nested and indexed properties?
For example, the call BeanUtils.setProperty(object, "foo.bar", "value") will result in calling object.getFoo().setBar("value") via reflection.
Is there a way I could do that in EL instead?
What I'm trying to do is analogous to <h:inputText value="#{object.foo.bar}"> but in a back-end method instead of via the UI, where "object.foo.bar" property expression might be dynamic.  I know BeanUtils works but feels somewhat archaic.

A: You can use ValueExpression#setValue() for this.
FacesContext context = FacesContext.getCurrentInstance();
ELContext elContext = context.getELContext();
ValueExpression expression = context.getApplication().getExpressionFactory()
    .createValueExpression(elContext, "#{object.foo.bar}", String.class);
expression.setValue(elContext, "value");


text:
Q: How to calculate difference between longitude latitude? I need to calculate the difference between longitude and latitude of current position
and previous position. but it display the result in Exponential format and I need it in
metres. I don't understand how to convert it in metre format.
Which formula require for that?
double distance2 = distanceCalculate(lat,lng,locationB.getLatitude(),locationB.getLongitude());
Toast.makeText(this, "distance2=="+Double.valueOf(distance2).longValue() + "meter" , Toast.LENGTH_SHORT).show();

double ActualDistance=(Double.valueOf(distance2).longValue())/1E6;
if(ActualDistance<400)
{
    System.out.println("identical");
    Toast.makeText(this,"identical", Toast.LENGTH_LONG).show();
}
else
{
    // send sms
    SmsManager sms = SmsManager.getDefault();
}

public static float distanceCalculate (double lat1, double lng1, double lat2, double lng2 )
{
      double earthRadius = 3958.75;
      double dLat = Math.toRadians(lat2-lat1);
      double dLng = Math.toRadians(lng2-lng1);
      double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
      Math.sin(dLng/2) * Math.sin(dLng/2);
      double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      double dist = earthRadius * c;

      int meterConversion = 1609;

      return new Float(dist * meterConversion).floatValue();
}

A: i find this in JavaScript i think it's can help you to understand how you can do it

A: That's a simple one -- currently you're using the radius of the Earth in miles; simply change that for the radius in metres (per Wikipedia: 6,371,000), and remove your conversion

A: On this question, I found this code :
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
  double earthRadius = 3958.75;
  double dLat = Math.toRadians(lat2-lat1);
  double dLng = Math.toRadians(lng2-lng1);
  double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
           Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
           Math.sin(dLng/2) * Math.sin(dLng/2);
  double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  double dist = earthRadius * c;

  return dist;
}

It's a java implementation of Haversine formula.
It will return the distance in miles. For other units change the earthRadius with http://en.wikipedia.org/wiki/Earth_radius


text:
Q: JDBC prepared statement UTF-8 Continuing my previous question https://stackoverflow.com/questions/21060720/jsp-upload-file-with-utf-8-encoding
I discovered that when i do:
String url = "jdbc:mysql://localhost:3306/crm2?useUnicode=yes&characterEncoding=UTF-8";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
connection = DriverManager.getConnection (url, MY_USERNAME, MY_PASSWORD);

PreparedStatement pst = connection.prepareStatement(sql);
.
.
.

pst.setString(1, customer.getFullName());
.
.
.
pst.executeUpdate();

I got the following SQL exception:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '(name = '?…?±?ˆ?§?†'

As you can see i mentioned in the connection string too use encoding utf-8!
looks like i have to do something else in the PST to insure using UTF-8?
Thanks

A: When reading and writing to a database with UTF-8 data it is important that the Java source code file be encoded as UTF-8. Otherwise, strange things can happen when we start manipulating strings that we receive from (or send to) the database.


text:
Q: Which plugin I should use for db migration for hibernate4? I am using grails2.3.7 and hibernate4.
However, the default database-migration plugin is not working with hibernate4.
Is there any other plugin that can do the same thing but support hibernate4?
Thanks.

A: Depending on what functionality you can do without, you may be able to use straight Liquibase in your project.  It is fairly simple to setup.  You could use the manual or a presentation I gave to get yourself started.
You can always look at the source of the database-migration plugin to give you clues about how to set it up if you get stuck.

A: The plugin is updated to support hibernate4 now.
database-migration


text:
Q: How do I map Freebase topic ids to the corresponding topic names? I am using Youtube Analytics API. In the response I get the topics of channel as Freebase TopicIds. Since the Freebase API is deprecated now, how can I get the topic names to corresponding ids? I had a look at the Google Graph Search API (mentioned as an alternative to freebase api).
https://developers.google.com/knowledge-graph/#typical_use_cases.
But I am not sure if we can get topic names from topic ids using this API.

A: Use the ids parameter with the Knowledge Graph API Search API. https://developers.google.com/knowledge-graph/reference/rest/v1/