text: Q: C# OpenXML 2.5. I want to replace a merge field with an image I have a requirement to insert a mergefield say << MERGEFIELD Image >> and replace it with the actual image. I know how to loop through FieldCodes and when the field name matches with the merge field name, replace it with a TEXT value. But my requirement is to Give the users option to use a Mail merge field on the document, but then I need to replace the mail merge field with an image. Can anyone help on this with a working example.


text:
Q: Does Room, DB and DAO need to be in the same package? Im having a hard time creating a database for my login UI. Currently using a local DB with room just to start testing. I will set up a rest api and remote db later once done testing. While I have been able to get it to work on other tutorials, it appears the classes are all in the same package. With my current application I am building, I separated my packages into the types of classes they are / what they are used for I.E. Activities, Fragments, DAOs, ViewModels, Interfaces, Adapters etc. Everything works fine up until I try to initialize the db in my viewmodel. Using the debugger I can see that INSTANCE is null during the getDatabase function all the way up until the .build() and that is where it crashes.
Here is the exception log:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.whatever, PID: 13042
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.whatever/com.example.whatever.activities.LoginActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.whatever.viewModels.ViewModelEmailLogin
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
        at android.app.ActivityThread.-wrap14(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1534)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1424)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.whatever.viewModels.ViewModelEmailLogin
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.example.whatever.ui.fragments.EmailLoginFragment.onCreateView(EmailLoginFragment.java:74)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:310)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1185)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1354)
        at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1432)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1495)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2617)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2569)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1256)
        at android.app.Activity.performStart(Activity.java:6959)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2890)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
        at android.app.ActivityThread.-wrap14(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1534)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1424)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.example.whatever.ui.fragments.EmailLoginFragment.onCreateView(EmailLoginFragment.java:74)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:310)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1185)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1354)
        at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1432)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1495)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2617)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2569)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1256)
        at android.app.Activity.performStart(Activity.java:6959)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2890)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
        at android.app.ActivityThread.-wrap14(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1534)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1424)
     Caused by: java.lang.RuntimeException: cannot find implementation for com.example.whatever.db.WhatEverUserDB. WhatEverUserDB_Impl does not exist
        at androidx.room.Room.getGeneratedImplementation(Room.java:94)
        at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:952)
        at com.example.whatever.db.WhatEverUserDB.getDatabase(WhatEverUserDB.java:45)
        at com.example.whatever.repositories.WhatEverUserRepo.<init>(WhatEverUserRepo.java:33)
        at com.example.whatever.viewModels.ViewModelEmailLogin.<init>(ViewModelEmailLogin.java:31)
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.example.whatever.ui.fragments.EmailLoginFragment.onCreateView(EmailLoginFragment.java:74)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:310)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1185)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1354)
        at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1432)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1495)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2617)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2569)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1256)
        at android.app.Activity.performStart(Activity.java:6959)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2890)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
        at android.app.ActivityThread.-wrap14(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1534)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1424)
D/NetworkSecurityConfig: No Network Security Config specified, using platform default

Model
package com.example.whatever.db;

import androidx.room.Entity;
import androidx.room.PrimaryKey;

// This is an object used to create a WhatEver User
//debating if we should use WhatEver user to link to other social media accounts
// we could create lists of social sites with accounts that gather the info from the db

import java.util.List;
@Entity(tableName = "whatever_user_table")
public class WhatEverUser {

    @PrimaryKey(autoGenerate = true)// with each new row we add to the db, room will automatically create a new id
    private int ID;

    private CharSequence Username;

    private CharSequence Email;

    private CharSequence Password;

    public WhatEverUser(CharSequence Username, CharSequence Email, CharSequence Password){
        this.Username = Username;
        this.Email = Email;
        this.Password = Password;

    }

    public CharSequence getPassword() {
        return Password;
    }

    public CharSequence getEmail() {
        return Email;
    }

    public CharSequence getUsername() {
        return Username;
    }

    public int getID() {
        return ID;
    }

    public void setUsername(CharSequence username) {
        this.Username = username;
    }

    public void setPassword(CharSequence password) {
        Password = password;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public void setEmail(CharSequence email) {
        this.Email = email;
    }
}

DB
package com.example.whatever.db;

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.Database;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.example.whatever.interfaces.WhatEverUserDAO;

import com.example.whatever.db.WhatEverUser;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Database(entities = {WhatEverUser.class},version = 1)
public abstract class WhatEverUserDB extends RoomDatabase {

    private static volatile WhatEverUserDB INSTANCE;     // this is an instance of our database

    public abstract WhatEverUserDAO whatEverUserDAO();     //we use this method to access our dao
    // we use this method to access our db methods in the dao

    private static final int NUMBER_OF_THREADS = 4;

    static final ExecutorService databaseWriteExecutor =
            Executors.newFixedThreadPool(NUMBER_OF_THREADS);

    public static WhatEverUserDB getDatabase(final Context context){
        if (INSTANCE == null){
            synchronized (WhatEverUserDB.class){
                if (INSTANCE == null){
                    INSTANCE =  Room.databaseBuilder(context.getApplicationContext(),
                            WhatEverUserDB.class,
                            "whatever_user_table")
                            .allowMainThreadQueries()
                            .addCallback(roomCallback)
                            .build();
                }
            }
        }
        return INSTANCE;
    }

    private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback(){

        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db) {
            super.onOpen(db);
            databaseWriteExecutor.execute(() -> {

                WhatEverUserDAO whatEverUserDAO = INSTANCE.whatEverUserDAO();

                WhatEverUser admin = new WhatEverUser("admin","admin@admin.com","password");
                whatEverUserDAO.insertUser(admin);
                WhatEverUser test1 = new WhatEverUser("test1","test1@test1.com","test1234");
                whatEverUserDAO.insertUser(test1);

            });
        }
    };

}

    //creating the database
 /*   public static synchronized whatEverUserDB getInstance(final Context context){     //we create our only db instance, synchronized means only one thread can access this db at a time.
        if (instance == null){
            instance = Room.databaseBuilder(context.getApplicationContext(), whatEverUserDB.class, "whatever_user_database")
                    //.enableMultiInstanceInvalidation()
                    //.allowMainThreadQueries()
                    .fallbackToDestructiveMigration() //if we don't do this and try to increase the version, the app will crash, this avoids this by deleting the tables and starting from scratch
                    //.addCallback(roomCallback)
                    .build();
        }
        return instance;
    }
    */

 /*   private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback(){
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
          //  new PopulateDBAsyncTask(instance).execute();
        }
    };

 private  static class PopulateDBAsyncTask extends AsyncTask<Void, Void, Void> { // Creating this async task to populate the db for test users
        private WhatEverUserDAO whatEverUserDAO;

        private PopulateDBAsyncTask(whatEverUserDB db){
            whatEverUserDAO = db.whatEverUserDAO();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            whatEverUserDAO.insertUser(new WhatEverUser("admin","admin@admin.com","password"));
            whatEverUserDAO.insertUser(new WhatEverUser("test1","admin1@admin.com","password"));
            whatEverUserDAO.insertUser(new WhatEverUser("test2","admin2@admin.com","password"));

            return null;
        }
    }

*/

// must extend roomDb and be abstract
// version must be changed every time we create a new db from scratch
// we should not leave userDB on devices, this will eventually need to be grabbed from our own sql server so this class may be removed later TODO

DAO
package com.example.whatever.db;

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.Database;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.example.whatever.interfaces.WhatEverUserDAO;

import com.example.whatever.db.WhatEverUser;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Database(entities = {WhatEverUser.class},version = 1)
public abstract class WhatEverUserDB extends RoomDatabase {

    private static volatile WhatEverUserDB INSTANCE;     // this is an instance of our database

    public abstract WhatEverUserDAO whatEverUserDAO();     //we use this method to access our dao
    // we use this method to access our db methods in the dao

    private static final int NUMBER_OF_THREADS = 4;

    static final ExecutorService databaseWriteExecutor =
            Executors.newFixedThreadPool(NUMBER_OF_THREADS);

    public static WhatEverUserDB getDatabase(final Context context){
        if (INSTANCE == null){
            synchronized (WhatEverUserDB.class){
                if (INSTANCE == null){
                    INSTANCE =  Room.databaseBuilder(context.getApplicationContext(),
                            WhatEverUserDB.class,
                            "whatever_user_table")
                            .allowMainThreadQueries()
                            .addCallback(roomCallback)
                            .build();
                }
            }
        }
        return INSTANCE;
    }

    private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback(){

        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db) {
            super.onOpen(db);
            databaseWriteExecutor.execute(() -> {

                WhatEverUserDAO whatEverUserDAO = INSTANCE.whatEverUserDAO();

                WhatEverUser admin = new WhatEverUser("admin","admin@admin.com","password");
                whatEverUserDAO.insertUser(admin);
                WhatEverUser test1 = new WhatEverUser("test1","test1@test1.com","test1234");
                whatEverUserDAO.insertUser(test1);

            });
        }
    };

}

    //creating the database
 /*   public static synchronized whatEverUserDB getInstance(final Context context){     //we create our only db instance, synchronized means only one thread can access this db at a time.
        if (instance == null){
            instance = Room.databaseBuilder(context.getApplicationContext(), whatEverUserDB.class, "whatever_user_database")
                    //.enableMultiInstanceInvalidation()
                    //.allowMainThreadQueries()
                    .fallbackToDestructiveMigration() //if we don't do this and try to increase the version, the app will crash, this avoids this by deleting the tables and starting from scratch
                    //.addCallback(roomCallback)
                    .build();
        }
        return instance;
    }
    */

 /*   private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback(){
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
          //  new PopulateDBAsyncTask(instance).execute();
        }
    };

 private  static class PopulateDBAsyncTask extends AsyncTask<Void, Void, Void> { // Creating this async task to populate the db for test users
        private WhatEverUserDAO whatEverUserDAO;

        private PopulateDBAsyncTask(whatEverUserDB db){
            whatEverUserDAO = db.whatEverUserDAO();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            whatEverUserDAO.insertUser(new WhatEverUser("admin","admin@admin.com","password"));
            whatEverUserDAO.insertUser(new WhatEverUser("test1","admin1@admin.com","password"));
            whatEverUserDAO.insertUser(new WhatEverUser("test2","admin2@admin.com","password"));

            return null;
        }
    }

*/

