text:
Q: TypeError: Cannot read property 'style' of undefined in /node_modules/galio-framework/src/Toast.js I am having this error when doing
expo start --web

TypeError: Cannot read property 'style' of undefined
Module /APP/node_modules/galio-framework/src/Toast.js
node_modules/galio-framework/src/Toast.js:23
  20 |   PropTypes.string,
  21 | ]),
  22 | round: PropTypes.bool,
> 23 | style: ViewPropTypes.style,
     | ^  24 | textStyle: ViewPropTypes.style,
  25 | styles: PropTypes.any,
  26 | theme: PropTypes.any,

Initially I had other errors but I could solve them by adding the following code in the web section app.json
"web": {
  "favicon": "./assets/favicon.png",
  "build": {
    "babel": {
      "include": ["galio-framework"]
    }
  }
},

package.json
{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@expo/vector-icons": "^12.0.3",
    "@react-native-community/masked-view": "^0.1.10",
    "@react-navigation/native": "^5.9.2",
    "@react-navigation/stack": "^5.14.2",
    "cheerio": "^1.0.0-rc.5",
    "expo": "~40.0.0",
    "expo-constants": "~9.3.3",
    "expo-image-picker": "^10.0.0",
    "expo-status-bar": "~1.0.3",
    "expo-web-browser": "^9.0.0",
    "galio-framework": "^0.7.1",
    "moment": "^2.29.1",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz",
    "react-native-animatable": "^1.3.3",
    "react-native-elements": "^3.1.0",
    "react-native-gesture-handler": "^1.9.0",
    "react-native-image-view": "^2.1.9",
    "react-native-image-zoom-viewer": "^3.0.1",
    "react-native-masked-text": "^1.13.0",
    "react-native-material-menu": "^1.2.0",
    "react-native-material-ui": "^1.30.1",
    "react-native-modal": "^11.6.1",
    "react-native-paper": "^4.7.1",
    "react-native-reanimated": "^1.13.2",
    "react-native-screens": "^2.17.1",
    "react-native-vector-icons": "^8.0.0",
    "react-native-web": "^0.14.13",
    "react-native-wizard": "^2.1.0",
    "react-navigation": "^4.4.3",
    "react-navigation-drawer": "^2.6.0",
    "react-navigation-stack": "^2.10.2",
    "uuid": "^3.4.0"
  },
  "devDependencies": {
    "@babel/core": "~7.9.0",
    "typescript": "~4.0.0"
  },
  "private": true
}

A: style: PropTypes.style

I have done and fixed that problem, but now I get the problem a little further down, on the line that says
textStyle: Text.propTypes.style,

How should I solve it?

A: Replace the follwing code in node_modules/galio-framework/src/Toast.js
replace :
style: ViewPropTypes.style

for : style: PropTypes.style


text:
Q: How do I complete the extraction wave in multiplayer? The eleventh (and final) wave in multiplayer involves getting to an extraction zone before the time limit expires. What happens if there are players outside of the zone when the time limit ends? Do all players need to be inside or just one?

A: Once you've reached Wave 11 (The "Extraction" wave), you've officially won the match, and are playing in a "bonus" round of sorts.
The only thing at stake is your extraction bonus, which tops out at "Full Extraction".

*

*2500 team score for 1 person extracted

*5000 team score for 2 or 3 people extracted

*15000 team score for all 4 teammembers extracted.

The only thing that matters is where players are when the timer reaches zero. If they're alive, but outside the extraction zone, they don't count. If they're downed an in the extraction zone, they don't count. Only living characters within the extraction zone count towards this bonus.
So you don't need anybody in the extraction zone, but the more you have, the merrier.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loading all the images from gallery into the Application in android I am creating an application wherein I need all the images in the gallery into my application that has a girdview in it. I want all the images from all the folders to appear in the gridview.
String[] proj = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
                      null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);

actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor.getString(actual_image_column_index);

I have added this code into my code but i get only the sd card images no other folder images are obtained.
How can i get all the images from the gallery?
Thanks in advance.

A: You are using MediaStore.Images.Media.EXTERNAL_CONTENT_URI which is only the external storage.For the internal there is MediaStore.Images.Media.INTERNAL_CONTENT_URI.
You can use a MergeCursor to combine both query results.

A: Working solution with the help of Glide. Bonus part is Glide will auto play Gif .

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

/**
 * The Class GallarySample.
 */
public class GallarySample extends Activity {

    /** The images. */
    private ArrayList<String> images;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery_activity);

        GridView gallery = (GridView) findViewById(R.id.galleryGridView);

        gallery.setAdapter(new ImageAdapter(this));

        gallery.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                if (null != images && !images.isEmpty())
                    Toast.makeText(
                            getApplicationContext(),
                            "position " + position + " " + images.get(position),
                            300).show();
                ;

            }
        });

    }

    /**
     * The Class ImageAdapter.
     */
    private class ImageAdapter extends BaseAdapter {

        /** The context. */
        private Activity context;

        /**
         * Instantiates a new image adapter.
         *
         * @param localContext
         *            the local context
         */
        public ImageAdapter(Activity localContext) {
            context = localContext;
            images = getAllShownImagesPath(context);
        }

        public int getCount() {
            return images.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView,
                ViewGroup parent) {
            ImageView picturesView;
            if (convertView == null) {
                picturesView = new ImageView(context);
                picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                picturesView
                        .setLayoutParams(new GridView.LayoutParams(270, 270));

            } else {
                picturesView = (ImageView) convertView;
            }

            Glide.with(context).load(images.get(position))
                    .placeholder(R.drawable.ic_launcher).centerCrop()
                    .into(picturesView);

            return picturesView;
        }

        /**
         * Getting All Images Path.
         *
         * @param activity
         *            the activity
         * @return ArrayList with images Path
         */
        private ArrayList<String> getAllShownImagesPath(Activity activity) {
            Uri uri;
            Cursor cursor;
            int column_index_data, column_index_folder_name;
            ArrayList<String> listOfAllImages = new ArrayList<String>();
            String absolutePathOfImage = null;
            uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

            String[] projection = { MediaColumns.DATA,
                    MediaStore.Images.Media.BUCKET_DISPLAY_NAME };

            cursor = activity.getContentResolver().query(uri, projection, null,
                    null, null);

            column_index_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
            column_index_folder_name = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
            while (cursor.moveToNext()) {
                absolutePathOfImage = cursor.getString(column_index_data);

                listOfAllImages.add(absolutePathOfImage);
            }
            return listOfAllImages;
        }
    }
}

Layout file for gridView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <GridView
        android:id="@+id/galleryGridView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnWidth="280dp"
        android:gravity="center"
        android:horizontalSpacing="2dp"
        android:numColumns="2"
        android:padding="2dp"
        android:stretchMode="columnWidth"
        android:verticalSpacing="2dp" >
    </GridView>

</RelativeLayout>

UPDATE 2019 with Kotlin and LoderManager:
** 2) Use LoderManager to load async load images.**
Implement  LoaderManager.LoaderCallbacks<Cursor> in your activity or Fragment class
Override LoaderCallbacks this:
private val IMAGE_LOADER_ID = 1
private val listOfAllImages = ArrayList<String>()

override fun onCreateLoader(p0: Int, p1: Bundle?): Loader<Cursor> {

    val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val projection = arrayOf(MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME)
    val selection: String? = null     //Selection criteria
    val selectionArgs = arrayOf<String>()  //Selection criteria
    val sortOrder: String? = null

    return CursorLoader(
            activity!!.applicationContext,
            uri,
            projection,
            selection,
            selectionArgs,
            sortOrder)
}

override fun onLoadFinished(loader: Loader<Cursor>, cursor: Cursor?) {

    cursor?.let {
        val columnIndexData = it.getColumnIndexOrThrow(MediaColumns.DATA);

        while (it.moveToNext()) {

            listOfAllImages.add(it.getString(columnIndexData));
        }
    }
}

override fun onLoaderReset(loader: Loader<Cursor>) {
}

Lastly on onCreate method init loader:
 loaderManager.initLoader(IMAGE_LOADER_ID,
                null,
                this)

3) Using Kotlin Coroutine & ViewModel

implementation 'androidx.core:core-ktx:1.0.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0-M2'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0-M2"

Create View Model With Coroutine Context
  /**
   * Use Coroutines To Load Images
   */
   class ImageViewModel : ViewModel(), CoroutineScope {

    private val job = Job()
    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Main

    private var imagesLiveData: MutableLiveData<List<String>> = MutableLiveData()
    fun getImageList(): MutableLiveData<List<String>> {
        return imagesLiveData
    }

    /**
     * Getting All Images Path.
     *
     * Required Storage Permission
     *
     * @return ArrayList with images Path
     */
    internal fun loadImagesfromSDCard(): ArrayList<String> {
        val uri: Uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val cursor: Cursor?
        val column_index_data: Int
        val column_index_folder_name: Int
        val listOfAllImages = ArrayList<String>()
        var absolutePathOfImage: String? = null

        val projection = arrayOf(MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME)

        cursor = AppController.globalContentResolvere!!.query(uri, projection, null, null, null)

        column_index_data = cursor!!.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
        column_index_folder_name = cursor!!
            .getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)
        while (cursor!!.moveToNext()) {
            absolutePathOfImage = cursor!!.getString(column_index_data)
            listOfAllImages.add(absolutePathOfImage)
        }
        return listOfAllImages
    }

    fun getAllImages() {
        launch(Dispatchers.Main) {
            imagesLiveData.value = withContext(Dispatchers.IO) {
                loadImagesfromSDCard()
            }
        }
    }
}

And then use viewModel
 val imageViewModel = ViewModelProviders.of(this).get(ImageViewModel::class.java)

    imageViewModel.getImageList().observe(this, Observer<List<String>> { listOfImage ->
        imageWidgetStatus.text = """ Found ${listOfImage.size} Images"""

    // load images
    imageViewModel.getAllImages()

A: Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);

A:  public static ArrayList<String> fetchGalleryImages(Activity context) {
        ArrayList<String> galleryImageUrls;
        final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};//get all columns of type images
        final String orderBy = MediaStore.Images.Media.DATE_TAKEN;//order data by date

        Cursor imagecursor = context.managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
                null, orderBy + " DESC");//get all data in Cursor by sorting in DESC order

        galleryImageUrls = new ArrayList<String>();

        for (int i = 0; i < imagecursor.getCount(); i++) {
            imagecursor.moveToPosition(i);
            int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);//get column index
            galleryImageUrls.add(imagecursor.getString(dataColumnIndex));//get Image from column index

        }
        Log.e("fatch in","images");
        return galleryImageUrls;
    }

A: This is how I did it in Kotlin with the usage of Coroutines and Flow (but Flow can be easily changed to LivaData).
Dependencies:
def lifecycle_version = "2.2.0"
def coroutines_version = "1.4.2"
def glide_version = "4.11.0"

// Coroutines https://github.com/Kotlin/kotlinx.coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"

// Lifecycle https://developer.android.com/jetpack/androidx/releases/lifecycle#declaring_dependencies
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"

// Glide https://github.com/bumptech/glide (OPTIONALLY)
implementation "com.github.bumptech.glide:glide:$glide_version"

ViewModel:
import android.app.Application
import android.content.ContentUris
import android.net.Uri
import android.provider.MediaStore
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AddViewModel(
    application: Application
) : AndroidViewModel(application)
{
    private val _allImagesFromGallery: MutableStateFlow<List<Uri>> = MutableStateFlow(listOf())
    val allImagesFromGallery: StateFlow<List<Uri>> = _allImagesFromGallery

    private fun getAllImages(): List<Uri>
    {
        val allImages = mutableListOf<Uri>()

        val imageProjection = arrayOf(
            MediaStore.Images.Media._ID
        )

        val imageSortOrder = "${MediaStore.Images.Media.DATE_ADDED} DESC"

        val cursor = getApplication<Application>().contentResolver.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            imageProjection,
            null,
            null,
            imageSortOrder
        )

        cursor.use {

            if (cursor != null)
            {
                val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
                while (cursor.moveToNext())
                {
                    allImages.add(
                        ContentUris.withAppendedId(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            cursor.getLong(idColumn)
                        )
                    )
                }
            }
            else
            {
                Log.d("AddViewModel", "Cursor is null!")
            }
        }
        return allImages
    }

    fun loadAllImages()
    {
        viewModelScope.launch {
            _allImagesFromGallery.value = withContext(Dispatchers.IO) {
                getAllImages()
            }
        }
    }
}

In Fragment (or Activity):
import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import kotlinx.coroutines.flow.collectLatest

class AddFragment : Fragment(R.layout.fragment_add)
{
    private lateinit var binding: FragmentAddBinding
    private val viewModel: AddViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?)
    {
        super.onViewCreated(view, savedInstanceState)
        binding = DataBindingUtil.bind(view)!!

        viewModel.loadAllImages()
        setupCollecting()
    }

    private fun setupCollecting()
    {
        lifecycleScope.launchWhenStarted {
            viewModel.allImagesFromGallery.collectLatest {
                // simple test, take first image and load it to ImageView using Glide
                if (it.isNotEmpty())
                {
                    Glide.with(requireContext())
                        .load(it[0])
                        .into(binding.imgSelected)
                }
            }
        }
    }
}

*

*Before loading all images from the gallery Manifest.permission.READ_EXTERNAL_STORAGE has to be granted.

*When using Glide in Manifest there also should be: android:requestLegacyExternalStorage="true"

A: You can not get results with just one query, try to instantiate two different Cursors.
Since you have already added EXTERNAL_CONTENT_URI, here is another:
 actualimagecursor2 = managedQuery(MediaStore.Images.Media.INTERNAL_CONTENT_URI, proj,
                      null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);

A: Download the source code from here (Get all images from gallery in android programmatically)
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
xmlns:android="http://schemas.android.com/apk/res/android">

<GridView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/gv_folder"
    android:numColumns="2"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"></GridView>

</RelativeLayout>

MainActivity.java
package galleryimages.galleryimages;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    gv_folder = (GridView)findViewById(R.id.gv_folder);

    gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(getApplicationContext(), PhotosActivity.class);
            intent.putExtra("value",i);
            startActivity(intent);
        }
    });

    if ((ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
        if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE))) {

        } else {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_PERMISSIONS);
        }
    }else {
        Log.e("Else","Else");
        fn_imagespath();
    }

}

public ArrayList<Model_images> fn_imagespath() {
    al_images.clear();

    int int_position = 0;
    Uri uri;
    Cursor cursor;
    int column_index_data, column_index_folder_name;

    String absolutePathOfImage = null;
    uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

    String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};

    final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
    cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");

    column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
    while (cursor.moveToNext()) {
        absolutePathOfImage = cursor.getString(column_index_data);
        Log.e("Column", absolutePathOfImage);
        Log.e("Folder", cursor.getString(column_index_folder_name));

        for (int i = 0; i < al_images.size(); i++) {
            if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
                boolean_folder = true;
                int_position = i;
                break;
            } else {
                boolean_folder = false;
            }
        }

        if (boolean_folder) {

            ArrayList<String> al_path = new ArrayList<>();
            al_path.addAll(al_images.get(int_position).getAl_imagepath());
            al_path.add(absolutePathOfImage);
            al_images.get(int_position).setAl_imagepath(al_path);

        } else {
            ArrayList<String> al_path = new ArrayList<>();
            al_path.add(absolutePathOfImage);
            Model_images obj_model = new Model_images();
            obj_model.setStr_folder(cursor.getString(column_index_folder_name));
            obj_model.setAl_imagepath(al_path);

            al_images.add(obj_model);

        }

    }

    for (int i = 0; i < al_images.size(); i++) {
        Log.e("FOLDER", al_images.get(i).getStr_folder());
        for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
            Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
        }
    }
    obj_adapter = new Adapter_PhotosFolder(getApplicationContext(),al_images);
    gv_folder.setAdapter(obj_adapter);
    return al_images;
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case REQUEST_PERMISSIONS: {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    fn_imagespath();
                } else {
                    Toast.makeText(MainActivity.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

}

adapter_photosfolder.xml
   <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:background="@drawable/drawable_photofolder"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:layout_height="match_parent">
    <ImageView
        android:layout_width="150dp"
        android:layout_gravity="center"
        android:layout_height="150dp"
        android:id="@+id/iv_image"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_folder"
        android:textStyle="bold"
        android:textColor="#000000"
        android:layout_marginLeft="10dp"
        android:textSize="15dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_folder2"
            android:textColor="#dfdfdf"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:textSize="15dp"/>
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:id="@+id/rl_select"
        android:alpha="0.5"
        android:layout_height="match_parent">

    </RelativeLayout>

    </RelativeLayout>

Adapter_PhotosFolder.java
    package galleryimages.galleryimages;

    import android.content.Context;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;

    import com.bumptech.glide.Glide;
    import com.bumptech.glide.load.engine.DiskCacheStrategy;

    import java.util.ArrayList;

     public class Adapter_PhotosFolder extends ArrayAdapter<Model_images> {

    Context context;
    ViewHolder viewHolder;
    ArrayList<Model_images> al_menu = new ArrayList<>();

    public Adapter_PhotosFolder(Context context, ArrayList<Model_images> al_menu) {
        super(context, R.layout.adapter_photosfolder, al_menu);
        this.al_menu = al_menu;
        this.context = context;

    }

    @Override
    public int getCount() {

        Log.e("ADAPTER LIST SIZE", al_menu.size() + "");
        return al_menu.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        if (al_menu.size() > 0) {
            return al_menu.size();
        } else {
            return 1;
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null) {

            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_photosfolder, parent, false);
            viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
            viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
            viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.tv_foldern.setText(al_menu.get(position).getStr_folder());
            viewHolder.tv_foldersize.setText(al_menu.get(position).getAl_imagepath().size()+"");

        Glide.with(context).load("file://" + al_menu.get(position).getAl_imagepath().get(0))
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(viewHolder.iv_image);

        return convertView;

    }

    private static class ViewHolder {
        TextView tv_foldern, tv_foldersize;
        ImageView iv_image;

    }

    }

**PhotosActivity.java**
    package galleryimages.galleryimages;
    import android.app.Activity;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.GridView;

    public class PhotosActivity extends AppCompatActivity {
    int int_position;
    private GridView gridView;
    GridViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gridView = (GridView)findViewById(R.id.gv_folder);
        int_position = getIntent().getIntExtra("value", 0);
        adapter = new GridViewAdapter(this,MainActivity.al_images,int_position);
        gridView.setAdapter(adapter);
    }
}