// must extend roomDb and be abstract
// version must be changed every time we create a new db from scratch
// we should not leave userDB on devices, this will eventually need to be grabbed from our own sql server so this class may be removed later TODO

Repo
package com.example.whatever.repositories;

import android.app.Application;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;

import com.example.whatever.db.WhatEverUser;
import com.example.whatever.db.WhatEverUserDB;
import com.example.whatever.interfaces.WhatEverUserDAO;

import androidx.lifecycle.LiveData;

// UserRepo connects the view model to the room. Transmits LiveData from room to ViewModel
// takes requests from ViewModel
// This class is not necessary but recommended , it provides an abstraction between the db and vm
// Repo can grab data from the SQLite db or an internet resource
// REPO can make API calls
// The viewModel calls methods from the repo directly
// The repo calls methods from the DAO

public class WhatEverUserRepo {

    private static final String TAG = "MainActivity";

    private WhatEverUserDAO whatEverUserDao;
    private LiveData userName;
    private LiveData userPassword;

    public WhatEverUserRepo(Application application){

        WhatEverUserDB database = WhatEverUserDB.getDatabase(application);
        whatEverUserDao = database.whatEverUserDAO();
        //userName = whatEverUserDao.getUsername();

    }
    public void setUserName(LiveData whatEverUserName){

            userName = whatEverUserName;
    }

    public void getUserName(WhatEverUser whatEverUser){

    }

    public void insertUserName(String userName){

    }
    public void getUserEmail(String whatEverUserEmail){

    }

    public void insertUserEmail(String whatEverUserEmail){

    }

    public void insertUserPassword(String userPassword){

    }

   /* public LiveData<String> getUserName() {
        return userName;
    }*/
// we will need to copy this method and use it in each public method above for each action
 private static class getUserAsyncTask extends AsyncTask<WhatEverUser,Void, Void> {

        private WhatEverUserDAO wUserDAO ;
        private WhatEverUser whatEverUser;

    private getUserAsyncTask(WhatEverUser whatEverUser){
            this.wUserDAO = wUserDAO;
        }

        @Override
        protected Void doInBackground(WhatEverUser... whatEverUser) {
            //wUserDAO.getUsername();
            return null;
        }
    }

public void startThread(View view){
    for (int i = 0; i  < 10; i++){
        Log.d(TAG,"startThread: " + i);
        try {
            Thread.sleep(1000);

        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}

public void stopThread(View view){

}

}

ViewModel
package com.example.whatever.viewModels;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.whatever.db.WhatEverUser;
import com.example.whatever.repositories.WhatEverUserRepo;

public class ViewModelEmailLogin extends AndroidViewModel {
    private static final String TAG = "WhatEverLogState";

    private WhatEverUserRepo whatEverUserRepo;
    private MutableLiveData<WhatEverUser> whatEverUser;
    private MutableLiveData<CharSequence> UserName = new MutableLiveData<>();
    private MutableLiveData<CharSequence> uPassword = new MutableLiveData<>();
    private MutableLiveData<CharSequence> UserEmail = new MutableLiveData<>();
    private MutableLiveData<WhatEverUser> WhatEverUser = new MutableLiveData<>();

     public ViewModelEmailLogin(@NonNull Application application) {

        super(application);
         Log.i(TAG, "Instanced");

         whatEverUserRepo = new WhatEverUserRepo(application);
         Log.i(TAG, "Set whatEverUserRepo");

         LiveData<WhatEverUser> whatEverUserLiveData; // not sure what this is for
         LiveData<CharSequence>UserEmail;
         LiveData<CharSequence>UserPassword;

    }

}

and Gradle
apply plugin: 'com.android.application'
//apply plugin: 'kotlin-android'
//apply plugin: 'kotlin-kapt'
//apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.whatever"
        minSdkVersion 24
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildFeatures{
        dataBinding true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    def lifecycle_version = '2.2.0'
    def room_version = '2.2.5'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation "com.google.android.material:material:1.1.0"

    implementation 'androidx.cardview:cardview'
    implementation 'androidx.recyclerview:recyclerview'

    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.annotation:annotation:1.1.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'

    implementation 'com.twitter.sdk.android:twitter:3.1.1'
    implementation 'com.twitter.sdk.android:twitter-core:3.1.1'

    //lifecycle components
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"

    // Room Components
    implementation "androidx.room:room-runtime:$room_version"
    implementation "androidx.core:core-ktx:+"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"

 //   implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    //kapt "androidx.arch.persistence.room:compiler$room_version"
//    kapt "androidx.room:room-compiler:2.2.5"

}
repositories {
    mavenCentral()
}

A: As indicated in the Room setup instructions, the build dependencies must include:
"annotationProcessor "androidx.room:room-compiler:$room_version"

redpajama_set_name: RedPajamaStackExchange


text:
Q: apt remove gcc-5 dependency errors I'm face on some troubles here. I'm trying to remove gcc-5, however there are a lot of dependencies that will be affect by it. I'm looking for a magician that could help me uninstall it without make a huge difference in my system.
My system is:
Description:    Ubuntu 16.04.6 LTS
Release:    16.04
Codename:   xenial

I filtered all the dependencies relative to gcc 5 that I wanna uninstall and, I had this output:
$ sudo dpkg -l | grep '16.04.11'

ii  cpp-5                                        5.4.0-6ubuntu1~16.04.11                               amd64        GNU C preprocessor
ii  g++-5                                        5.4.0-6ubuntu1~16.04.11                               amd64        GNU C++ compiler
ii  gcc-5                                        5.4.0-6ubuntu1~16.04.11                               amd64        GNU C compiler
ii  gcc-5-base:amd64                             5.4.0-6ubuntu1~16.04.11                               amd64        GCC, the GNU Compiler Collection (base package)
ii  gcc-5-base:i386                              5.4.0-6ubuntu1~16.04.11                               i386         GCC, the GNU Compiler Collection (base package)
ii  gfortran-5                                   5.4.0-6ubuntu1~16.04.11                               amd64        GNU Fortran compiler
ii  gnome-software                               3.20.5-0ubuntu0.16.04.11                              amd64        Software Center for GNOME
ii  gnome-software-common                        3.20.5-0ubuntu0.16.04.11                              all          Software Center for GNOME (common files)
ii  libasan2:amd64                               5.4.0-6ubuntu1~16.04.11                               amd64        AddressSanitizer -- a fast memory error detector
ii  libatomic1:amd64                             5.4.0-6ubuntu1~16.04.11                               amd64        support library providing __atomic built-in functions
ii  libcc1-0:amd64                               5.4.0-6ubuntu1~16.04.11                               amd64        GCC cc1 plugin for GDB
ii  libcilkrts5:amd64                            5.4.0-6ubuntu1~16.04.11                               amd64        Intel Cilk Plus language extensions (runtime)
ii  libgcc-5-dev:amd64                           5.4.0-6ubuntu1~16.04.11                               amd64        GCC support library (development files)
ii  libgd3:amd64                                 2.1.1-4ubuntu0.16.04.11                               amd64        GD Graphics Library
ii  libgd3:i386                                  2.1.1-4ubuntu0.16.04.11                               i386         GD Graphics Library
ii  libgfortran-5-dev:amd64                      5.4.0-6ubuntu1~16.04.11                               amd64        Runtime library for GNU Fortran applications (development files)
ii  libgfortran3:amd64                           5.4.0-6ubuntu1~16.04.11                               amd64        Runtime library for GNU Fortran applications
ii  libgomp1:amd64                               5.4.0-6ubuntu1~16.04.11                               amd64        GCC OpenMP (GOMP) support library
ii  libitm1:amd64                                5.4.0-6ubuntu1~16.04.11                               amd64        GNU Transactional Memory Library
ii  liblsan0:amd64                               5.4.0-6ubuntu1~16.04.11                               amd64        LeakSanitizer -- a memory leak detector (runtime)
ii  libmpx0:amd64                                5.4.0-6ubuntu1~16.04.11                               amd64        Intel memory protection extensions (runtime)
ii  libquadmath0:amd64                           5.4.0-6ubuntu1~16.04.11                               amd64        GCC Quad-Precision Math Library
ii  libstdc++-5-dev:amd64                        5.4.0-6ubuntu1~16.04.11                               amd64        GNU Standard C++ Library v3 (development files)
ii  libstdc++6:amd64                             5.4.0-6ubuntu1~16.04.11                               amd64        GNU Standard C++ Library v3
ii  libstdc++6:i386                              5.4.0-6ubuntu1~16.04.11                               i386         GNU Standard C++ Library v3
ii  libtsan0:amd64                               5.4.0-6ubuntu1~16.04.11                               amd64        ThreadSanitizer -- a Valgrind-based detector of data races (runtime)
ii  libubsan0:amd64                              5.4.0-6ubuntu1~16.04.11                               amd64        UBSan -- undefined behaviour sanitizer (runtime)

I have tried to install the specific version:
$ sudo apt install gcc-5=5.4.0-6ubuntu1~16.04.10

Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 gcc-5 : Depends: cpp-5 (= 5.4.0-6ubuntu1~16.04.10) but 5.4.0-6ubuntu1~16.04.11 is to be installed
         Depends: gcc-5-base (= 5.4.0-6ubuntu1~16.04.10) but 5.4.0-6ubuntu1~16.04.11 is to be installed
         Depends: libgcc-5-dev (= 5.4.0-6ubuntu1~16.04.10) but 5.4.0-6ubuntu1~16.04.11 is to be installed
E: Unable to correct problems, you have held broken packages.

It seems that my system has multiple options for this package.
$ sudo apt-cache policy cpp-5:amd64

cpp-5:
  Installed: 5.4.0-6ubuntu1~16.04.11
  Candidate: 5.4.0-6ubuntu1~16.04.11
  Version table:
 *** 5.4.0-6ubuntu1~16.04.11 100
        100 /var/lib/dpkg/status
     5.4.0-6ubuntu1~16.04.10 500
        500 http://security.ubuntu.com/ubuntu xenial-security/main amd64 Packages
     5.3.1-14ubuntu2 500
        500 http://br.archive.ubuntu.com/ubuntu xenial/main amd64 Packages

To be a little bit more clear, I wanna use the gcc compatible with ubuntu 16.04.10 and not 16.04.11.
Thanks in advance!

A: Ubuntu 16.04.11 doesn't exist, Xenial minor versions only go to 16.04.6.
5.4.0-6ubuntu1~16.04.11 is some horrible version "number" for gcc-5. I assume it is supposed to indicate 16.04 specific patches and still sort sanely for version comparison.
Update your packages if necessary and use them. Stable distros like Ubuntu try not to ship breaking changes as updates, that is for major version upgrades.


text:
Q: schedule selector in didFinishLaunchingWithOptions I have encountered a problem in my app that didFinishLaunchingWithOptions was taking too long to finish, what could possibly result in the app being terminated.
I have also been getting crash reports from itunes connect that seem to indicate that the app takes too long to launch.
This might be caused by the fact that I was loading some textures synchronously during didFinishLaunchingWithOptions, a process that takes more than a second.
In an attempt to solve it, I call the method that loads the data after delay, in the following way:
[self performSelector:@selector(loadTextures) withObject:nil afterDelay:0.5f];

The way I understand - though I might be wrong - the scheduled task will not be carried out on a different thread, and therefore will only be processed after didFinishLaunchingWithOptions is done.
My question is:
Are there any best practice solutions for such a problem? Is the solution I suggested works as I intended?
Also, is apple's watchdog known to check apps for responsiveness even after the launch phase in cases such as this?

A: We had a similar problem in our ebook reader application where we copy ebooks (of several MBs) from bundle to the documents directory.Scheduling selector for copying the books has been the best solution so far.The same solution works fine in your case as well.I am not sure about apple's watch dog but our application is live on the app store and running since more then one year with this solution incorporated.


text:
Q: How do I use keyboard shortcuts to enter a value into a cell that has a list data validation entry? So I used data validation to only allow an user to enter values from a list. How do I select something from the list without using the mouse?
For example, here's what I made:

Clicking on the little arrow beside the active cell will give me a drop-down using which I can select an appropriate value. How do I do this with just my keyboard?

A: 1) Navigate to the cell
2) Press <ALT><Arrow down>
3) Navigate to the menu entry with the up/down arrows
4) Press <Enter> to accept the selected entry


text:
Q: Angularjs with ng-repeat to print data separate by , I have data in json format, which I would like to display the item on the different data cell based on its first element. If more than one element in the cell, multiple item should be shown separable by "," or .
For example, if my json is:
data = {{"Mon","012"},{"Tue","123"},{"Mon","112"},{"Mon","032"},...}

    012 , 112 , 032
    id="TUe"> 123

or

012

 112

032

123

I was investigating the doc for ng-repeat with $odd and $index etc., but could not find the right way to get my result.

A: Your JSON is invalid, so I reformated it a bit to answer the format question.
CSS should do the formatting. You can define a delimiter if there are multiple  elements.
td span+span:before {
  content: ", ";
}

angular.module('app', [])
  .run(function($rootScope) {
    $rootScope.dataOrdered = [{
      key: "Mon",
      values: ["012", "112", "032"]
    }, {
      key: "Tue",
      values: ["123"]
    }];

  });
table,
th,
td {
  border: 1px solid black;
  padding: 2px;
}
td span+span:before {
  content: ", ";
}


text:
Q: How to set an array containing data from firestore query result in my code? I successfully get the Orders with order_id and orders_data from firestore database and show in console, but I am unable to set the state of orders variable, I'm noob here.
I tried the commented part but it doesn't work to setOrders. Please give any solution and do tell why my commented part isn't setting data.
Orders.js

import React, { useEffect, useState } from 'react';
import './Orders.css';
import { db } from './firebase';
import { useStateValue } from './StateProvider';
import { doc, query, getDocs, orderBy, collection, getDoc, onSnapshot } from "firebase/firestore";
import Order from './Order';

function Orders() {
  const [{ basket, user }, dispatch] = useStateValue();
  const [orders, setOrders] = useState([]); //Initial value will be empty array

  useEffect(() =>{
    if(user){
      async function fetchData() {
        // You can await here
        const ordersRef = collection(db,"users",user?.uid, "orders");
        const q = query(ordersRef, orderBy("created", "desc"));
        const querySnapshot = await getDocs(q);
        querySnapshot.forEach((doc) => {
          console.log(doc.id, " => ", doc.data());
        });

        //console.log("Got Orders>>",orders)
        //   setOrders(querySnapshot.forEach((doc =>({
        //     id: doc.id,
        //     data: doc.data()
        //   }))));
        //...
     }
      fetchData();
     }else{
       setOrders([]);
     }
  }, []); //You have to have [] here. This makes it run only once.

  return (

Your Orders

          {orders?.map(order =>{
            <Order order={order}/>
          })}

  )
}

export default Orders

Order.js

import React from 'react';
import CheckoutProduct from './CheckoutProduct';
import './Order.css';
import moment from 'moment';

function Order({order}) {
  return (

Order

{moment.unix(order.data.created).format("MMMM Do YYYY, h:mma")}

            {order.id}

        {order.data.basket?.map(item =>{
            <CheckoutProduct
            id = {item.id}
            title = {item.title}
            image = {item.image}
            price = {item.price}
            rating = {item.rating}
            />
        })}

  )
}

export default Order

A: I see.
You should use map function instead of foreach
setOrders(querySnapshot.map((doc =>({
    id: doc.id,
    data: doc.data()
}))));

A: data() is a queurySnapshot Object and it does not have a map fucntion to use, so we have to do it like this.

setOrders(querySnapshot.docs.map(doc =>({
    id: doc.id,
    data: doc.data()
})));


text:
Q: react-native netinfo behaving strange in ios System Environment:
OS: Windows 10 OS 64 bit
CPU: Intel core i7-9700k @ 3.60GHz
Memory: 550.87 MB / 16.00 GB
Platforms:
Issue related to both Android and IOS
Versions :
Android: 9
iOS: 13.1.3
react-native-netinfo: 5.0.0
react-native: 0.61.4
expo: 36.0.0
Description :
In my expo project i need details like ssid , ipAddress of WiFi to which current phone is connected.
i followed below procedure as follows :
first step i did npm install --save @react-native-community/netinfo
second step i imported NetInfo from "@react-native-community/netinfo";
third step i wrote below code
NetInfo.fetch().then(state => {
                console.log("Connection type", state.type);
                console.log("Isconnected?", state.isConnected);
                console.log("Details ", state.detail);
                });

following is the output i can see on my terminal
Output in-case of Android
Connection type wifi
Is connected? true
Detail? Object {
    "ipAddress": "192.168.0.171",
    "isConnectionExpensive": false,
    "ssid": "DM",
    "subnet": "255.255.255.0",
}

Output in-case of iOS.
Is connected? true
Detail? Object {
    "ipAddress": "192.168.0.171",
    "isConnectionExpensive": false,
    "ssid": null,
    "subnet": "255.255.255.0",
}

So if you see in output Details i get all the detalis like ssid, subnet for Android but incase of iOS ssid is always null even after giving location permission. As i am newbie to react native i don't understand where did i do mistake because of which i am not getting wiFi ssid and ipaddress. Please give me a solution for the above mentioned problem. I dont want to eject from Expo.


text:
Q: Chromium browser: how to move BubbleDialogDelegateView widget without flickering? I have a popup dialog based on views::BubbleDialogDelegateView ( similar to ProfileChooserView ).
class WebViewPopup : public views::BubbleDialogDelegateView,
                       public ExtensionViewViews::Container,
                       public content::NotificationObserver,
                       public TabStripModelObserver,
                       public content::DevToolsAgentHostObserver,
                       public zoom::ZoomObserver,
                       public FullscreenObserver
{
....
static void ShowPopup(views::Button* anchor_button,
                        Browser* browser) {
  auto* popup =
      new WebViewPopup(anchor_button, browser);
  views::BubbleDialogDelegateView::CreateBubble(popup);
}
....
}

And I need to move it from left to right (animate) when window appears. Similar to Opera easy setup bar.
Is there a cross-platform way to move or animate a widget without flickering?
If I imitate animation using timer and change widget size step-by-step, it flickers
void WebViewPopup::SetPaneWidth(int w)
{
  views::Widget* this_widget = this->GetWidget();
  gfx::Rect bounds(); //calculate new widget size
  this_widget->SetBounds(bounds); // flickers!
}

I've found window animation in chromium\src\ui\wm\core\window_animations.cc and it works ok, but it uses Aura and only available on Windows.
So, main question again: Is there a cross-platform way to move or animate a widget without flickering?


text:
Q: How to get HDL Designer Series library contents in tcl script? I can get a list of the libraries in an HDL Designer Series project with the following command on the tcl console:
library names

Is there a similar command to get a list of the library contents?  Not the actual files, but the design units (e.g. entity or package), just like what is displayed in the gui.

A: There isn't a direct command like $library names.  There are library and file object properties that have the design unit names.  The object structures are listed in the HDL Designer Series Command Reference.
This gives a list of the files in a library (file objects, not the actual files):
$lib files

So looping through those to get the declarations of each file:
$file declarations

And then looping through those and getting the name of each gives the design units.
$declaration configure name