**GridViewAdapter.java**

package galleryimages.galleryimages;

    import android.app.Activity;
    import android.content.Context;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;

    import com.bumptech.glide.Glide;
    import com.bumptech.glide.load.engine.DiskCacheStrategy;

    import java.util.ArrayList;
    import java.util.List;

    public class GridViewAdapter extends ArrayAdapter<Model_images> {

    Context context;
    ViewHolder viewHolder;
    ArrayList<Model_images> al_menu = new ArrayList<>();
    int int_position;

    public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
        super(context, R.layout.adapter_photosfolder, al_menu);
        this.al_menu = al_menu;
        this.context = context;
        this.int_position = int_position;

    }

    @Override
    public int getCount() {

        Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
        return al_menu.get(int_position).getAl_imagepath().size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
            return al_menu.get(int_position).getAl_imagepath().size();
        } else {
            return 1;
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null) {

            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_photosfolder, parent, false);
            viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
            viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
            viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.tv_foldern.setVisibility(View.GONE);
        viewHolder.tv_foldersize.setVisibility(View.GONE);

        Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(viewHolder.iv_image);

        return convertView;

    }

    private static class ViewHolder {
        TextView tv_foldern, tv_foldersize;
        ImageView iv_image;

    }

    }

Model_images.java
  package galleryimages.galleryimages;

    import java.util.ArrayList;

    public class Model_images {
    String str_folder;
    ArrayList<String> al_imagepath;

    public String getStr_folder() {
        return str_folder;
    }

    public void setStr_folder(String str_folder) {
        this.str_folder = str_folder;
    }

    public ArrayList<String> getAl_imagepath() {
        return al_imagepath;
    }

    public void setAl_imagepath(ArrayList<String> al_imagepath) {
        this.al_imagepath = al_imagepath;
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="galleryimages.galleryimages">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".PhotosActivity"></activity>
    </application>

</manifest>

A: Adding to @anil-singhania's answer, context.managedQuery is deprecated. Rather, we use context.getContentResolver.query()
Code:
public static ArrayList<String> fetchGalleryImages(Context context) {
    ArrayList<String> galleryImageUrls;
    final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};//get all columns of type images
    final String orderBy = MediaStore.Images.Media.DATE_TAKEN;//order data by date

    Cursor imagecursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy + " DESC");//get all data in Cursor by sorting in DESC order

    galleryImageUrls = new ArrayList<String>();

    for (imagecursor.moveToFirst(); !imagecursor.isAfterLast(); imagecursor.moveToNext()) {
        int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);//get column index
        galleryImageUrls.add(imagecursor.getString(dataColumnIndex));//get Image from column index

    }
    return galleryImageUrls;
}


text:
Q: dll in php "the specified module could not be found" I am having trouble with PHP extensions. I am trying to run a script and nothing happens then I checked my error log and here is what I got:
PHP Startup: Unable to load dynamic library 'C:\Program Files (x86)\PHP\ext\php_oci8.dll' - The specified module could not be found. in Unknown on line 0

same goes for following files:
 php_oci8_11g.dll
 php_pdo_oci.dll
 php_sybase_ct.dll
 php_com_dotnet.dll

every file except php_com_dotnet.dll was installed with PHP installation, all the files are enabled in php.ini configuration. After researching online I saw some people said that it has to be copied to system32 or sysWOW64 folder, which I did without success. Then I tried to register them using regsvr32 in cmd and I am getting error for every single file:
"The module name_of_the_module.dll failed to load"

I don't understand what am I doing wrong.
Server configuration is Windows 2008 R2 64bit, IIS7, PHP 5.3.27

A: On Windows, I solved these kind of problems by adding the path specified in 'extension_dir' (in php.ini) to the value of PATH system environment variable.

A: Check your extension_dir in your php.ini, it has to point to the correct directory.
# X:/path/to/php.ini

# On Windows
extension_dir = "ext"


text:
Q: flask url_for TypeError I have an error when trying to use the url_for method in Flask. I'm not sure what the cause of it because I only follow the Flask quick start. I'm a Java guy with a bit of Python experience and want to learn Flask.
Here's the trace:
Traceback (most recent call last):
  File "hello.py", line 36, in <module>
    print url_for(login)
  File "/home/cobi/Dev/env/flask/latest/flask/helpers.py", line 259, in url_for
    if endpoint[:1] == '.':
TypeError: 'function' object has no attribute '__getitem__

My code is like this:
from flask import Flask, url_for
app = Flask(__name__)
app.debug = True

@app.route('/login/<username>')
def login(): pass

with app.test_request_context():
  print url_for(login)

I'm have tried both the stable and development version of Flask and the error still occurs. Any help will be much appreciated! Thank you and sorry if my English is not very good.

A: The docs say that url_for takes a string, not a function. You also need to provide a username since the route you created requires one.
Do this instead:
with app.test_request_context():
    print url_for('login', username='testuser')

You are receiving this error because strings have a __getitem__ method but functions do not.
>>> def myfunc():
...     pass
...
>>> myfunc.__getitem__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__getitem__'
>>> 'myfunc'.__getitem__
<method-wrapper '__getitem__' of str object at 0x10049fde0>
>>>


text:
Q: Drawing panel size I have problem setting the size of drawing panel. I want a drawing panel with the size 0f 600,600.However I found that, the size of the drawing panel is smaller than 600,600. It seems that the frame size is 600,600 which make the drawing panel smaller. How can I set the drawing panel size 600,600 ?
....
public class DrawingBoardWithMatrix extends JFrame {
   public static void main(String[] args) {
      new DrawingBoardWithMatrix();
   }

   public DrawingBoardWithMatrix(){
      this.getContentPane().setBackground(Color.WHITE);
      this.setSize(600, 600);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.add(new PaintSurface(), BorderLayout.CENTER);
      this.setVisible(true);
      setResizable(false);
   }

I have changed the code,however the problem still exist.
At this time the size of the drawing panel is larger than the intended size dimension.
public class DrawingBoardWithMatrix extends JFrame {
  public static void main(String[] args) {
      new DrawingBoardWithMatrix();
  }

  public DrawingBoardWithMatrix(){
      Container c = getContentPane();
      c.add(new PaintSurface(), BorderLayout.CENTER);
      c.setPreferredSize(new Dimension(600,600));
      pack();
      this.setVisible(true);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setResizable(false);
  }

A: The reason is that there is some space reserved for 'inset' such as border. To know how much extra space is needed called the frame 'getInsets()'.

A: Set the preferred size of your component to 600,600, and call pack() on the frame.

A: do as NawaMan suggested, and take the insets into account, or set the size of your 'PaintSurface' Object to 600x600.  Of course you may then need a scroll pane to get the full size.

A:
The problem SOLVED
  public DrawingBoardWithMatrix(){
      Container c = getContentPane();
      c.add(new PaintSurface(), BorderLayout.CENTER);
      setResizable(false);      //put the code setResizable(false) before pack();
      pack();
      this.setVisible(true);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  }

public PaintSurface() {
    this.setPreferredSize(new Dimension (600,600));
.....
}


text:
Q: How do I scale and set the origin of a draw picturebox with xy coordinates I have a series of X,Y coordinates generated from a triangulated method of measurements. I would like to draw lines to the X,Y coordinates on a picture box so the data entry can be validated. My code generates these x,y values to dynamically created textboxes and then draws them on the picture box. Currently it is working but the resulting lines are very small and they are not centered. How can I fix this? The picturebox1 is 500x500. Here is the code
 Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
    If Me.CheckBox1.Checked = True Then
        Dim n As Integer
        Dim g As Graphics
        g = PictureBox1.CreateGraphics

        Dim x, y, x1, y1 As String
        x = Me.Controls.Item("myTextBoxX1").Text
        y = Me.Controls.Item("myTextBoxY1").Text
        x1 = Me.Controls.Item("myTextBoxX2").Text
        y1 = Me.Controls.Item("myTextBoxY2").Text

        Dim xi, yi, x1i, y1i As Integer

        xi = Convert.ToDecimal(x)
        yi = Convert.ToDecimal(y)
        x1i = Convert.ToDecimal(x1)
        y1i = Convert.ToDecimal(y1)

        g.DrawLine(New Pen(ForeColor), xi, yi, x1i, y1i)
        Dim x1a, y1a, x2a, y2a As String
        Dim x1ai, y1ai, x2ai, y2ai As Integer
        For n = 3 To Me.TextBoxABPts.Text
            x1a = Me.Controls.Item("myTextBoxX" & n - 1).Text
            y1a = Me.Controls.Item("myTextBoxY" & n - 1).Text
            x2a = Me.Controls.Item("myTextBoxX" & n).Text
            y2a = Me.Controls.Item("myTextBoxY" & n).Text