There's an example of how to loop through them in the HDL Designer Series Tcl Reference Manual.


text:
Q: More ways of sending Broadcast and receivening In my application I am using a simply way to send broadcast and receiver them.
Intent in = new Intent("UPDATE_SOMETHING");
sendBroadcast(in);

And in my receiver I just check if(intent.getAction().equals("UPDATE_SOMETHING")), of course in AndroidManifest in intent-filter i put  so that the application know which receiver should receive it. This method works fine for me, and than i find out that this can be done i other way.
Intent in = new Intent(getApplicationContext(), Receiver.class);
in.setAction("UPDATE_SOMETHING");
sendBroadcast(in);

In this example i don't need to put the action in AndroidManifest, and i can check it in the receiver in the same way as above (if(intent.get...))
Also there is a third way
Intent in = new Intent();
in.setAction("UPDATE_SOMETHING");
sendBroadcast(in);

And puting a action in AndroidManifest...
My question is, which of this three ways is the best to use?, and are there any differences between this ways? (except in writing the code) :)

A: First and third method are the same. The only difference how you pass actions to intent (through constructor or method). Both of these methods will send broadcast to all registered broadcast receivers who listens for UPDATE_SOMETHING action.
In second method, you send broadcast explicitly to your Receiver class. So no other broadcast receiver will see/receive it.


text:
Q: what would be my rails URL? i have a rails app located at [home]/rails_apps/final/final2 on my Bluehosts server. I run script/server here with ssh/shell..
actionen@actionengineers.com [~/rails_apps/final/final2]# script/server -e production
=> Booting Mongrel
=> Rails 2.3.4 application starting on http://0.0.0.0:3000
/home/actionen/rails_apps/final/final2/app/controllers/items_controller.rb:87: warning: parenthesize argument(s) for future version
/home/actionen/rails_apps/final/final2/app/controllers/shelves_controller.rb:84: warning: parenthesize argument(s) for future version
=> Call with -d to detach
=> Ctrl-C to shutdown server

I am not able to see my site at http://actionengineers.com:3000. what is my url?!

A: There is nothing wrong with how you've started Mongrel. 0.0.0.0 is the wildcard address; it means that the server will listen on all available interfaces, even ones that are brought up after the server starts.
actionengineers.com resolves to 69.89.27.235. Is this the IP address for your server? Run ifconfig -a and ensure the IP matches.
If it does, you probably have a firewall issue. iptables is the most common way to set up a firewall on Linux, though it is by no means the only way. Run iptables -L INPUT as root to see the existing rules for incoming packets. In particular, look at the first line for the default policy. If it's DROP, then any packets that don't match a rule are dropped.

A: If the firewall passes this port outside, your url should be http://:3000 or http://:3000
Do not forget open 3000 port in your firewall


text:
Q: Set default contenttype on list, from JSOM I got some JavaScript that is creating some Lists and Content Types. I am able to set the Content Types on the Lists, however I am not sure how I am suppose to set it as the Default Content Type. So I am pretty much just looking for code snippet that illustrates this.

A: Default Content Type is the First Content Type in the list of content types.
You can use set_uniqueContentTypeOrder for changing the order.
var context = SP.ClientContext.get_current();
var contentTypes = context.get_web().get_lists().getByTitle('ListTitle').get_contentTypes();
var rootFolder = context.get_web().get_lists().getByTitle('ListTitle').get_rootFolder();
context.load(contentTypes);
context.load(rootFolder, 'ContentTypeOrder', 'UniqueContentTypeOrder');
context.executeQueryAsync(onSuccess, onFailed);

function onSuccess(){
    contentTypes = context.get_web().get_lists().getByTitle(current.ListTitle).get_contentTypes();
    var ctOrder = new Array();
    var enum = contentTypes.getEnumerator();
    while (enum.moveNext()) {
        //Populate ctOrder in your new order by making default content type as the first item
    }
    rootFolder.set_uniqueContentTypeOrder(ctOrder);
    rootFolder.update();
    context.executeQueryAsync(success, failed);
};

Source - https://cann0nf0dder.wordpress.com/2014/02/26/setting-default-content-types-for-listlibraries-using-javascript/


text:
Q: WordPress PHP Fatal error: Out of memory - BUT only when listing one of my CPTs in admin We have a WordPress site in which I have create a CPT called Students (along with a few other CPTs), that lists student details for a language school. This data was imported from another site via a csv file and included 4296 student records each with 28 custom fields on top of the standard fields (post_type, post_status, post_date, etc).
I use CMB2 (not the plugin version) to create the 28 custom fields and there are an extra 27 custom fields for extra details that will be used in the future. Most for these fields are simple text, select or radio fields. There are 18 wysiwyg fields but these are not populated yet.
I can view the records in the front-end as a listing and a single entry. I can view a single entry in the back-end too, but when I view the listing page (ie [domain]/wp-admin/edit.php?post_type=students) I get the error:

PHP Fatal error:  Out of memory (allocated 250085376) (tried to
  allocate 71 bytes) in
  /home/sites/riversdown.com/public_html/wp-includes/wp-db.php on line
  [various line numbers here - but mainly 2204 or 2224]

I started to delete these student entries in bulk and as their numbers reduced the error changed to:

PHP Fatal error:  Out of memory (allocated 254541824) (tried to
  allocate 71 bytes) in
  /home/sites/riversdown.com/public_html/wp-includes/meta.php on
  line [829 or 826]

by the time I got down to 2709 student records the error went away and I was able to see the listing page in the back-end.
in php.ini I have:
max_input_time = 200
max_input_vars = 10000
memory_limit = 512M

in wp-config.php I have:
define( 'WP_MEMORY_LIMIT', '256M' );
define( 'WP_MAX_MEMORY_LIMIT', '512M' );

Are there too many posts? To many custom fields? Something else?


text:
Q: 401 Error accessing Rest API passing get_cookie I am accessing an API which expects me to make a POST call to their Login endpoint and then make subsequent calls to get data. The call I make to their login endpoint works. But the subsequent call to get data throws a 401 error. This is the error I get
org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:615)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:573)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:544)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:465)
    at com.wsc.eventconsumer.phonex.api.InventoryServiceImpl.getProducts(InventoryServiceImpl.java:70)
Now this works fine when I use Postman and the Restlet client. I noticed that in Restlet client the GET call to the API passes a cookie that was set by the API in the login call. I tried passing the response headers from the login call in the GET request. But I still get a 401. I am using the standard resttemplate configuration.
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

HttpEntity<Credentials> entity = new HttpEntity<Credentials>(credentials, headers);
ResponseEntity<String> response = restTemplate.exchange(loginEndpoint, HttpMethod.POST, entity, String.class);
HttpHeaders rHeaders = response.getHeaders();

HttpEntity<String> request = new HttpEntity<String>(rHeaders);
ResponseEntity<Product[]> response2 = restTemplate.exchange(productEndpoint,
                HttpMethod.GET, request, Product[].class);


text:
Q: htaccess 307 redirect, This file should be served over HTTPS I'm trying to redirect a folder to another by htaccess file. That's working, but I'm loosing the https and got the error "the file was redirected through an insecure connection. This file should be served over HTTPS.".
This is my code :
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]
  RewriteRule ^old_folder/(.*)$ /new_folder/$1 [L,QSA,R=301]
</IfModule>

I also saw in network browser a 307 redirection even if I'm trying to have a 301 redirection.
Could anyone help me ?


text:
Q: Can't run GPU_FFT in an infinite loop I am currently trying to take FFT using GPU_FFT libraries provided with Pi. I've successfully taken FFT of the data. However, whenever I try this in a while(1) loop, somehow it takes FFT 1023 times and stops at 1024th. I've read about someone who faced with exact same issue on Raspberry Pi official forum, but couldn't figure out how to fix mine.
The code below is function to compute FFT
    void computeFFT(float *Input,float *Output){

    struct GPU_FFT_COMPLEX *base;
    struct GPU_FFT *fft;
    int i;

    int ret = gpu_fft_prepare(mb,log2_N,GPU_FFT_FWD,1,&fft);
    base = fft->in;

    for(i=0;i<N;i++)
        base[i].re =  Input[i]; base[i].im =0.0;

    gpu_fft_execute(fft);
    base = fft->out;

    for(i=0;i<N;i++)
        Output[i]= base[i].re;

    gpu_fft_release(fft);
}

and this is my while(1) loop
    while (1){
    if (mb != 0)
        mb = mbox_open();

    adc1Value = a2d(adc1Channel);
    voltage1 = ((2.5/4096) * adc1Value);
    QueueGet(Queue);
    QueuePut(voltage1);

    OutData = computeFFT(Queue,OutData);
    printf("%f\n",OutData[0]); // Printing out signal value on 0Hz
}
mbox_close(mb);
free(OutData);
return 0;

I do believe problem is related to where I use mbox_open and close functions.
Things that I tried

*

*Changing Queue into new array with random number generated with rand().

*Changing location of mbox functions as suggested.

*Disabling a2d function

*Changing FFT length to 512, 2048, 4096.

Yet none of them was the solution.


text:
Q: Sqoop import having SQL query with where clause sqoop import --connect jdbc:teradata://192.168.xx.xx/DBS_PORT=1025,DATABASE=ds_tbl_db
--driver com.teradata.jdbc.TeraDriver
--username dbc
--password dbc
--query 'select * from reason where id>20'
--hive-import
--hive-table reason_hive
--target-dir <hdfs-location>
-m 1

I got the error:

Query [select * from reason where id>20] must contain '$CONDITIONS' in WHERE clause.

I know there must be a where clause in query for Sqoop.
So, for queries like
select * from reason
I modify it to:
select * from reason WHERE $CONDITIONS
What to do for queries having where clause?

A: Sqoop requires to access metadata of table for example column type information. Placeholder $CONDITIONS is by default set to '1 = 0' to ensure
that sqoop receives only type information. So, after executing sqoop command you will see first query that gets fired is
with default $CONDITIONS. Later on, it is substituted by different values defining different ranges based on number of mappers (-m) or --split-by column or --boundary-query so that entire data set can be divided into different data slices or chunks and chunks can be imported in parallel with as much as concurrency available. Sqoop will automatically substitute this placeholder with the generated conditions specifying which slice of data should be transferred by each individual task
For example, consider sample_data table with columns name, id and salary.
You want to fetch records with salary > 1k.
 sqoop import \
    --connect "jdbc:mysql://quickstart.cloudera:3306/retail_db" \
    --username retail_dba --password cloudera \
    --query 'select * from sample_data where $CONDITIONS AND salary > 1000' \
    --split-by salary \
    --target-dir hdfs://quickstart.cloudera/user/cloudera/sqoop_new

Following is first query which returns empty set.
SqlManager: Executing SQL statement: select * from sample_data where  (1 = 0)  AND salary > 1000

Then next query is to get min and max of range.
INFO db.DataDrivenDBInputFormat: BoundingValsQuery: SELECT MIN(salary), MAX(salary) FROM (select * from sample_data where  (1 = 1)  AND salary > 1000) AS t1;

A: You have to add AND \$CONDITIONS
--query "select * from reason where id>20  AND \$CONDITIONS"
Please refer Sqoop documentation .

A: You can use Where Clause
--where "order_status = 'CLOSED'"
https://sqoop.apache.org/docs/1.4.2/SqoopUserGuide.html

A: You can set as like below

*

*If database is oracle then select * from (query) where $CONDITIONS else select * from (query) as T where $CONDITIONS
Please let me know if in case any issue.

A: I am working in cloudera with querying list of tables in Mysql.
I got results with below listed query:
sqoop import --connect jdbc:mysql://127.0.0.1/Mydatabase
    --username root --password cloudera
    --query 'select * from employee where $CONDITIONS AND Sal<250000'
    --split-by Sal --target-dir=user/cloudera/myfirstdata2 -m 1

A: when you are using free form query, just make sure you are place '\' before $CONDITIONS and you are good to do. Here is an example I have tried on Cloudera Quickstart VM and it worked fine.
sqoop import --connect jdbc:mysql://quickstart.cloudera/retail_db --username retail_dba --password cloudera --query "select customers.customer_fname, customers.customer_lname, orders.order_id, orders.order_date from customers join orders on (customers.customer_id = orders.order_customer_id) WHERE \$CONDITIONS" --as-parquetfile --split-by "orders.order_customer_id" --target-dir "/user/cloudera/problem2/data/cusotmers"
Please refer to this link for detailed documentation:
https://sqoop.apache.org/docs/1.4.7/SqoopUserGuide.html#_free_form_query_imports


text:
Q: Angular 2, interact with a bootstrap component How can I use inside an Angular 2  page a getboostrap component that need some javascript initializations and dom accesses for interacts?
For Example:
http://seiyria.com/bootstrap-slider/


text:
Q: How to manage Parent-Child Hierarchy in Git I want to get the idea on how to manage the Parent-Child Hierarchy in git.
Let's say I have a master branch where code will be updated once a week. I have made a new branch say MainDev for development.
When the team works, they create branches on their local like NewBranch.
I have 2 questions:

*

*How can I push the newly created branch only to MainDev so that, MainDev and all the pull requests I create, should be merged only on MainDev?

*Is there any way that BitBucket automatically merges the MainDev branch to master and updates master and MainDev once a week?

A: No automatic merge tools that I know of with BitBucket, but regarding PRs you may want to change your default branch through the repo's admin page.


text:
Q: If I buy a vehicle online, and I don't have a garage, where does it go? I really like this one specific bike, which is worth only 15k.  But, I don't have a garage.  If I purchase the bike online, where will the bike go? I don't have a house, either.

A: You can't buy a car if you do not own a garage to store it. The cheapest garage is a 2 car garage titled "Unit 124 Popular St." that will cost you $25000.
Just like in the real world, you can't just go leaving your cars all over town!


text:
Q: How to find latest version of a document? I have two tables as tblDocument, tblDocVersions connected using primary key docid as follows:
tblDocument:  docid | title
tblVersions: id | docid | verion | datecreated | status
tblVersions could have data as
id  + docid + version
----+-------+--------+
1   | 1     | 1
----+-------+---------
2   | 1     | 2
----+-------+---------
3   | 1     | 3
----+-------+---------
4   | 2     | 1
----+-------+---------
5   | 3     | 1
----+-------+---------
6   | 3     | 2
----+-------+---------

Now I need to select each individual document with it latest version...
NOTE: I need to select the row from Versions that correcpond to the latest version number.

A: select max(version), tab1.docid from tblDocument as tab1
inner join tblVersions as tab2 on tab1.docid = tab2.docid
group by tab1.docid

EDIT
Not sure but this will work for you
select tab1.* from tblDocument as tab1
inner join tblVersions as tab2 on tab1.docid = tab2.docid
inner join

  (select max(version) as ver,tab1.docid from tblDocument group by tab1.docid )  d
on d.docid = tab1.docid and  d.ver = tab1.version


text:
Q: Unable to open BCP host data-file error Having problem using BCP via xp_cmdshell.
I exported the table data to a file as .dat but when I try to import the file to a new table, I am getting the below error. The SQL Server service and the account that I am using has full access on that drive. I am not sure why I am still having issues.

Error = [Microsoft][SQL Server Native Client 10.0]  Unable to open BCP
  host data-file.

Here are the scripts that I am running.
exec master..xp_cmdshell 'BCP database.dbo.tabel OUT d:\tabledata.dat -T -c'
exec master..xp_cmdshell 'BCP database.dbo.tabelnew IN d:\tabledata.dat -T -c'

A: I had the same - somehow a windows or SQL Server update changed something and a previously successful build started failing.
In my case it was access permissions to the folder containing the dat files that was failing.
I could run the bcp from the command line and it worked but it failed from SQL Server.
The SQL Service needs access to the folder, basically.
To test this, try running
EXEC master..xp_cmdshell 'DIR <your-dat-folder>'

and if that fails check your access permissions (and grant as needed).


text:
Q: Aggregate histogram data I have the histogram for a number of properties of different unique models of some 'thing'.
When I do an experiment I find multiple of those unique models. I need to find the histogram of each property considering the entire sample set of the experiment.
Example:
With a data frame df like below, with a bunch of id's and for each id there are a bunch of properties named prop1, prop2 and so on.
set.seed(1)
df <- data.frame(id = sample(1:5, 6, replace = TRUE),
                     prop1 = rep(c("A", "B"), 3),
                     prop2 = sample(c(TRUE, FALSE), 6, replace = TRUE),
                     prop3=sample(3:6, 6, replace = TRUE))

> df
  id prop1 prop2 prop3
1  2     A FALSE     4
2  2     B  TRUE     4
3  3     A FALSE     6
4  1     B  TRUE     5
5  3     A FALSE     3
6  3     B FALSE     4

For eqch unique id a histogram is computed for each property and the result is stored in a list l1 which holds the histogram for each property on a per id basis.
# Create histogram for each property
df[-1] <- lapply(df[-1], as.factor)
fun1 <- function(df, n){as.data.frame(t(sapply(split(df, df$id), function(i)
                                                         prop.table(table(i[,n])))))}
l1 <- sapply(2:ncol(df), function(i)fun1(df, i))
names(l1) <- names(df[-1])

> l1
$prop1
          A         B
1 0.0000000 1.0000000
2 0.5000000 0.5000000
3 0.6666667 0.3333333

$prop2
  FALSE TRUE
1   0.0  1.0
2   0.5  0.5
3   1.0  0.0

$prop3
          3         4 5         6
1 0.0000000 0.0000000 1 0.0000000
2 0.0000000 1.0000000 0 0.0000000
3 0.3333333 0.3333333 0 0.3333333

Now below I have a new set of ids from a new experiment, with repetitions. I need to compute the histogram for each property across the set of id's using the reference data from l1.
Some id's may not be present; some id's not present in the original df and l1 may be present in ids- example 4 in ids is not present in l1 - however these can be excluded from the histogram computation , but captured as a dataframe with excluded id and count for each id excluded.
ids <- sample(1:4, 7, replace = TRUE)
> ids
 [1] 2 3 1 3 3 2 4

Update:
Expected output - I'm showing it as a list-  any other data structure which is more appropriate could be used.
> l2
$prop1
      A     B
1 0.500 0.500

$prop2
    FALSE    TRUE
1   0.667  0.333

$prop3
      3     4     5     6
1 0.167 0.500 0.167 0.167

base R solution preferred.
Update: Clarifying how the output is computed.
Counts in ids - one 1, two 2, three 3 and one 4. Since we do not have any data for 4 the useful ids are 1, 2 and 3 with total count of 6 ids between them.
For prop1, the aggregated histogram for ids can be computed as follows
A = (1*0.0 + 2*0.5  + 3*0.6667)/6 = 0.5
B = (1*1.0 + 2*0.5  + 3*0.3333)/6 = 0.5

A: I have a solution for you, that does involve other packages (dplyr and tidyr). Since I am reshaping (melting) the data that you generated in a list. After that I spread the data into a nice data.frame. Offcourse you could also use the normalized version of the data. (df) within function(x).
library(dplyr)
library(tidyr)

res <- do.call(rbind,
               lapply(ids, function(id) do.call(cbind,
                                                lapply(names(l1),function(x) {
  df <- l1[[x]] %>% rownames_to_column("id")
  df <- df[df$id == id,] %>% gather(key, value, -id)
  if(nrow(df) > 0){
    df[,'key'] <- paste0(x,'.',df[,'key'])
    df <- df %>% spread(key,value)
  }
  df
}))
)
)

result:
> res
  id   prop1.A   prop1.B id prop2.FALSE prop2.TRUE id   prop3.4   prop3.5 prop3.6