            x1ai = Convert.ToDecimal(x1a)
            y1ai = Convert.ToDecimal(y1a)
            x2ai = Convert.ToDecimal(x2a)
            y2ai = Convert.ToDecimal(y2a)

            g.DrawLine(New Pen(ForeColor), x1ai, y1ai, x2ai, y2ai)
        Next n

        g.DrawLine(New Pen(ForeColor), x2ai, y2ai, xi, yi)
    End If
End Sub

A: It will probably be easier to use .Net Point for working with coordinates. They consist of X and Y integer values. PointF is another structure that is based on singles. Either will work for you. Create a function that can transpose as scale coordinates.
Private Function ScaledPoint(Point As Point, Origin As Point, Optional Scale As Double = 1.0) As Point
    Return New Point(CInt(Origin.X + Point.X * Scale), CInt(Origin.Y + Point.Y * Scale))
End Function

In you application, define an origin and scale factor. For example:
Dim origin As New Point(200, 100) 'Moves all points 200 right, 100 down.
Dim scaleFactor As Double = 5 'Makes drawing 5 times larger.

Now where you call g.DrawLine, change it to something like:
Dim Point1 As New Point(x1ai, y1ai) 'There are lots of ways to do this.
Dim Point2 As New Point(x2ai, y2ai) 'This is only an example.
g.DrawLine(New Pen(ForeColor), ScaledPoint(Point1, origin), ScaledPoint(Point2, origin))

There are lots of ways to define Point1 and Point2.


text:
Q: Prove Property of Green Function Solution to Laplace Equation in a 2D-square Let's consider a 2D-square with 4 euqal subsquares containing different dielectrics.

Inside the square domain, the unkown potential function $\Phi$ satisfies the Laplace equation:
$\nabla^2\Phi=0$
and satisfies the continuity conditions on the interfaces between differnet dielectrics:
$\Phi^+=\Phi^-$
$\frac{\partial\Phi^+}{\partial n}\epsilon^+=\frac{\partial\Phi^-}{\partial n}\epsilon^-$
If we apply Dirichlet Boundary conditions to the 4 edges of the square domain, then we can define a surface green function[1] G(x, y | $\eta$) to help solve the unknown function $\Phi$ inside the square domain:
$\Phi(x,y)=\oint_L\Phi(\eta)G(x,y|\eta)d\eta$
Coordinate (x, y) denotes a point inside the square domain while $\eta$ denotes the point on the domain boundary. The $\Phi(\eta)$ is the Dirichlete Boundary Condition and is known. L is the closed boundary of the square domain.
Assuming the length of the square domain's each edge is a, by numerical method, I found a property of G(x, y | $\eta$):
$$\frac{G(\frac{a}{2},\frac{a}{2}|\eta_i)}{\epsilon_i}=\frac{G(\frac{a}{2},\frac{a}{2}|\eta_j)}{\epsilon_j}$$
where the 2 points corresponding to $\eta_i$ and $\eta_j$ are centrosymmetric in reference to the central point of the square domain. $\epsilon_i$ and $\epsilon_j$ are the dielectric value of the subdomains containing them.
For special case, such as the dielectrics of each subsquare are the same, the analytic solution for G(x, y | $\eta$) does exist and the property holds, as done in [1] with variational separation method for Laplace equation. But I dont't know how to prove it for arbitary $\epsilon_1, \epsilon_2, \epsilon_3, \epsilon_4$ with analytic method. I don't know wether there is an analytic solution for G(x, y | $\eta$) with help of the centrosymmetry of the square domain. Or maybe we can only prove the property holds while the numerical solution converges to the true solution?
Thanks for your help!
Refs:
[1] Y. Le Coz and R. B. Iverson, "A stochastic algorithm for high speed capacitance extraction in integrated circuits," Solid State Electron., vol. 35, no. 7,pp.1005–1012, Jul. 1992.


text:
Q: 2 stacked divs in container: one shrinks to fit its content, the other expands to fill remaining space Here is a jsfiddle containing basic html and css for what I'm trying to do.
Here is my html:

#mother {
  width: 100%;
  height: 100vh;
  background-color: white;
}

#header,
#footer {
  width: 100%;
  height: 20px;
  background-color: pink;
}

#title {
  width: 100%;
  background-color: grey;
}

#main {
  width: 100%;
  background-color: cyan;
}

    Title content of indeterminate length

    Main body content of indeterminate length

I am trying to create a website which will fill 100% of the window height and no more.
The layout needs to consist of 4 sections:
- header
- title
- main
- footer
The header and footer have a fixed height. The title and main will have content of unknown length.
My ideal behaviour would be for the title container to shrink to fit its content, and the main container to expand to fill the remaining available space before the footer. There will be divs within the main container which will need to be sized to 100% of its height.
The use of absolutely positioned elements or tables is acceptable as long as it has IE support (only need to support most recent version, but support for older versions would be amazing).

A: Try using Flexbox.
The flex:1 means it will fill as much space as it can. So leaving the title without flex:1 allows it to shrink to fit its content.
Also, don't forget to use all the prefixes required for your browser support.
http://shouldiprefix.com/
Here's the jsfiddle
html, body{

  height:100%;

}

#mother {
  width: 100%;
  height: 100vh;
  background-color: white;
  display: -webkit-box;  /* OLD - iOS 6-, Safari 3.1-6, BB7 */
  display: -ms-flexbox;  /* TWEENER - IE 10 */
  display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
  display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */
  flex-direction:column;
}

#header, #footer {
  width: 100%;
  height: 20px;
  background-color: pink;
}

#title {
  width: 100%;
  background-color: grey;
}

#main {
  width: 100%;
  background-color: cyan;
  flex:1;
}

A: You can use calc in css3.
Include title in main and give height to main content using calc .
    #main{
     height: calc(100% - 40px);
    }

Title and the inner content should place inside the main.


text:
Q: Capitalize the vowels I have been doing a challenge in which I have to create a function in Javascript which would change the letter position by one and vowels have to be capitalized, for instance "f" goes "g", "z" to "A" and "m" goes to "O". I did a big chunk of these steps but I am struggling with capitalizing the vowels. This is my code:

function LetterChanges(str) {
  var newString = [];

  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) >= 97 && str.charCodeAt(i) <= 121) {
      newString.push(String.fromCharCode(str.charCodeAt(i) + 1));
    }
    // z to a
    else if (str.charCodeAt(i) === 122) {
      newString.push(String.fromCharCode(str.charCodeAt(i) - 57));
    } //spaces
    else if (str.charCodeAt(i) === 32) {
      newString.push(String.fromCharCode(32));
    } else {
      newString.push(String.fromCharCode(str.charCodeAt(i)));
    }
  }

  return newString.join("");
}

console.log(LetterChanges("fanzd times!"));

A: You're not alone. Many people when confronted with a problem like this, start by writing complicated logic involving character codes, if statements etc. There's usually a much simpler way: write down "source" and "target" alphabets and write two lines of code that translates the input between them. If the result is not what you expect, just edit the target alphabet.

src = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
dst = 'bcdEfghIjklmnOpqrstUvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZA'

str = 'whatever!'
out = ''

for (c of str)
  out += dst[src.indexOf(c)] || c

console.log(out)

A: You can just run a string.replace and check for vowels as following;

function LetterChanges(str) {
  var newString = "";

  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) >= 97 && str.charCodeAt(i) <= 121) {
      newString += String.fromCharCode(str.charCodeAt(i) + 1);
    }
    // z to a
    else if (str.charCodeAt(i) === 122) {
      newString += String.fromCharCode(str.charCodeAt(i) - 57);
    } //spaces
    else if (str.charCodeAt(i) === 32) {
      newString += String.fromCharCode(32);
    } else {
      newString += String.fromCharCode(str.charCodeAt(i));
    }
  }

  return newString.replace(/[aeiou]/gi, function(a){return a.charAt().toUpperCase()});
}

console.log(LetterChanges("fanzd times!"));

A: Character Ranges/Codes vs. Dictionary Mappings
Dealing with character ranges is quite confusing, the 97 <= str.charCodeAt(i) <= 121 makes very little sense without looking for ascii char code references. A cleaner solution is to build a dictionary that maps the letters to your desired result, such as {a: 'b', b: 'c', c: 'd', d: 'E', ...} which can be built very efficiently and cleanly — this is much easier to debug, and a much more readable/understandable solution.
Proposed Solution
As a modified version of one of my answers to another question (Replace letters in string with a dictionary array set in Javascript), you could instead do something similar to this if you're using Node.js, a JS precompiler, or don't care about old browsers and can use ES6:
class LetterChanges {
    constructor() {
        const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

        this.encryptionKey = {};

        // build encryptionKey = {a: 'b', b: 'c', c: 'd', d: 'E', ...}
        for (let i=0; i<alphabet.length; i+=1) {
            const j = (i + 1) % alphabet.length;

            this.encryptionKey[alphabet[i]] = alphabet[j].replace(/[aeiou]/, match => match.toUpperCase());
        }
    }

    /**
     * Encrypt some plaintext
     * @param plaintext
     */
    encrypt(plaintext) {
        return plaintext.split('').map(letter => this.encryptionKey[letter] || letter).join('');
    }
}

const cipher = new LetterChanges();
const plaintext = 'fanzd times!';
const encoded = cipher.encrypt(plaintext);

console.log(plaintext, encoded);  // "fanzd times!", "gbOAE Ujnft!"

A: As far as I know there is no clever algorithmic way to see if a letter is a vowel. So for the check, you're going going to need to use a plain old indexOf ['a', 'e', 'i', 'o', 'u'].indexOf(c) !== -1.
I would place it after your other transformations in the loop as a separate condition on the newString at position i and perform the transformation if it's a vowel.

A: For the special case "z" goes to "A", you are already treating that correctly by moving from lowercase to uppercase. You can treat the other vowels in the same manner, by specifically searching for the ASCII values of the preceding characters and changing them to the correct ASCII code for the uppercase vowel. Of course you need to do that distinction before the general case "a - z" in order for the code to work ;-)
Bottom line: if-else cascades need not have mutually exclusive conditions - the first match wins, and the others are skipped because of the "else".
Also, your cases for "32" and "all the rest" are identical, so you can combine them. And if you don't change the char, you can just use str[i] - no conversion required.


text:
Q: Collecting color picker data from HTML form to use in PHP <form action="example.php" method="get">

        Choose a color:
        <input type="color" name="favcolor">

        <input type="submit">
    </form>

Im having a hard time trying to figure this out, hoping someone could assist.
If a user chooses a color from the color picker, how do i save that specific color so that i can transfer it into my PHP file in order to use that color on text for example? Thanks in advance.

A: Hope you will find this as a good solution.  Works with me,  using XAMPP as server
I use 3 languages in HTML page using this code:  English, Arabic, and Urdu.
I use core PHP coding with a slight touch of JavaScript.
Codes for 2 files
color.html and action.php

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

 <meta http-equiv="Content-Language" content="ur" />
 <title> Color  Picker in Php , for Webpage having Urdu, English and Arabic Content   </title>

  <form method="POST" action="action.php">
  Select your favorite color:
  <input type="color" id="favcolor" name="favcolor"  value="#1919f5">

 <input type="submit">
 </form>

 Save this as  color.html

 and   php file  as action.php

 When you Press submit, data is passed using  POST method and processed.

PHP based example

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

 <meta http-equiv="Content-Language" content="ur" />
 <title> Color  Picker in Php , for Webpage having Urdu, English and Arabic Content   </title>

Note:  This PHP function extracts the FORM data submitted via POST method. It assigns a variable $newColor the value passed by id=favcolor.
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST")   {
        //  to be used with empty input or on First visit of page
            if (!empty($_POST["favcolor"]))
            {$newColor  = test_input($_POST["favcolor"]);}
            else $newColor  = "#ff19f5";
          }
/*
Note:  This PHP function **removes unneccasry charaters from FORM data**. Hackers attempt to embed their codes in form data and manipulate to hack you website and database.   **It is to prevent hackers' attacks**. May have many more advantages.
*/

    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
        }
    error_reporting(E_ALL ^ E_NOTICE);

    echo "
The colour of paragraph is
 $newColor .
 ";
     ?>

 <?php  echo  " Colour Value is " . $newColor ;
 ?>

<form method="POST" action="action.php">
  Select your favorite color:
  <input type="color" id="favcolor" name="favcolor"  value="<?php echo $newColor ; ?>">

  <input type="submit">
</form>

A: <form action="" method="get">
    Choose a color:
    <input type="color" name="favcolor">

    <input type="submit">
</form>

Then use this php code that will return in variable the color you pick.
<?php
$favcolor = "";
if (isset($_GET['favcolor'])) {
    $favcolor = $_GET['favcolor'];
} else {
    echo "Pick a color!";
}

echo $favcolor;
?>

I hope it's work for you.


text:
Q: Input numbers with assembly language I am trying to input two numbers from user in assembly language using Irvine32 library but don't know how. This is what I have so far:
INCLUDE Irvine32.inc
.data

number1 WORD
number2 WORD

.code
main PROC

exit
main ENDP
END main