1  2 0.6666667 0.3333333  2   0.6666667  0.3333333  2 0.3333333 0.6666667       0
2  3 1.0000000 0.0000000  3   1.0000000  0.0000000  3 0.0000000 0.0000000       1
3  2 0.6666667 0.3333333  2   0.6666667  0.3333333  2 0.3333333 0.6666667       0
4  2 0.6666667 0.3333333  2   0.6666667  0.3333333  2 0.3333333 0.6666667       0
5  2 0.6666667 0.3333333  2   0.6666667  0.3333333  2 0.3333333 0.6666667       0

You can also achieve this without your prop.table function and only dplyr which is a much neater solution.
propsum <- df %>% gather(key,value,-id) %>% mutate(n = 1) %>%
  complete(nesting(key,value),id, fill=list(n = 0)) %>%
  group_by(id, key, value) %>%
  summarise(n = sum(n)) %>%
  group_by(id, key) %>%
  mutate(p = n/sum(n)
         ,col = paste0(key,'.',value)) %>%
  ungroup() %>%
  select(id, col, p) %>%
  spread(col,p)

propsum[match(ids,propsum$id),]

result:
# A tibble: 10 × 8
      id   prop1.A   prop1.B prop2.FALSE prop2.TRUE   prop3.4   prop3.5 prop3.6
   <int>     <dbl>     <dbl>       <dbl>      <dbl>     <dbl>     <dbl>   <dbl>
1      2 0.6666667 0.3333333   0.6666667  0.3333333 0.3333333 0.6666667       0
2     NA        NA        NA          NA         NA        NA        NA      NA
3     NA        NA        NA          NA         NA        NA        NA      NA
4     NA        NA        NA          NA         NA        NA        NA      NA
5      3 1.0000000 0.0000000   1.0000000  0.0000000 0.0000000 0.0000000       1
6     NA        NA        NA          NA         NA        NA        NA      NA
7      2 0.6666667 0.3333333   0.6666667  0.3333333 0.3333333 0.6666667       0
8      2 0.6666667 0.3333333   0.6666667  0.3333333 0.3333333 0.6666667       0
9     NA        NA        NA          NA         NA        NA        NA      NA
10     2 0.6666667 0.3333333   0.6666667  0.3333333 0.3333333 0.6666667       0

Since you added the expected result, I am not sure in what way this result was generated. I give you two options:
option 1: using the source data to multiply according to the given ids.
#option 1
data.frame(id = ids) %>% inner_join(df, by='id') %>%
  gather(key, value, -id) %>%
  group_by(key, value) %>%
  mutate(n = 1) %>%
  complete(nesting(key,value),id, fill=list(n = 0)) %>%
  summarise(n = sum(n)) %>%
  group_by(key) %>%
  mutate(p = n/sum(n))

which results in:
    key value     n          p
  <chr> <chr> <dbl>      <dbl>
1 prop1     A     9 0.69230769
2 prop1     B     4 0.30769231
3 prop2 FALSE     9 0.69230769
4 prop2  TRUE     4 0.30769231
5 prop3     4     4 0.30769231
6 prop3     5     8 0.61538462
7 prop3     6     1 0.07692308

or option 2:
Using the aggregated data and calculate the mean proportion.
#option 2
df %>% gather(key,value,-id) %>% mutate(n = 1) %>%
  complete(nesting(key,value),id, fill=list(n = 0)) %>%
  group_by(id, key, value) %>%
  summarise(n = sum(n)) %>%
  group_by(id, key) %>%
  mutate(p = n/sum(n)) %>%
  inner_join(data.frame(id = ids), by='id') %>%
  group_by(key, value) %>%
  summarise(p = mean(p))

which results in:
Source: local data frame [7 x 3]
Groups: key [?]

    key value         p
  <chr> <chr>     <dbl>
1 prop1     A 0.7333333
2 prop1     B 0.2666667
3 prop2 FALSE 0.7333333
4 prop2  TRUE 0.2666667
5 prop3     4 0.2666667
6 prop3     5 0.5333333
7 prop3     6 0.2000000


text:
Q: What happened to clojure.xml/emit? Many blogs refer to the clojure.xml/emit (or clojure.contrib.lazy-xml/emit) function, but it seems to be absent from the 1.2 documentation.
Was it deprecated? What has replaced it?
Can it be used to write Clojure-encoded XML (e.g.: {:tag :address :content {:tag :street ...} })?
UPDATE: I looked at the source code for clojure.contrib.lazy-xml/emit (by Chris Houser) and, although it too is not "official", it looks like a more stable solution than clojure.xml/emit.
BTW, I have "discovered" the clojure and clojure-contrib source code as great examples of well-written, idiomatic Clojure (especially the parts written by the masters, Rich Hickey, the two Stuarts, Chris Houser, etc.) I'll need to spend some time studying that code.