A: i'm not familiar with irvine, but how about writing the input and decode routine yourself?
DOS int 21/a reads a line from stdin, and put's it to your buffer
the decoding from ascii to register is a but more tricky; you have to walk thoug each digit and add them one by one, by shifting the curent value
here's an approach, just to have an idea:
(sorry for syntax, max be incompatible to masm, I still use Eric Isaacson's A86 assembler)
.org 0100
JMP start

buffer: db 10,"          "  ; space for 10 digits

; read input to buffer
input:  mov ah, 0ah         ; input value
        mov dx, buffer
        int 21h
        ret

; decode buffer to CX
decode: mov dx,0
        mov si, buffer+2
        mov cl, [buffer+1]    ; while (numChars>0)

decLoop: cmp cl,0
        je decEnd

        mov ax, dx          ; mul DX by 10
        shl ax, 2
        add ax, dx
        shl ax, 1
        mov dx, ax

        mov al,[si]        ; get current digit
        inc si             ; and point to next one
        sub al,'0'
        mov ah, 0
        add dx, ax          ; add the digit read

        dec cl              ; numChars--
        jmp decLoop
decEnd: ret

; main()
start:  call input
        call decode
        push dx
        call input
        call decode
        pop cx

        ; CX now holds first, DX second number
        ; feel free to do with em what you feel like

        int 20h             ; quit


text:
Q: Invalid Access Token/Missing Claims when logged into IdentityServer4 I have a standard .NET Core 2.1 (MVC and API) and Identity Server 4 project setup.
I am using reference tokens instead of jwt tokens.
The scenario is as follows:

*

*Browse to my application

*Redirected to Identity Server

*Enter valid valid credentials

*Redirected back to application with all claims (roles) and correct access to the application and API

Wait an undetermined amount of time (I think it's an hour, I don't have the    exact timing)

*

*Browse to my application

*Redirected to Identity Server

*I'm still logged into the IDP so I'm redirected immediately back to my
application

*At this point the logged in .NET user is missing claims (roles) and no longer has access to the API

The same result happens if I delete all application cookies
It seems obvious to me that the access token has expired.  How do I handle this scenario?  I'm still logged into the IDP and the middleware automatically logged me into my application, however, with an expired (?) access token and missing claims.
Does this have anything to do with the use of reference tokens?
I'm digging through a huge mess of threads and articles, any guidance and/or solution to this scenario?
EDIT:  It appears my access token is valid.  I have narrowed my issue down to the missing user profile data.  Specifically, the role claim.
When I clear both my application and IDP cookies, everything works fine.  However, after "x" (1 hour?) time period, when I attempt to refresh or access the application I am redirected to the IDP then right back to the application.
At that point I have a valid and authenticated user, however, I am missing all my role claims.
How can I configure the AddOpenIdConnect Middleware to fetch the missing claims in this scenario?
I suppose in the OnUserInformationReceived event I can check for the missing "role" claim, if missing then call the UserInfoEndpoint...that seems like a very odd workflow.  Especially since on a "fresh" login the "role" claim comes back fine.  (Note: I do see the role claim missing from the context in the error scenario).
Here is my client application configuration:
services.AddAuthentication(authOpts =>
        {
            authOpts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            authOpts.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, opts => { })
        .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, openIdOpts =>
        {
            openIdOpts.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            openIdOpts.Authority = settings.IDP.Authority;
            openIdOpts.ClientId = settings.IDP.ClientId;
            openIdOpts.ClientSecret = settings.IDP.ClientSecret;
            openIdOpts.ResponseType = settings.IDP.ResponseType;

            openIdOpts.GetClaimsFromUserInfoEndpoint = true;
            openIdOpts.RequireHttpsMetadata = false;
            openIdOpts.SaveTokens = true;
            openIdOpts.ResponseMode = "form_post";

            openIdOpts.Scope.Clear();
            settings.IDP.Scope.ForEach(s => openIdOpts.Scope.Add(s));

            // https://leastprivilege.com/2017/11/15/missing-claims-in-the-asp-net-core-2-openid-connect-handler/
            // https://github.com/aspnet/Security/issues/1449
            // https://github.com/IdentityServer/IdentityServer4/issues/1786

            // Add Claim Mappings
            openIdOpts.ClaimActions.MapUniqueJsonKey("preferred_username", "preferred_username"); /* SID alias */
            openIdOpts.ClaimActions.MapJsonKey("role", "role", "role");

            openIdOpts.TokenValidationParameters = new TokenValidationParameters
            {
                ValidAudience = settings.IDP.ClientId,
                ValidIssuer = settings.IDP.Authority,
                NameClaimType = "name",
                RoleClaimType = "role"
            };

            openIdOpts.Events = new OpenIdConnectEvents
            {
                OnUserInformationReceived = context =>
                {
                    Log.Info("Recieved user info from IDP.");
                    // check for missing roles?  they are here on a fresh login but missing
                    // after x amount of time (1 hour?)
                    return Task.CompletedTask;
                },
                OnRedirectToIdentityProvider = context =>
                {
                    Log.Info("Redirecting to identity provider.");
                    return Task.CompletedTask;
                },
                OnTokenValidated = context =>
                    {
                        Log.Debug("OnTokenValidated");
                        // this addressed the scenario where the Identity Server validates a user however that user does not
                        // exist in the currently configured source system.
                        // Can happen if there is a configuration mismatch between the local SID system and the IDP Client
                        var validUser = false;
                        int uid = 0;
                        var identity = context.Principal?.Identity as ClaimsIdentity;

                        if (identity != null)
                        {
                            var sub = identity.Claims.FirstOrDefault(c => c.Type == "sub");

                            Log.Debug($"    Validating sub '{sub.Value}'");

                            if (sub != null && !string.IsNullOrWhiteSpace(sub.Value))
                            {

                                if (Int32.TryParse(sub.Value, out uid))
                                {
                                    using (var configSvc = ApiServiceHelper.GetAdminService(settings))
                                    {
                                        try
                                        {
                                            var usr = configSvc.EaiUser.GetByID(uid);

                                            if (usr != null && usr.ID.GetValueOrDefault(0) > 0)
                                                validUser = true;
                                        }
                                        catch { }
                                    }
                                }
                            }

                            Log.Debug($"    Validated sub '{sub.Value}'");
                        }

                        if (!validUser)
                        {
                            // uhhh, does this work?  Logout?
                            // TODO: test!
                            Log.Warn($"Unable to validate user is SID for ({uid}).  Redirecting to '/Home/Logout'");
                            context.Response.Redirect("/Home/Logout?msg=User not validated in source system");
                            context.HandleResponse();
                        }

                        return Task.CompletedTask;
                    },
                OnTicketReceived = context =>
                {
                    // TODO: Is this necessary?
                    // added the below code because I thought my application access_token was expired
                    // however it turns out I'm actually misisng the role claims when I come back to the
                    // application from the IDP after about an hour
                    if (context.Properties != null &&
                        context.Properties.Items != null)
                    {
                        DateTime expiresAt = System.DateTime.MinValue;

                        foreach (var p in context.Properties.Items)
                        {
                            if (p.Key == ".Token.expires_at")
                            {
                                DateTime.TryParse(p.Value, null, DateTimeStyles.AdjustToUniversal, out expiresAt);
                                break;
                            }
                        }

                        if (expiresAt != DateTime.MinValue &&
                            expiresAt != DateTime.MaxValue)
                        {
                            // I did this to synch the .NET cookie timeout with the IDP access token timeout?
                            // This somewhat concerns me becuase I thought that part should be done auto-magically already
                            // I mean, refresh token?
                            context.Properties.IsPersistent = true;
                            context.Properties.ExpiresUtc = expiresAt;
                        }
                    }

                    return Task.CompletedTask;
                }
            };
        });

A: I'm sorry folks, looks like I found the source of my issue.
Total fail on my side :(.
I had a bug in the ProfileService in my Identity Server implementation that was causing the roles to not be returned in all cases
humph, thanks!


text:
Q: I am working with a large dataset, RStudio slows down and goes back to normal after I restart it Is there a another way to get RStudio running at normal speed once it starts lagging other than having to restart?
I am working with large datasets and understand that is expected.  However a simple command like 2000 + 2000 starts running with a lag, and once I restart RStudio the speed goes back to normal.  I think that RStudio starts running with a lag once if I run a command that asks R to display 1000's of entries.  It is annoying as heck and would appreciate some feedback and comments, Thanks.


text:
Q: Can we use my own crate repository url in Cargo.toml to download the dependencies I have my own repository, where I have list of rust crates. When I run the command "cargo run", i want cargo to download all the dependencies from my crate repository url instead of crates.io. To achieve this what configuration need to be done
Looking for some suggestion or code snippet for the same


text:
Q: The image does not show up when I run this Python code in Ubuntu Is there something wrong with this code? It doesn't say there are any errors but the 'img' variable never shows at the end.
import Image
import ImageDraw

def main():
    b = 4
    size = 25
    fig_width = size
    fig_height = size

    white_rgb = (255, 255, 255)
    black_rgb = (0, 0, 0)
    img = Image.new("RGB", (fig_width, fig_height), white_rgb)
    draw = ImageDraw.Draw(img)

    for i in range(0, size, 5):
        for j in range(0, size, 5):
            if i % 2 == j % 2:
                draw.rectangle([(j, i), (j + b, i + b)], black_rgb)
    img.show()

main()

A: PIL will try to use the ImageMagick display utility or xv to display images. If it cannot find either, it will fail silently.  Try installing the imagemagick Ubuntu package and then run the script again.


text:
Q: ggplot renaming facet labels in facet_wrap I've hit a stumbling block in writing a ggplot function. I'm trying to change the facet labels in a ggplot facet_wrap plot.... but its proving trickier than I though it would be....
The data I am using can be accessed here
str(ggdata)
'data.frame':   72 obs. of  8 variables:
 $ Season : Factor w/ 3 levels "Autumn","Spring",..: 2 2 2 2 2 2 2 2 2 2 ...
 $ Site   : Factor w/ 27 levels "Afon Cadnant",..: 13 13 13 13 13 13 13 13 13 13 ...
 $ Isotope: Factor w/ 4 levels "14CAA","14CGlu",..: 1 1 1 1 1 1 2 2 2 2 ...
 $ Time   : int  0 2 5 24 48 72 0 2 5 24 ...
 $ n      : int  3 3 3 3 3 3 3 3 3 3 ...
 $ mean   : num  100 88.4 80.7 40.5 27.6 ...
 $ sd     : num  0 1.74 2.85 2.58 2.55 ...
 $ se     : num  0 1 1.65 1.49 1.47 ...

I have written the following function to create the ggplot which uses the Isotope factor levels to label the facets:
plot_func <- function(T) {site_plots <- ggplot(data = T) + geom_point(aes(Time, mean, colour = Season, shape = Season)) +
  geom_line(aes(Time, mean, colour = Season, linetype = Season)) +
  geom_errorbar(aes(Time, mean, ymax = (mean + se), ymin = (mean - se)), width = 2) +
  labs(title = T$Site[1], y = "Percentage of isotope remaining in solution", x = "Time (h)") +
  scale_x_continuous(breaks=c(0, 24, 48, 72)) +
  scale_y_continuous(limits=c(0,115), breaks = c(0,25,50,75,100)) +
  theme(axis.title.y = element_text(vjust = 5)) +
  theme(axis.title.x = element_text(vjust = -5)) + theme(plot.title =  element_text(vjust = -10)) +
  theme_bw() + facet_wrap(~Isotope, ncol =2)
  print(site_plots)
  ggsave(plot = site_plots, filename = paste(T$Site[1], ".pdf"),
     path = "C:/Users/afs61d/Dropbox/Academic/R/Practice datasets/Helens_data/Site_Isotope_Season_plots/",
     width = 9, height = 7, dpi = 300)}

Resulting in this lovely graph:

Which is nice but I want to change the facet labels now...
Having done some poking around google I thought I might be able to use the labeller function as an argument to pass to facet_wrap. After a frustrating hour I discovered that this only works with facet_grid!!!???
So, an alternative method was to change the Factor level names so give me the facet labels that I want::
 gdata$Isotope <- revalue(x = ggdata$Isotope,
c("14CAA" = " 14C Amino Acids", "14CGlu" = "14C Glucose",
  "14cGlu6P" = "14C Glucose-6-phosphate", "33P" = "33P Phosphate"))

This works, but the problem I have now is that I want the numbers in the labels to be super-scripted. Can anyone suggest the best way to achieve this?
Thanks

A: Manage to sort it out!
Had trouble installing the development version of ggplot but after installing curl and devtools and reinstalling scalesit worked. I tried @eipi10 answer but couldn't get that to work so I changed the factor label names in a different way:
ggdata$Isotope <- factor(ggdata$Isotope, labels = c("NULL^14*C~Amino~Acids",
"NULL^14*C~Glucose", "NULL^14*C~Glucose-6-phosphate", "NULL^33*P~Phosphate"))

I then adjusted the ggplot function to pass labeller = label_parsed to the facet_wrap function:
plot_func <- function(T) {site_plots <- ggplot(data = T) + geom_point(aes(Time, mean, colour = Season, shape = Season)) +
  geom_line(aes(Time, mean, colour = Season, linetype = Season)) +
  geom_errorbar(aes(Time, mean, ymax = (mean + se), ymin = (mean - se)), width = 2) +
  labs(title = T$Site[1], y = "Percentage of isotope remaining in solution", x = "Time (h)") +
  scale_x_continuous(breaks=c(0, 24, 48, 72)) +
  scale_y_continuous(limits=c(0,115), breaks = c(0,25,50,75,100)) +
  theme(axis.title.y = element_text(vjust = 5)) +
  theme(axis.title.x = element_text(vjust = -5)) + theme(plot.title = element_text(vjust = -10)) +
  theme_bw() + facet_wrap(~Isotope, ncol =2, labeller = label_parsed)
  print(site_plots)
  ggsave(plot = site_plots, filename = paste(T$Site[1], ".pdf"),
     path = "C:/Users/afs61d/Dropbox/Academic/R/Practice datasets/Helens_data/Site_Isotope_Season_plots/",
     width = 9, height = 7, dpi = 300)}

Passing the ggdata to the plot_func gives me the below graphs with the correct facet labels.

A: Set the facet labels to the appropriate expressions, then use the labeller function label_parsed to ensure that they are displayed properly. Here's an example, using the built-in iris data frame:
data(iris)
iris$Species = as.character(iris$Species)
iris$Species[iris$Species == "virginica"] = "NULL^14*C~Amino~Acids"

ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
  geom_point() +
  facet_wrap(~ Species, labeller=label_parsed)

You need to add the NULL before ^14*C or you'll get an error due to having ^ as the initial character. * and ~ mark the boundaries of each part of the expression, depending on whether you don't or do want a space between each part.
As of this writing (Dec. 12, 2015), you need to use the development version of ggplot2 for this to work with facet_wrap. However, this feature will presumably soon be incorporated into a regular release of the package.


text:
Q: confusion about asynchronous programming class Program
{
    public delegate void ss(string s);

    public static void print(string s)
    {
        Console.WriteLine("asynchronous thread..."+s+DateTime.Now.ToLongTimeString());
        System.Threading.Thread.Sleep(3000);
    }

    static void Main(string[] args)
    {
        ss s = print;

        Console.WriteLine("Main thread..." + DateTime.Now.ToLongTimeString());

        IAsyncResult result = s.BeginInvoke("hello", null, null);

        for (int i = 0; i < 50; i++)
        {
            Console.WriteLine("Main...thread..."+DateTime.Now.ToLongTimeString());
        }

        System.Threading.Thread.Sleep(3000);

        Console.WriteLine("Main...thread...after sleep" + DateTime.Now.ToLongTimeString());
        Console.WriteLine("Main...thread...after sleep..." + DateTime.Now.ToLongTimeString());

        s.EndInvoke(result);

Output is:
Main thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
**asynchronous thread...hello 4:20:01 PM**
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
**Main...thread...after sleep4:20:04 PM**
**Main...thread...after sleep...4:20:04 PM**

My question is why sleep method doesn't count in asynchronous method?

A:
My question is why sleep method doesn't count in asynchronous method?

It does encounter. After writing line asynchronous thread...hello 4:20:01 PM your background thread goes to sleep, but main thread continues to print messages. Add message after background thread has awaken to see that Sleep worked:
public static void print(string s)
{
    Console.WriteLine("async thread..." + s + DateTime.Now.ToString("T"));
    System.Threading.Thread.Sleep(2000);
    Console.WriteLine("async thread after sleep " + DateTime.Now.ToString("T"));
}


text:
Q: DateTime conversion with Timezone information C#
Possible Duplicate:
Parse DateTime with timezone of form PST/CEST/UTC/etc

I have a datetime string = "10/09/2012 5:00 pm PST" How do I convert this into DateTime using DateTime.ParseExact(). I am looking for the literal that will match PST or EST.

A: Replace the PST with the UTC offset, I think it should work:
string value = "10/09/2012 5:00 pm PST";
value = value.Replace ("PST", "−8");

DateTime.ParseExact (value, "M/d/yyyy h:mm tt z", Culture....);


text:
Q: Promises in functions, angularjs How to implement promise into function so i can get rid off timeout, if it is even possible? I'm getting some data from factory 'Prim',function look's like :
$scope.getPre = function(id){

 var url = WEB_API.MainUrl + '/api/prim/' + id +'/' + $window.sessionStorage.getItem('idsom');

    Prim.getprim(function(data) {

        $scope.prim1 = data;
        $scope.prim = $scope.prim1[0];

    }, url);

    $scope.$apply();

}

and the timeout i want to rid off :
setTimeout(function() { // it can't work without timeout
    $scope.getPre($routeParams.idprim);
}, 100);

A: Your function should return a promise, so you could use .then() on it:
$scope.getPre = function(id){
    var deferred = $q.defer()
    var url = WEB_API.MainUrl + '/api/prim/' + id +'/' + $window.sessionStorage.getItem('idsom');

    Prim.getprim(function(data)
        $scope.prim1 = data;
        $scope.prim = $scope.prim1[0];
        deferred.resolve();
    }, url);

    return deferred.promise;
}

And then just use it like this:
$scope.getPre($routeParams.idprim).then(function () {
    // Do whatever you did after setTimeout
});


text:
Q: Swipe to accept animation in SwiftUI I want to create a swipe to accept gesture in SwiftUI.

For example, in this image, if you swipe to the left, a green rectangle would show and say something like "accepted". However, you can swipe right and the black rectangle would return to its original position.

A: You can make a swipe to action button like this. You can customize and optimize code as per your requirement.
Tested in XCode 12.3 with iOS 14.3
typealias FrontView<V> = Group<V> where V:View
typealias BackView<V> = Group<V> where V:View

struct SwipeButton<Content: View, BackContent: View>: View {

    private var content: () -> TupleView<(FrontView<Content>, BackView<BackContent>)>
    @State private var offset = CGSize.zero

    private let onAction: () -> ()

    init(@ViewBuilder content: @escaping () -> TupleView<(FrontView<Content>, BackView<BackContent>)>, onAction: @escaping () -> Void) {
        self.content = content
        self.onAction = onAction
        self.content = content
    }

    var body: some View {
        let (frontView, backView) = self.content().value

        return GeometryReader { (geometry) in
            ZStack {
                backView
                frontView
                    .offset(self.offset)
                    .gesture(DragGesture(minimumDistance: 30, coordinateSpace: .local)
                                .onChanged { gestrue in
                                    if gestrue.translation.width < 0  {
                                        self.offset.width = gestrue.translation.width
                                    }
                                    print(offset)
                                }
                                .onEnded { value in
                                    if value.translation.width < 0 {
                                        self.offset.width -= geometry.size.width
                                        onAction()
                                    }
                                }
                    )
            }
        }
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
        .animation(.spring())
    }
}

Usage
struct SwipeDemoView: View {
    var body: some View {
        SwipeButton {
            // Add your fron view
            FrontView {
                Text("Swipe").frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(Color.black).foregroundColor(Color.white)
            }
            // Add your back view
            BackView {
                Text("Accepted")
                    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
                    .background(Color.green)
            }
        } onAction: {
            print("Swiped...")
        }
        .frame(width: 200, height: 50)
        .cornerRadius(15)
    }
}


text:
Q: Is there a way to relate prime numbers and the Fourier transform? According to what I know about Fourier transforms, any continuous periodic signal can be represented as a combination of sine and cosine functions. To me, this looks analogous to the fundamental theorem of arithmetic (every integer $\ge 2$ can be represented as a unique product of primes) where the integer is the signal and the primes are the sine and cosine.
Any ideas of way to connect the Fourier transform with prime factorization?

P.S. I found this paper that does something close.

A: The question is quite broad, but here is a possible relation between Fourier transformation and prime numbers.
We know that the Riemann zeta function is defined as
$$\zeta(s) = \sum_{n=1}^\infty\frac{1}{n^s},$$
for all $\Re(s)>1$.
The second thing, that the Riemann zeta function is related to prime numbers via Euler product formula.
$$\zeta(s)=\sum_{n=1}^\infty\frac{1}{n^s} = \prod_{p \text{ prime}} \frac{1}{1-p^{-s}},$$
for all $\Re(s)>1$.
As a generalization of Riemann zeta function the Hurwith zeta function is defined as
$$\zeta(s,q) = \sum_{n=0}^\infty \frac{1}{(q+n)^{s}},$$
for all $\Re(s)>1$ and $\Re(q)>0$. The Riemann zeta function is $\zeta(s,1)$.
Another way to generalize Riemann zeta function is using polylogarithm, which is defined as
$$\operatorname{Li}_s(z) = \sum_{k=1}^\infty {z^k \over k^s}.$$
For $\Re(s)>1$ we have $\operatorname{Li}_s(1)=\zeta(s)$. Is is also true, that $\operatorname{Li}_s(-1)= (2^{1-s}-1)\zeta(s)$.
The sequence of $N$ complex numbers $x_0,x_1,\dots,x_{N-1}$ is transformed with discrete Fourier transformation into an $N$-periodic sequence of complex numbers with
$$X_k\ =\ \sum_{n=0}^{N-1} x_n \cdot e^{-i 2 \pi k n / N},  \quad k\in\mathbb{Z}\,.$$
Of course by using Euler's formula we could also use trigonometric functions.
Here comes the connection. The discrete Fourier transform of the Hurwitz zeta function with respect to the order $s$ is the Legendre chi function, which is defined as
$$\chi_s(z) = \sum_{k=0}^\infty \frac{z^{2k+1}}{(2k+1)^s}.$$
The Legendre chi function is related to polylogarithms as the following.
$$\chi_s(z) = \frac{1}{2}\left[\operatorname{Li}_s (z) - \operatorname{Li}_s (-z)\right].$$
So it is also true that
$$\chi_s(1) = (1-2^{-s})\zeta(s),$$
for all $s>0$ real numbers.
So if we put this all together.
$$\prod_{p \text{ prime}} \frac{1}{1-p^{-s}} \stackrel{\text{DFT}}{\implies} (1-2^{-s})\prod_{p \text{ prime}} \frac{1}{1-p^{-s}},$$
for all $s>0$ real numbers.
I hope that my argument is right, it's just've come into my mind while reading your question. While doing the DFT at the end we've substituted $z=1$ into Legrende chi function.

A: It is not that logical to represent primes using Fourier transform directly. Fourier transform has linearity in mind and there is some linearity but not the one that can be easily exploited among primes.
At first, it looks like sieving, when you cross every second then every third then every fifth number and so on, is linear in nature, right? But this is just hiding a painful truth that $2 \cdot 3 = 6$ and that $2+3$ is not revealing anything regarding the composition of $5$.
If you start that every number can be represented uniquely as a product of primes
$$n=\prod_{k=1}^{\omega(n)}p_{m_k}^{\alpha_k}$$
you obtain intended linearity using
$$\ln(n)=\sum_{k=1}^{\omega(n)}\alpha_k\ln(p_{m_k})$$
Technically if you allow $\alpha_k=0$ you have
$$\ln(n)=\sum_{k=1}^{+\infty}\alpha_k\ln(p_k)$$
where $\alpha_k=0$ means that $p_k$ is not a factor of $n$, that $n$ is not divisible by $p_k$.
This, observing prime numbers using logarithmic scale, is bringing you to a cousin of Fourier transform, which is the Mellin transform. To illustrate it, we will use Gamma function, the extension of factorial, so if $f(x)=e^{-x}$ then its Mellin transform is the Gamma function
$$\Gamma(s) = \int_0^\infty e^{-x}x^{s-1} dx$$
We can define Fourier transform using Mellin transform, true, but you inevitably grab for logarithmic scaling in the process.
To understand why Mellin tastes better, we define Riemann zeta function as Mellin transform of another function $f(x)=\frac1{e^x-1}$ i.e.:
$$\zeta(s) = \frac1{\Gamma(s)}\int_0^\infty \frac1{e^x-1}x^{s-1} dx$$
To understand how intimate this function is to the primes, a few relations:
$$\ln\zeta(s) = s\int_0^\infty \frac{\pi(x)}{x(x^s-1)} dx$$
$$\frac{1}{\zeta(s)}=\sum_{n=1}^\infty \frac{\mu(n)}{n^s}$$
$$\zeta^2(s) =\sum_{n=1}^\infty \frac{d(n)}{n^s}$$
$$-\frac{\zeta'(s)}{\zeta(s)} = \sum_{n=1}^\infty \frac{\Lambda(n)}{n^s}$$
$$\frac{\zeta^2(s)}{\zeta(2s)} = \sum_{n=1}^\infty \frac{2^{\omega(n)}}{n^s}$$
where
$\pi(x)$ is number of primes up to $x$
$\mu(n)$ is Möbius function equal to $0$ if $n$ is divisible by square otherwise $1$ if it has even and $-1$ if it has odd number of prime factors
$d(n)$ is number of divisors of $n$
$\Lambda(n)$ is the von Mangoldt function equal to $\ln(p)$ if the number $n$ is $n=p^k$ otherwise $0$
$\omega(n)$ is the number of distinct prime factors of $n$
and many more relations like these.
Again, we are not far away from Fourier transform, we are just basically scaling it in order to extract multiplicative essence. Pure Fourier transform might connect two multiplicative relations related to primes, but to dig very deep into the primes we need related Mellin transform.
Regarding prime factorization, there is not much there where Fourier transform is directly involved. The problem is so complex that techniques are bordering with mathematical limits not rarely using guessing and heuristics even when the factorization is expect to run very fast and when the algorithm is quite precise and sound.
Still if you look back at the Riemann zeta function defined above as
$$\zeta(s)=\sum_{n=1}^{\infty} n^{-s} = \prod_{p \text{ is prime}}\frac1{1-p^{-s}}$$
you have readily available factorization of each $n$, albeit you cannot extract it directly. Because Riemann zeta function is intimately related to other arithmetic functions, all you need is to be able to extract $n^{th}$ coefficient of any interesting sum:
$$f(s)=\sum_{n=1}^{\infty}\frac{a_n}{n^s}$$
and that would be
$$\frac{a_n}{n^{\sigma}} = \lim_{T\to\infty} \frac{1}{2T} \int_{-T}^{T} f(\sigma+ it)n^{it} \mathrm{d}t$$
and you can obtain sufficient information about factorization to start the actual factorization. This is not the fastest possible known way, but it is the way that is relating Fourier, i.e. Mellin transform, with the factorization process more directly than with other known methods.


text:
Q: How to call method recursively in typescript I want to call the filterArr inside the filterArr. Here is my implementation.
 filterArr(array, search) {
        var result = [];
        array.forEach((a)=> {
            var temp = [],
                 o = {},
                found = false;

            if (a.name === search) {
                this.o.name = a.name;
                found = true;
            }
            if (Array.isArray(a.children)) {
                temp = this.filterArr(a.children, search);//***Cannot read property 'filterArr' of undefined***
                if (temp.length) {
                    this.o.children = temp;
                    found = true;
                }
            }
            if (found) {
                result.push(o);
            }
        });
        return result;
    }

How to call the filterArr method without any error?

A: You have to use Arrow function to get hold on correct this, so you need to change array.forEach(function (a) { to use `Arrow function
array.forEach((a) => {


text:
Q: WFFM sitecore module installation - bin\System.Data.SQLite.x32 access denied I'm trying to install the WFFM module for sitecore, After the installation is complete and the placeholder settings are provided i get the following error

Access to the path
  'C:\Inetpub\wwwroot\XXXXX\Website\bin\System.Data.SQLite.x32' is
  denied

So the WFFM database is not created under web root /data folder (I guess)
I'm having hard time understanding the issue.

A: It seems like you have a permissions issue, make sure your IUSR or NETWORK SERVICE has modify permissions set on your \bin directory. Part of the post-install step of the WFFM module is to copy across the correct version of the SQLite dll, based on whether you are using x86 or x64 architecture.
You can rectify this manually by renaming System.Data.SQLite.x32 to System.Data.SQLite.dll in the bin directory. If you on a x64 system then copy across the dll from the bin_x64 instead.
I would suggest rather than using SQLite that you:

*

*Attach or restore the backup of the WebForms databases located in /data to SQL Server (personally I move these to the same location as the other Sitecore databases)

*Add a connection string named wfm in connectionStrings.config with the correct connection details

*or, modify the <formsDataProvider> in forms.config

If you need to run the Restricting Placeholders wizard again then click
Sitecore > All Applications > Web Forms for Marketers > Restricting Placeholders.
See section 3.4.2 of the WFFM reference.


text:
Q: How to model a skewed Student's t disribution I have a small number of samples (5) of a large population (~10,000). The samples are percentages and hence I know from the context that no answers are possible below 0% or above 100%. From this one set of samples I've calculated my t statistic and confidence intervals; however, for anything above 95% confidence my interval width is such that the predicted upper limit is above 100.
My understanding is that is you have specific knowledge like this you can create a skewed Student's t distribution. First, is this correct? Second, how would this apply to the upper and lower limits of my confidence interval? I understand that two values are important in calculating this, the skewness and kurtosis, but I'm not sure how to use them.
My skewness value: -1.82
My kurtosis value: 3.448
Sample Values:
79.465
91.905
91.096
88.144
90.599

A: Here's a simple Monte Carlo simulation. Assuming that the population distribution is Beta with parameters 80 and 1.1, I draw samples of 5 observations, then plot the histogram of their mean.
x=mean(100*betarnd(80,1.1,5,100000));
subplot(2,1,1)
plot([94:0.01:100],betapdf([94:0.01:100]/100,80,1.1))
title 'Population distribution'
subplot(2,1,2)
histfit(x,40,'t')
title 'Sample mean'

You can see that the sample mean does not fit neither normal nor t-distribution, so t-statistics would be useless. I don't think that you can derive the distribution of the sample mean without knowing something about the distribution of the population beyond its bounds. Your sample variance is 26, i.e. too high relative to the size of the population and its bounds in order to apply CLT here or other asymptotic analysis reliably.
Now if instead of assuming some random population distribution, let's fit Beta distribution to your data.
xp=[79.465
91.905
91.096
88.144
90.599]

% fit Beta distribution to the sample
ab=betafit(xp/100)
% generate many samples of 5 observations
x=mean(100*betarnd(ab(1),ab(2),5,100000));

subplot(2,1,1)
plot([0:0.01:100],betapdf([0:0.01:100]/100,ab(1),ab(2)))
title 'Population PDF'
subplot(2,1,2)
histfit(x,40,'tLocationScale')
title 'Sample mean distribution'

phat=mle(x,'distribution','tlocationscale')
pd = makedist('tLocationScale','mu',phat(1),'sigma',phat(2),'nu',phat(3))
disp 'Conf. intervals of population mean'
pd.icdf([0.025 0.975])

This gives an output:
pd =

  tLocationScaleDistribution

  t Location-Scale distribution
       mu = 88.2223
    sigma = 1.82489
       nu = 89.9698

Conf. intervals of population mean

ans =

   84.5968   91.8478

The 95% confidence interval seems reasonable, but the t Distribution fit is not so good, it's not skewed as the sample mean distribution. You could do something along this line, so long that you have a good idea about the population distribution. I still don't tink that the confidence interval would be reliable given the tiny size of the sample and its high variance.