A: Strangely enough, clojure.xml/emit still exists when you (use 'clojure.xml) that namespace at the REPL in 1.2.0.
To verify:
user=> (use 'clojure.xml)
user=> (emit (parse "http://feeds.feedburner.com/burningonesblog"))

For full disclosure I discovered this using the useful (ns-map 'user) function
user=> (doc ns-map)
-------------------------
clojure.core/ns-map
([ns])
  Returns a map of all the mappings for the namespace.
nil

Now please note that you are entirely correct about their disappearing from the documentation in 1.2 (clojure.xml and clojure.contrib.lazy-xml) for all but prxml which isn't really what you're looking for.  I can't speak to why that is the case but the reason they no longer show up in the web interface becomes evident upon examining their docstring.
user=> (doc emit)
-------------------------
clojure.xml/emit
([x])
  nil
nil

Now there is this thread over at the Google Group which indicates that use of the emit function is discouraged for 2 reasons.

*

*It is undocumented and thus subject to change without notice.

*It, in general, does not produce valid xml (although I suppose if you know your data is valid it would emit valid xml).

At the end of that thread, Stuart Halloway talks about a project to extend Clojure's XML support.
Of course there's always dipping into the Java pool and using any of the excellent XML tools on the Java end.  It sounds like clojure's XML story is mostly told in parsing at this point.
Hope that helps.

A: If you are running clojure 1.2, there is clojure.contrib.prxml.
If you are running clojure 1.3, the replacement is supposed to be https://github.com/clojure/data.xml
However according to "Where did clojure.contrib go" document on dev.clojure.org, the new lib does not have a repository yet, it may be built and in a maven repo somewhere, but I wasn't able to find it. It is pretty easy to package yourself though.
I had some legacy code that used prxml, so I ended up just fixing up prxml to work with Clojure 1.3, it's on clojars.org
https://clojars.org/weissjeffm/clojure.prxml
It's been working fine for me, but your mileage may vary.


text:
Q: Azure Cognitive Search: add multiple suggesters to a single index I'm trying to add multiple suggesters to an Azure Search index, but receive this error response:

An index cannot have more than one suggester with searchMode='analyzingInfixMatching'

The property on the index is called suggesters and is of type array.
The documentation states:

The only mode currently supported is analyzingInfixMatching

Is the api defined to support future capabilities? Or am I overlooking an option that will enable me to add multiple suggesters?
And to understand why:
I have fields in my index for different languages. I would like a suggester only to include the field for the language the current user has specified.
With the current implementation I can only provide suggestions or autocomplete based on all available languages.

A: I work on the Azure Cognitive Search team. As you guessed, the schema is designed to be adaptive to future changes but at the moment only one suggester is supported - analyzingFixMatching.
If I understand correctly, you want to apply suggestions selectively only on fields specified by user at query time. You can achieve that through searchFields property of suggestions API. Define a suggester with all the fields that can potentially be specified by users and then limit the required ones using the above property.
More details here - https://learn.microsoft.com/rest/api/searchservice/suggestions


text:
Q: HTML5 Application Cache Error Event Detail I have an HTML5 offline app and on occasion users have cache errors which I handle with the event listener and display a generic error message.
In order to help debug these I'd like to also display and log the error details (as seen in the Chrome console), such as a failed get. I have not yet found a way to get the details through Javascript. Is this currently possible?

A: Probably something like this:
var appCache = window.applicationCache;
    function handleCacheError(e){
          console.log(e);
    }
    appCache.addEventListener('error', handleCacheError, false);

And then you should have the error logged to the Chrome console on error.


text:
Q: How to set a Javascript variable from my View using a ViewBag property I would like to set a JavaScript variable in my view (inside a script block) based on the existences of a ViewBag property from the controller... like:
var doAboutTab = @(ViewBag.DoAboutTab != null)

This generates a JavaScript error of:
var doAboutTab = False
'False is not defined'

A: @if(ViewBag.DoAboutTab != null)
{
    var doAboutTab ="something";
}else
{
    var doAboutTab ="something_else";
}

or
var doAboutTab = '@ViewBag.DoAboutTab' !== '';

A: The false keyword is lower case in javascript.
var doAboutTab = @((ViewBag.DoAboutTab != null).ToString().ToLower());

A: ToString() method on bool in C# returns it as "False".Javascript expects "false", you should make it lowercase
var doAboutTab = @((ViewBag.DoAboutTab != null).ToString().ToLower())


text:
Q: How to get a pair (tuple) of integer and float? I'm very much a beginner in Haskell, I'm trying to create a tuple of 2 elements, the first being an integer, and the second being a float. Example:
f1 n = [(x, x) | x <- [1 .. n]]
f2 n = [(x, 1 / x) | x <- [1 .. n]]

> f1 5
[(1,1),(2,2),(3,3),(4,4),(5,5)]

> f2 5
[(1.0,1.0),(2.0,0.5),(3.0,0.3333333333333333),(4.0,0.25),(5.0,0.2)]

f1 behaves as expected, returning a list of tuples of two integers.
f2 returns a list of tuples of two floats, but I was expecting it to return a list of tuples of one integer and one float.
How would I preserve the first tuple element type as integer, such that the output of f2 5 would look like: [(1,1.0),(2,0.5),(3,0.3333333333333333),(4,0.25),(5,0.2)]

A: The reason this happens is that the compiler sees 1/x, which requires not only the result to be floating (Fractional, actually) but also the argument x. This is because the numerical operators in Haskell have all-same-type signatures
(/) :: Fractional a => a -> a -> a

I.e. the compiler infers that x must already have floating type as well, and thus the left element of the tuple ends up as a float.
You can prevent this by dividing not by x itself but instead allowing for conversion:
Prelude> [(x, 1 / fromIntegral x) | x <- [1 .. 9]]
[(1,1.0),(2,0.5),(3,0.3333333333333333),(4,0.25),(5,0.2),(6,0.16666666666666666),(7,0.14285714285714285),(8,0.125),(9,0.1111111111111111)]

Additionally, one thing you should always try when the types don't seem right is to add an explicit signature. This way you can also enforce the computation to be carried out in other, perhaps more suitable types such as Rational:
Prelude> [(x, 1 / fromIntegral x) | x <- [1 .. 9]] :: [(Int, Rational)]
[(1,1 % 1),(2,1 % 2),(3,1 % 3),(4,1 % 4),(5,1 % 5),(6,1 % 6),(7,1 % 7),(8,1 % 8),(9,1 % 9)]

Also, you'll then get a clear-cut compiler error if you try something that doesn't work, instead of silently unexpected results.


text:
Q: Redefine or add Methods to class through decorator. Possible? I have class:
@custom_decorator
class Creature(objects):

    def __init__(self):
        pass

    def rise_hands(self, *args, **kwargs):
        print 'hands rised'

I want to define the custom decorator on the top of this class Creature, so that it will redefine the method rise_hands or adds new methods.
By the way: how can I redefine the values of args or kwargs?
UPDATE:
The gola is as follow:
I wanna implement an app with decorator for django models. Whatever i define it on the model it will log changes by saving old values and new values of curten fields...

A: Don't. Do. This.
You have inheritance to do exactly what you're talking about.
class FancyCreature( Creature ):

    def __init__(self):
        super( FancyCreature, self ).__init___()

    def rise_hands(self, *args, **kwargs):
        print 'hands rised'
        super( FancyCreature, self ).rise_hands( *args, **kwargs )

    def new_method( self ):
        print "new method"

This is the way you "redefine the method rise_hands or adds new methods"

A: Here's how you can modify arguments in kwargs and args. I don't see anything wrong with doing this in principle
>>> def go(func,*args,**kwargs):
...     def g(*args,**kwargs):
...             func(args+(1,),kwargs)
...     return g
...

>>> @go
... def rise_hands(*args, **kwargs):
...     print args
...
>>> rise_hands(1)
((1, 1), {})


text:
Q: JSX vs component class instancing Can somebody explain to me the difference between the following two statements?
let test1 = new CustomComponent();

and
let test2 = <CustomComponent />

The debugger is Chrome gives me:
for test1
CustomComponent {props: undefined, context: undefined, refs: Object, updater: Object, state: Object…}

for test2
Object {$$typeof: Symbol(react.element), key: null, ref: null, props: Object, type: function…}

And how can I get a variable of type of test2, from of variable of the type of test1 ?

A: So.
let test1 = new CustomComponent(); is just a regular javascript thing, same thing happens as calling new thing() any other time. Nothing special.
let test2 = <CustomComponent /> this is an JSX statement, and babel does some magic. It compiles <CustomComponent /> into React.createElement(CustomComponent , null). So, as you can see it is nothing like calling new, it's calling a React function that creates an element, that react knows how to deal with.
Babel has a REPL tool that you can use to see what it's doing to your source code if you ever want to see quickly what's going on under the hood.

A: Case 1: let test1 = new CustomComponent();

In this case you have created an instance of a component. But this is not
a React Instance. Your console output looks like an object, but this is not
a React Component object. It's just like a instance of a class.
Case 2: let test2 = <CustomComponent />

In this case same things have happened. But React takes responsibility, that created instance of it as React Component object and render it.
You have obviously seen the difference between two outputs.
test2 output has type attribute with value of $$typeof: Symbol(react.element) .
But there is no type attribute in test1 output.
I hope your doubts is solved.

A: These are two entirely different things, and I honestly cannot see any use case where you would be using the first case. But you sure ask an interesting question...

Finally, to create elements, use React.createElement(), JSX, or an element factory helper. Don't write elements as plain objects in the real code—just know that they are plain objects under the hood.

new RequirementSection()
This creates an creates an instance of your class and that's pretty much it. You end up with a "dummy" class that doesn't have any of the React logic whatsoever, such as lifecycle methods.
This means that you would have to invoke each class method manually.
Demo:
In this demo we have two components, MyApp and Test. I've made the Test component so that when it's created a local flag variable is set to false, but before mounting, it's set to true.
As you can see, the flag doesn't get updated from the lifecycle and remains falsey.

class MyApp extends React.Component {
  render() {
    let test = new Test();
    return
{test.render()}
;
  }
}

class Test extends React.Component {
  constructor() {
    super();
    this.flag = false;
  }
  componentWillMount() {
    this.flag = true;
  }
  render() {
    return
{this.flag ? "flag is true" : "flag is false"}
;
  }
}

ReactDOM.render(<MyApp />, document.getElementById("myApp"));

<RequirementSection />
As you probably know, this is the most common way of using React. This is JSX and basically translates into:
React.createElement(RequirementSection, null);`

Here, RequirementSection is the class object. What this returns is a ReactElement, which in contrast to the previous example, does include React logic.
Demo:
This demo is similar to the former one, with the difference that we are now using JSX to create a React Element, instead of just instancing a class object.
Indeed, the lifecycle method does run, and the component update the flag to true.

class MyApp extends React.Component {
  render() {
    let test = <Test />;
    return
{test}
;
  }
}

class Test extends React.Component {
  constructor() {
    super();
    this.flag = false;
  }
  componentWillMount() {
    this.flag = true;
  }
  render() {
    return
{this.flag ? "flag is true" : "flag is false"}
;
  }
}

ReactDOM.render(<MyApp />, document.getElementById("myApp"));

Further reading
You may find one of the following links interesting:

*

*React Components, Elements and Instances (official documentation)

*React Without JSX (official documentation)

*React Top-Level API (official documentation)


text:
Q: Android Studio. Image Assets sizes generation I successfully generated a "Launcher Icon" for my project with all expected sizes, now I want to do the same with images to use in ImageViews. I tried all the options in "Image Assets" and none worked.
How can I generate all the different image sizes with Android Studio at once? Just like the launcher icon.
Thanks.

A: If you use AndroidStudio this plugin is perfect
https://plugins.jetbrains.com/plugin/7658?pr=


text:
Q: Displaying Image from PHP MySQL into imageview in Android using Json (Error Parsing data) I've got an error in my code when I was trying to display an image into imageview in android from php mysql..I'm using JSON to parse the image..
So I have a table named movie..
movie
id_movie   |   Tittle   |    link_poster
-------------------------------------------------------------------
 MP01      |    Frozen  |http://10.0.2.2/cinemainfo/image/movie1.jpg

I save the image into a folder named cinemainfo/image in htdocs..
so here is my detail.php code:
$response = array();

$id_movie = $_REQUEST['id_movie'];

$sql="select tittle, link_poster from movie where id_movie = '".$id_movie."'";

$result = mysql_query($sql);

 if (mysql_num_rows($result) > 0)
      {
     $response["detail"] = array();

     while ($row = mysql_fetch_array($result))
        {
        $detail = array();
        $detail["tittle"] = stripslashes($row["tittle"]);
        $detail["link_poster"] = base64_encode($row["link_poster"]);

        array_push($response["detail"], $detail);
        }

     $response["success"] = 1;

     echo json_encode($response);
      }
      else {

      $response["success"] = 0;
      $response["message"] = "No data";

      echo json_encode($response);
        }

and here is my detail.java code:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detail);

    Bundle b = this.getIntent().getExtras();
    kode = b.getString("kode_intent");

    tittle=(TextView)findViewById(R.id.tv_tittle);
    poster=(ImageView)findViewById(R.id.img_poster);

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("id_movie", kode));

    String response = null;

    try {
        response = CustomHttpClient.executeHttpPost("http://10.0.2.2/cinemainfo/detail.php", postParameters);
        String result = response.toString();

            try {
                JSONArray jArray = new JSONArray(result);
                JSONObject json_data=null;
                for(int i=0;i<jArray.length();i++){

                     json_data = jArray.getJSONObject(i);

                     ttl =json_data.getString("tittle");

                     pstr = json_data.getString("link_poster");
                }

                byte[] rawImage = Base64.decode(pstr, Base64.DEFAULT);
                bmp = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);

            }

            catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
                }

            try {
                tittle.setText(ttl);
                poster.setImageBitmap(bmp);
                 }

            catch(Exception e){
                Log.e("log_tag","Error in Display!" + e.toString());;
               }
        }

        catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
        }
}
  }

And here is the log cat:
E/log_tag(338): Error parsing data org.json.JSONException: Value {"success":1,"detail":[{"link_poster":"aHR0cDovLzEwLjAuMi4yL2NpbmVtYWluZm8vaW1hZ2UvZmlsbTEuanBn","tittle":"Frozen"}]} of type org.json.JSONObject cannot be converted to JSONArray

When I running this site : "http://10.0.2.2/cinemainfo/detail.php" I want to make sure that my php code is fine..and it is..
here is the result of my php code :
{"detail":[
    {"tittle":"Frozen",
     "link_poster":"aHR0cDovLzEwLjAuMi4yL2NpbmVtYWluZm8vaW1hZ2UvZmlsbTEuanBn"
     }
          ],"success":1
 }

Does anyone know how to fix my problem? I'm getting stuck to cover this problem ..any help would be very helpful
thank you :)

A: you having the error on json parsing try this code.
 ArrayList<String> title= new ArrayList<String>();
        ArrayList<String> imgurl=new ArrayList<String>();
        String status="";

        try {

 JSONObject result=new JSONObject(jsonouput);
 status    = result.getJSONObject("success");
 JSONArray jArray = new JSONArray(result.getString("detail"));

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

json_data = jArray.getJSONObject(i).toString();

title.add(json_data.getString("tittle"));

imgurl.add(json_data.getString("link_poster"));

          }


text:
Q: detect whether in facebook environment or not I am developing a Facebook page and a website which is going to serve its contents to the Facebook page. I am using Zend Framework.
In order to use only one controller both for the website and the Facebook page, I would like to find some way to determine if the current user is navigating from Facebook or from the website. Thus, to hide some data if from Facebook and show other if from website.
Which is the best way to do this?

A: $_SERVER['HTTP_REFERER'];

If that doesn't answer your question I don't understand what you mean with "navigation from".


text:
Q: TurboC - malloc() in "compact" memory model I am using good old Borland's TurboC compiler for DOS. When I use malloc() on compact memory model and write anything to the allocated memory, program freezes at some point (I suspect malloc() returns pointer to somewhere I shouldn't write). When I do the same on small memory model, it works fine.
I took a look on the allocated memory and the pointer the malloc() returns, using this small piece of code:
#include <stdio.h>

unsigned char *x;
unsigned int i;
unsigned int mds, mss;

#define X(a) x[i+(a)]

int main(void) {

    // show current SS and DS
    asm {
        mov AX, DS
        mov mds, AX
        mov AX, SS
        mov mss, AX
    }
    printf("ds=%04x, ss=%04x\n", mds, mss);

    // allocate memory and show the pointer
    x = (unsigned char*)malloc(128);
    printf("x=%p\n", x);

    // write out contents of the allocated memory
    for (i = 0; i < 128; i += 16)
        printf("%p: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", &x[i], X(0), X(1), X(2), X(3), X(4), X(5), X(6), X(7), X(8), X(9), X(10), X(11), X(12), X(13), X(14), X(15));

    free(x);
    return 0;
}

When I compile this for small memory model, I get:
tcc -ms -IC:\turboc\include -LC:\turboc\lib -etest.exe test.c

ds=02f9, ss=02f9
x=05f2
05f2: 00 00 00 ... 00
0602: 00 00 00 ... 00
...
0662: 00 00 00 ... 00

When I do the same with compact memory model, I get:
tcc -mc -IC:\turboc\include -LC:\turboc\lib -etest.exe test.c

ds=034f, ss=0391
x=0000:0004
0000:0004: 08 00 70 00 ... 08 00 70 00
0000:0014: 54 ff 00 f0 ... a5 fe 00 f0
...
0000:0074: a4 f0 00 f0 ... 60 14 00 f0

The pointer 0000:0004 looks suspicious to me and I suspect it to point somewhere outside the heap. I do not recognize the contents, but if I write to the memory, the program freezes.
What am I doing wrong and what should I do to get correct pointer from malloc()? Any suggestion will be appreciated.

A: According to an old reference manual, including <stdlib.h> should fix this.  (Compilers on other systems would print a warning for this code, too.)
Without a prototype, malloc is implicitly declared as returning int.  The returned int value is automatically converted to a pointer.  But in the compact memory model, pointers and ints do not have the same representation, so the implicit declaration and conversion do not yield the correct value.
Pretty much same thing happens with implicitly declared malloc on 64-bit UNIX-like platforms.

A: If memory serves me correctly if you want memory allocation to behave as expected with memory models that use far and huge pointers you have to include  alloc.h. Try adding this to your file:
#include <alloc.h>


text:
Q: PostgreSQL - return most common value for all columns in a table I've got a table with a lot of columns in it and I want to run a query to find the most common value in each column.
Ordinarily for a single column, I'd run something like:
SELECT country
FROM users
GROUP BY country
ORDER BY count(*) DESC
LIMIT 1

Does PostgreSQL have a built in function for doing this or can anyone suggest a query I could run to achieve this?

A: Using the same query, for more than one column you should do:
SELECT *
FROM
(
    SELECT country
    FROM users
    GROUP BY 1
    ORDER BY count(*) DESC
    LIMIT 1
) country
,(
    SELECT city
    FROM users
    GROUP BY 1
    ORDER BY count(*) DESC
    LIMIT 1
) city

This works for any type and will return all the values in the same row, with the columns having its original name.
For more columns just had more subquerys as:
,(
    SELECT someOtherColumn
    FROM users
    GROUP BY 1
    ORDER BY count(*) DESC
    LIMIT 1
) someOtherColumn

Edit:
You could reach it with window functions also. However it will not be better in performance nor in readability.

A: Starting from PG 9.4 there is aggregate function for this:
mode() WITHIN GROUP (ORDER BY sort_expression)

returns the most frequent input value (arbitrarily choosing the first one if there are multiple equally-frequent results)
And for earlier versions, you could create one...
  CREATE OR REPLACE FUNCTION mode_array(anyarray)
            RETURNS anyelement AS
$BODY$
    SELECT a FROM unnest($1) a GROUP BY 1 ORDER BY COUNT(1) DESC, 1 LIMIT 1;
$BODY$
LANGUAGE SQL IMMUTABLE;

CREATE AGGREGATE mode(anyelement)(
   SFUNC = array_append, --Function to call for each row. Just builds the array
   STYPE = anyarray,
   FINALFUNC = mode_array, --Function to call after everything has been added to array
   INITCOND = '{}'--Initialize an empty array when starting
) ;

Usage: SELECT mode(column) FROM table;

A: If I were doing this, I'd write a query like this one:
SELECT 'country', country
FROM users
GROUP BY country
ORDER BY count(*) DESC
LIMIT 1
UNION ALL
SELECT 'city', city
FROM USERS
GROUP BY city
ORDER BY count(*) DESC
LIMIT 1
-- etc.

It should be noted this only works if all the columns are of compatible types.  If they are not, you'll probably need a different solution.

A: This window function version will read the users table and the computed table once each. The correlated subquery version will read the users table once for each of the columns. If the columns are many as in the OPs case then my guess is that this is faster. SQL Fiddle
select distinct on (country_count, age_count) *
from (
    select
        country,
        count(*) over(partition by country) as country_count,
        age,
        count(*) over(partition by age) as age_count
    from users
) s
order by country_count desc, age_count desc
limit 1


text:
Q: Reload own created UITableViewCell I got a custom UITableViewcell which should load an Image when use that code:
- (void)setImageWithURL:(NSURL *)URL
{
    dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(taskQ, ^{
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:URL]];
        imageView.image = image;
        NSLog(@"test");
    });
}

It loads the Image very fast, so I get the response "test" very fast, but it needs to load IN the tableView. Also if I select the row it loads the Image.
How can I fix this issue?
Thanks

A: As long as setImageWithURL: is called as an effect of cellForRowAtIndexPath, then it should should show up as you expect... however, you need to call imageView.image = image; on the main thread.  This goes for ALL UI related tasks.  So you'll want:
- (void)setImageWithURL:(NSURL *)URL
{
    dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(taskQ, ^{
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:URL]];
        dispatch_async(dispatch_get_main_queue(), ^{
            imageView.image = image;
            NSLog(@"test");
        });
    });
}

EDIT:
Using NSOperationQueue.
Create an operation queue as a member of your view controller.
    m_operationQueue = [NSOperationQueue new];
    m_operationQueue.maxConcurrentOperationCount = 1 // if you want to load images in order;

Make sure you cancel operations when the view unloads and when the table will refresh using
    [m_operationQueue cancelAllOperations];

Do your thing in setImageWithURL
- (void)setImageWithURL:(NSURL *)URL
{
    [m_operationQueue addOperationWithBlock:^{
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:URL]];
        dispatch_async(dispatch_get_main_queue(), ^{
            imageView.image = image;
            NSLog(@"test");
        });
    }];
}

EDIT again:
Sorry, forgot that setImage was in your custom table cell.  You can either:
1) make it a static object that you initialize in the +(void)initialize; method of your cell
2) make it a static object available via class method on your view controller
2) make a singleton instance that is available to your table cell
The design preference is up to you and depends what other practices you've been using if you want to be consistent.

A: You should call [tableView reloadData] when you finish downloading the image.
There is a similar question with an accepted answer, but also it has a suggestion to use SDWebImage. Take a look: How to get UITableViewCell images to update to downloaded images without having to scroll UITableView


text:
Q: How to track users cross domain for a purchase I'm creating a kind of affiliate marketing website with products I've scraped from partner websites. The user clicks on the Buy link and is re-directed to the partner site to complete the purchase. If the user buys the product, I should get a percentage of the sales. So far this model is a pretty common approach.
However the element that I don't yet understand is, what technology or script do other affiliate sites use to track to see if the user, once they've let the main site, does purchase the product or not? How do I track my user's purchase or actions once they've left my site?
I know that cookies can store brief user information but I don't think that's enough. I need to then store this information in a database. Should I use php sessions for this?
Any tips or suggestions is really appreciated.
Cheers

A: What technology or script do other affiliate sites use to track to see if the user, once they've let the main site, does purchase the product or not?
Javascript. Affiliate Softwares usually have click tracking code which is placed on the landing pages. Once a vsitor comes to landing page through an affiliate website, a random visitor id along with affiliate id mapping is created which gets stored in the database. At this same time, a cookie gets created with the visitor id, affiliate id info etc. When the user finishes a purchase, there is a sales tracking code javascript code which is placed on the purchase page that gets trigerred. You can use create this code and insert the visitor's id along with affiliate id in the database.
How do I track my user's purchase or actions once they've left my site?
I have answered this partly in the above question. But once the user comes back again, it is going to recognise this user based on cookie and preferably you can store the session value in the cookie itself rather than the database, because the sale entry will get created  in the database once the user has completed his purchase, if you have placed your sale tracking code at the end of purchase page.