text:
Q: Navigate WebBrowser from list when I launch this program I get in MessageBox only http://www.google.com, but
I should get http://www.yahoo.com and after that http://www.google.com. So, where is a problem? So, can you help me fix this problem? Thank you :)
There is a XAML code:
<Window x:Class="WpfApplication19.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="800" Width="800">
<Grid Name="grid">
    <Button Name="btn" Content="Navigate" HorizontalAlignment="Left" Margin="697,223,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
    <Button Name="shower" Content="getValues" HorizontalAlignment="Left" Margin="697,262,0,0" VerticalAlignment="Top" Width="75" Click="shower_Click"/>
</Grid></Window>

and there is C# short code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using mshtml;

namespace WpfApplication19
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<string> list = new List<string>();
        private List<string> arrOfAdresses = new List<string>();
        private WebBrowser thisIsWeb;
        public MainWindow()
        {
            InitializeComponent();
            list.Add("http://www.yahoo.com");
            list.Add("http://www.google.com");
            thisIsWeb = new WebBrowser();
            thisIsWeb.Width = thisIsWeb.Height = 400;
            this.grid.Children.Add(thisIsWeb);
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            foreach (string s in list)
            {
                thisIsWeb.Navigate(s);
                thisIsWeb.LoadCompleted += OnthisIsWebCompleted;
            }
        }

        private void OnthisIsWebCompleted(object sender, NavigationEventArgs e)
        {
            WebBrowser bro = sender as WebBrowser;
            this.arrOfAdresses.Add(bro.Source.ToString());
        }

        private void shower_Click(object sender, RoutedEventArgs e)
        {
            foreach (string s in arrOfAdresses)
                MessageBox.Show(s);
        }
    }
}

A: Well simple:
You are using the LoadCompleted to populate arrOfAdresses. Calling navigate does not guarantee LoadCompleted to be called! LoadCompleted is called - as the name suggests - as soon as the page you navigated to is loaded.
Since you navigate to two different urls immediately after each other, only the last call to Navigate will actually cause a website to be loaded - the prior navigations are implicitly "aborted" by the next call to Navigate.
So the only website that is loaded successfully (and therefore raises LoadCompleted) is http://www.google.com.


text:
Q: How do you set the last 'div' in another 'div' at the end flexbox? How do you set the last 'div' in another 'div' at the end with the changing number of elements in pagination? I have 12 elements.
During pagination, I have set the number of items for example 5 when I'm on the first page. Go to the second page I have 5 elements. Go to the third page I have two elements and here is the problem because

moves up, and I would like him to stay in the same place in down

    .artistsSection {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      text-align: center;
      align-items: center;
    }

    .pagination {
      margin: 0;
      padding: 10px;
      font-size: 10px;
      display: flex;
      align-self: flex-end;
    }

List

            <input />

I want to use flexbox.

A: There is no equivalent for align-self on the main axis (like justify-self).
Instead, you could do something like:
.Section {
  height: 100%;
  display: flex;
  flex-direction: column;
  text-align: center;
  align-items: center;
}

.pagination {
  margin: 0;
  padding: 10px;
  font-size: 10px;
  display: flex;
  margin-top: auto;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to take a screenshot of a current Activity and then share it? I need to take a screenshot of Activity (without the title bar, and the user should NOT see that a screenshot has actually been taken) and then share it via an action menu button "share". I have already tried some solutions, but they didn't work for me. Any ideas?

A: You can the below code to get the bitmap for the view you are seeing on screen You can specify which view to create bitmap.
    public static Bitmap getScreenShot(View view) {
           View screenView = view.getRootView();
           screenView.setDrawingCacheEnabled(true);
           Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
           screenView.setDrawingCacheEnabled(false);
           return bitmap;
     }

A: I couldn't get Silent Knight's answer to work to work until I added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

to my AndroidManifest.xml.

A: You can take screenshot of any portion of your view.You just need the reference of the layout of which you want the screenshot. for example in your case you want the screen shot of your activity. let assume that your activity root layout is Linear Layout .
   // find the reference of the layout which screenshot is required

     LinearLayout LL = (LinearLayout) findViewById(R.id.yourlayout);
      Bitmap screenshot = getscreenshot(LL);

     //use this method to get the bitmap
      private Bitmap getscreenshot(View view) {
        View v = view;
        v.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
        return bitmap;
      }

A: for taking screenshot
 public Bitmap takeScreenshot() {
    View rootView = findViewById(android.R.id.content).getRootView();
    rootView.setDrawingCacheEnabled(true);
    return rootView.getDrawingCache();
}

for saving screenshot
private void saveBitmap(Bitmap bitmap) {
    imagePath = new File(Environment.getExternalStorageDirectory() + "/scrnshot.png"); ////File imagePath
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }
}

and for sharing
private void shareIt() {
    Uri uri = Uri.fromFile(imagePath);
    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType("image/*");
    String shareBody = "My highest score with screen shot";
    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Catch score");
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
    sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(sharingIntent, "Share via"));
}

and simply in the onclick you can call these methods
shareScoreCatch.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Bitmap bitmap = takeScreenshot();
        saveBitmap(bitmap);
        shareIt();
   }
});

A: as of 2021 here is complete answer you would only copy past this code and it should work fine with you, also it uses all the new API including permission launchers, and android q way of saving images
I will be adding one more functionality which is saving inside folder inside Picture folder like this
/Pictures/MyAppName/photos.png

also this code is supporting android < 10 as well as the newer one.
i am making a screen shoot and saving it to desk to get uri of the image, to be able to share it later.
first, permission launcher is required on android < 10
val requestStoragePermissionLauncher =
    registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        var saveImageFlag = true
        permissions.entries.forEach {
            saveImageFlag = it.value
        }
        if (saveImageFlag) {
            shareScreenShootResult()
        } else {
            showMessage(getString(R.string.cant_share_ScreenShoot))
        }
    }

val permissionListener: () -> Boolean = {
    if (ContextCompat.checkSelfPermission(
            requireContext(),
            Manifest.permission.READ_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(
            requireContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
    ) {
        true
    } else {
        requestStoragePermissionLauncher.launch(
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        )
        false
    }
}

then the next method gives the image name and set the directory and then share the image
private fun shareScreenShootResult() {
    val dateFormatter by lazy {
        SimpleDateFormat(
            "yyyy.MM.dd 'at' HH:mm:ss z", Locale.getDefault()
        )
    }
    val filename = "${getString(R.string.my_ScreenShoot)}${dateFormatter.format(Date())}.png"
    val ScreenShootFolderPath = File.separator + requireContext().getAppName()

    val uri = binding.rootLayout.makeScreenShot()
        .saveScreenShot(requireContext(), filename, ScreenShootFolderPath, permissionListener)
        ?: return

    dispatchShareImageIntent(uri)
}

private fun dispatchShareImageIntent(screenShotUri: Uri) {
    val intent = Intent(Intent.ACTION_SEND)
    intent.type = "image/png"
    intent.putExtra(Intent.EXTRA_STREAM, screenShotUri)
    startActivity(Intent.createChooser(intent, "Share"))
}

getAppName is an extention funtion, you can add it anywhere in your project then call it on context, do not forget to import it.
fun Context.getAppName(): String {
    var appName: String = ""
    val applicationInfo = applicationInfo
    val stringId = applicationInfo.labelRes
    appName = if (stringId == 0) {
        applicationInfo.nonLocalizedLabel.toString()
    } else {
        getString(stringId)
    }
    return appName
}

this method makeScreenShot is extension function on the View
you better add all extension functions in different file.
fun View.makeScreenShot(): Bitmap {
    setBackgroundColor(Color.WHITE)
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    draw(canvas)
    return bitmap
}

it returns bitmap on which i am calling saveScreenShot which is another extenion function
fun Bitmap.saveScreenShot(
    requireContext: Context,
    filename: String,
    ScreenShootFolderPath: String,
    permissionListener: () -> Boolean,
): Uri? {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
        saveImageInQ(this, filename, ScreenShootFolderPath, requireContext.contentResolver)
    else
        legacySave(this, filename, ScreenShootFolderPath, permissionListener)
}

private fun saveImageInQ(
    bitmap: Bitmap,
    filename: String,
    parentFileName: String,
    contentResolver: ContentResolver
): Uri? {
    val fos: OutputStream?
    val uri: Uri?
    val contentValues = ContentValues()
    contentValues.apply {
        put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
        put(MediaStore.Files.FileColumns.MIME_TYPE, "image/png")
        put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + parentFileName)
        put(MediaStore.MediaColumns.IS_PENDING, 1)
    }

    uri =
        contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
    uri?.let { contentResolver.openOutputStream(it) }.also { fos = it }

    fos?.use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
    fos?.flush()
    fos?.close()

    contentValues.clear()
    contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0)
    uri?.let {
        contentResolver.update(it, contentValues, null, null)
    }
    return uri
}

private fun legacySave(
    bitmap: Bitmap,
    filename: String,
    parentFileName: String,
    permissionListener: () -> Boolean,
): Uri? {
    val fos: OutputStream?
    if (!permissionListener()) {
        return null
    }

    val path =
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() +
                parentFileName + File.separator + filename
    val imageFile = File(path)
    if (imageFile.parentFile?.exists() == false) {
        imageFile.parentFile?.mkdir()
    }
    imageFile.createNewFile()
    fos = FileOutputStream(imageFile)
    val uri: Uri = Uri.fromFile(imageFile)

    fos.use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
    fos.flush()
    fos.close()

    return uri
}

A: For all the Xamarin Users:
Xamarin.Android Code:
Create an external Class (I have an interface for each platform, and I implemented those 3 below functions from android platform):
    public static Bitmap TakeScreenShot(View view)
    {
        View screenView = view.RootView;
        screenView.DrawingCacheEnabled = true;
        Bitmap bitmap = Bitmap.CreateBitmap(screenView.DrawingCache);
        screenView.DrawingCacheEnabled = false;
        return bitmap;
    }
    public static Java.IO.File StoreScreenShot(Bitmap picture)
    {
        var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "MyFolderName";
        var extFileName = Android.OS.Environment.ExternalStorageDirectory +
                          Java.IO.File.Separator +
                          Guid.NewGuid() + ".jpeg";
        try
        {
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);

            Java.IO.File file = new Java.IO.File(extFileName);

            using (var fs = new FileStream(extFileName, FileMode.OpenOrCreate))
            {
                try
                {
                    picture.Compress(Bitmap.CompressFormat.Jpeg, 100, fs);
                }
                finally
                {
                    fs.Flush();
                    fs.Close();
                }
                return file;
            }
        }
        catch (UnauthorizedAccessException ex)
        {
            Log.Error(LogPriority.Error.ToString(), "-------------------" + ex.Message.ToString());
            return null;
        }
        catch (Exception ex)
        {
            Log.Error(LogPriority.Error.ToString(), "-------------------" + ex.Message.ToString());
            return null;
        }
    }
    public static void ShareImage(Java.IO.File file, Activity activity, string appToSend, string subject, string message)
    {
        //Push to Whatsapp to send
        Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
        Intent i = new Intent(Intent.ActionSendMultiple);
        i.SetPackage(appToSend); // so that only Whatsapp reacts and not the chooser
        i.AddFlags(ActivityFlags.GrantReadUriPermission);
        i.PutExtra(Intent.ExtraSubject, subject);
        i.PutExtra(Intent.ExtraText, message);
        i.PutExtra(Intent.ExtraStream, uri);
        i.SetType("image/*");
        try
        {
            activity.StartActivity(Intent.CreateChooser(i, "Share Screenshot"));
        }
        catch (ActivityNotFoundException ex)
        {
            Toast.MakeText(activity.ApplicationContext, "No App Available", ToastLength.Long).Show();
        }
    }`

Now, from your Activity, you run the above code like this:
                    RunOnUiThread(() =>
                {
                    //take silent screenshot
                    View rootView = Window.DecorView.FindViewById(Resource.Id.ActivityLayout);
                    Bitmap tmpPic = ShareHandler.TakeScreenShot(this.CurrentFocus); //TakeScreenShot(this);
                    Java.IO.File imageSaved = ShareHandler.StoreScreenShot(tmpPic);
                    if (imageSaved != null)
                    {
                        ShareHandler.ShareImage(imageSaved, this, "com.whatsapp", "", "ScreenShot Taken from: " + "Somewhere");
                    }
                });

Hope it will be of use to anyone.

A: create share button with click on listener
    share = (Button)findViewById(R.id.share);
    share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Bitmap bitmap = takeScreenshot();
            saveBitmap(bitmap);
            shareIt();
        }
    });

Add two methods
    public Bitmap takeScreenshot() {
    View rootView = findViewById(android.R.id.content).getRootView();
    rootView.setDrawingCacheEnabled(true);
    return rootView.getDrawingCache();
    }

public void saveBitmap(Bitmap bitmap) {
    imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }
}

Share screen shot. sharing implementation here
    private void shareIt() {
    Uri uri = Uri.fromFile(imagePath);
    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType("image/*");
    String shareBody = "In Tweecher, My highest score with screen shot";
    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Tweecher score");
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
    sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(sharingIntent, "Share via"));
    }

A: This Method Doesn't Need to Store and Retrieve Screenshot for Sharing Again.
On just Method Call you will Able to Share Screenshot.
private Bitmap screenShot(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

private void share(Bitmap bitmap){
    String pathofBmp=
            MediaStore.Images.Media.insertImage(ctx.getContentResolver(),
                    bitmap,"title", null);
    Uri uri = Uri.parse(pathofBmp);
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("image/*");
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Star App");
    shareIntent.putExtra(Intent.EXTRA_TEXT, "");
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    ctx.startActivity(Intent.createChooser(shareIntent, "hello hello"));
}

Called this Method like this
share(screenShot(view));

By using this Direct Share Screenshot without having READ & WRITE Permission

A: This is how I captured the screen and shared it.
First, get root view from current activity:
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);

Second, capture the root view:
 public static Bitmap getScreenShot(View view) {
       View screenView = view.getRootView();
       screenView.setDrawingCacheEnabled(true);
       Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
       screenView.setDrawingCacheEnabled(false);
       return bitmap;
 }

Third, store the Bitmap into the SDCard:
public static void store(Bitmap bm, String fileName){
    final static String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
    File dir = new File(dirPath);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dirPath, fileName);
    try {
        FileOutputStream fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

At last, share the screenshot of current Activity:
private void shareImage(File file){
    Uri uri = Uri.fromFile(file);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");

    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
    intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    try {
        startActivity(Intent.createChooser(intent, "Share Screenshot"));
    } catch (ActivityNotFoundException e) {
        Toast.makeText(context, "No App Available", Toast.LENGTH_SHORT).show();
    }
}

I hope you will be inspired by my code.
UPDATE:
Add below permissions into your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Because it creates and accesses files in external storage.
UPDATE:
Starting from Android 7.0 Nougat sharing file links are forbiden. To deal with this you have to implement FileProvider and share "content://" uri not "file://" uri.
Here is a good description how to do it.

A: You can try the below code to capture the screenshot of current screen and share that image without any LIBRARY & PERMISSION. I have tested this its working perfectly.
Just copy paste this.

*

*In MainAtivity.java
 public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button fullPageScreenshot, customPageScreenshot;
    private LinearLayout rootContent;
    private ImageView imageView;
    private TextView hiddenText;

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

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build());
        findViews();
        implementClickEvents();
    }
    /*  Find all views Ids  */
    private void findViews() {
        fullPageScreenshot = (Button) findViewById(R.id.full_page_screenshot);
        customPageScreenshot = (Button) findViewById(R.id.custom_page_screenshot);
        rootContent = (LinearLayout) findViewById(R.id.root_content);
        imageView = (ImageView) findViewById(R.id.image_view);
        hiddenText = (TextView) findViewById(R.id.hidden_text);
    }
    /*  Implement Click events over Buttons */
    private void implementClickEvents() {
        fullPageScreenshot.setOnClickListener(this);
        customPageScreenshot.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.full_page_screenshot:
                takeScreenshot(ScreenshotType.FULL);
                break;
            case R.id.custom_page_screenshot:
                takeScreenshot(ScreenshotType.CUSTOM);
                break;
        }
    }

    /*  Method which will take screenshot on Basis of Screenshot Type ENUM  */
    private void takeScreenshot(ScreenshotType screenshotType) {
        Bitmap b = null;
        switch (screenshotType) {
            case FULL:
                //If Screenshot type is FULL take full page screenshot i.e our root content.
                b = ScreenshotUtils.getScreenShot(rootContent);
                break;
            case CUSTOM:
                //If Screenshot type is CUSTOM
                fullPageScreenshot.setVisibility(View.INVISIBLE);//set the visibility to INVISIBLE of first button
                hiddenText.setVisibility(View.VISIBLE);//set the visibility to VISIBLE of hidden text
                 b = ScreenshotUtils.getScreenShot(rootContent);
                //After taking screenshot reset the button and view again
                fullPageScreenshot.setVisibility(View.VISIBLE);//set the visibility to VISIBLE of first button again
                hiddenText.setVisibility(View.INVISIBLE);//set the visibility to INVISIBLE of hidden text
                //NOTE:  You need to use visibility INVISIBLE instead of GONE to remove the view from frame else it wont consider the view in frame and you will not get screenshot as you required.
                break;
        }
        //If bitmap is not null
        if (b != null) {
            showScreenShotImage(b);//show bitmap over imageview
            File saveFile = ScreenshotUtils.getMainDirectoryName(this);//get the path to save screenshot
            File file = ScreenshotUtils.store(b, "screenshot" + screenshotType + ".jpg", saveFile);//save the screenshot to selected path
            shareScreenshot(file);//finally share screenshot
        } else
            //If bitmap is null show toast message
            Toast.makeText(this, R.string.screenshot_take_failed, Toast.LENGTH_SHORT).show();
    }
    /*  Show screenshot Bitmap */
    private void showScreenShotImage(Bitmap b) {
        imageView.setImageBitmap(b);
    }
    /*  Share Screenshot  */
    private void shareScreenshot(File file) {
        Uri uri = Uri.fromFile(file);//Convert file path into Uri for sharing
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
        intent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.sharing_text));
        intent.putExtra(Intent.EXTRA_STREAM, uri);//pass uri here
        startActivity(Intent.createChooser(intent, getString(R.string.share_title)));
    }
}

*ScreenshotType.java
public enum ScreenshotType {
    FULL, CUSTOM;
}

*ScreenshotUtils.java
public class ScreenshotUtils {
/*  Method which will return Bitmap after taking screenshot. We have to pass the view which we want to take screenshot.  */
public static Bitmap getScreenShot(View view) {
    View screenView = view.getRootView();
    screenView.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
    screenView.setDrawingCacheEnabled(false);
    return bitmap;
}

/*  Create Directory where screenshot will save for sharing screenshot  */
public static File getMainDirectoryName(Context context) {
    //Here we will use getExternalFilesDir and inside that we will make our Demo folder
    //benefit of getExternalFilesDir is that whenever the app uninstalls the images will get deleted automatically.
    File mainDir = new File(
            context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "Demo");

    //If File is not present create directory
    if (!mainDir.exists()) {
        if (mainDir.mkdir())
            Log.e("Create Directory", "Main Directory Created : " + mainDir);
    }
    return mainDir;
}

/*  Store taken screenshot into above created path  */
public static File store(Bitmap bm, String fileName, File saveFilePath) {
    File dir = new File(saveFilePath.getAbsolutePath());
    if (!dir.exists())
        dir.mkdirs();
    File file = new File(saveFilePath.getAbsolutePath(), fileName);
    try {
        FileOutputStream fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return file;

}

}
4.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context="com.takescreenshot_demo.MainActivity">

    <!--  Button which will take full page screenshot  -->
    <Button
        android:id="@+id/full_page_screenshot"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/full_page_screenshot"
        android:textColor="@android:color/white"
        android:textSize="14sp" />

    <!--   Hidden Text which will shown when taking screenshot from below Button  -->
    <TextView
        android:id="@+id/hidden_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/hidden_text"
        android:textColor="@android:color/white"
        android:textSize="14sp"
        android:visibility="invisible" />

    <!--  Button which will take screenshot after hiding some view and showing some view  -->
    <Button
        android:id="@+id/custom_page_screenshot"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/custom_page_screenshot"
        android:textColor="@android:color/white"
        android:textSize="14sp" />

    <!--  ImageView to show taken Screenshot  -->
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitCenter"
        android:src="@mipmap/ic_launcher" />

</LinearLayout>

A: A consolidated copy and paste code:
private void takeScreenshot() {
        Date now = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

        try {
            // image naming and path  to include sd card  appending name you choose for file
            String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
            String screenshotPath = mPath;

            // create bitmap screen capture
            View v1 = getWindow().getDecorView().getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
            v1.setDrawingCacheEnabled(false);

            File imageFile = new File(mPath);

            FileOutputStream outputStream = new FileOutputStream(imageFile);
            int quality = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();

//            openScreenshot(imageFile);
        } catch (Throwable e) {
            // Several error may come out with file handling or DOM
            e.printStackTrace();
        }
    }

    //Function to share Screenshot
    private void shareScreenshots(File file){
        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("image/*");

        intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
        intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        try {
            startActivity(Intent.createChooser(intent, "Share Screenshot"));
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, "No App Available", Toast.LENGTH_SHORT).show();
        }
    }

    //Function to open screenshot
    private void openScreenshot(File imageFile) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(imageFile);
        intent.setDataAndType(uri, "image/*");
        startActivity(intent);
    }

A: This is how I captured the screen and shared it. Take a look if you are interested.
public Bitmap takeScreenshot() {
  View rootView = findViewById(android.R.id.content).getRootView();
  rootView.setDrawingCacheEnabled(true);
  return rootView.getDrawingCache();
 }

And the method that saves the bitmap image to external storage:
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
    fos = new FileOutputStream(imagePath);
    bitmap.compress(CompressFormat.JPEG, 100, fos);
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
    Log.e("GREC", e.getMessage(), e);
 }}

see more in : https://www.youtube.com/watch?v=LRCRNvzamwY&feature=youtu.be

A: If someone is getting an java.io.FileNotFoundException, following SilengKnight's solution, the problem is probably that writing in storage was not permited (Although we added the user-permission in the manifest). I solved it by adding this in the store function before making a new FileOutputStream.
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        //Permission was denied
        //Request for permission
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_CODE_EXTERNAL_STORAGE);
    }

A: Create helper class for creating and sharing screen shot
public class share {
private final Context c;
public share(Context c) {
    this.c = c;
}
public void shareInt(Bitmap bitmap, String msg, String name) {
    Uri uri = getmageToShare(bitmap, name);
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.putExtra(Intent.EXTRA_TEXT, msg);
    intent.setType("*/*");
    c.startActivity(Intent.createChooser(intent, "Share Via").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}

// Retrieving the url to share
private Uri getmageToShare(Bitmap bitmap, String name) {
    File imagefolder = new File(c.getCacheDir(), "images");
    Uri uri = null;
    try {
        imagefolder.mkdirs();
        File file = new File(imagefolder, name+".png");
        FileOutputStream outputStream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 70, outputStream);
        outputStream.flush();
        outputStream.close();
        uri = FileProvider.getUriForFile(c, "com.yourapp.fileprovider", file);
    } catch (Exception e) {
        Toast.makeText(c, "" + e.getMessage(), Toast.LENGTH_LONG).show();
    }
    return uri;
   }
}

Now call this helper class from any activity you want to take screen shot and share
CardView mainView = findViewById(R.id.mainView);
new share(c).shareInt(new getBitmap().screenShot(mainView), "msg", "randomstring");

here mainView is that view which you want to take snap shot, jzt pass view reference.
No need of run time permission coz we are using cache dir

A: This is what I use to take a screenshot. The solutions described above work fine for API < 24, but for API 24 and greater another solution is needed. I've tested this method on API 15, 24, & 27.
I placed the following methods in MainActivity.java:
public class MainActivity {

...

String[] permissions = new String[]{"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
View sshotView;

...

private boolean checkPermission() {
List arrayList = new ArrayList();
for (String str : this.permissions) {
if (ContextCompat.checkSelfPermission(this, str) != 0) {
arrayList.add(str);
}
}
if (arrayList.isEmpty()) {
return true;
}
ActivityCompat.requestPermissions(this, (String[]) arrayList.toArray(new String[arrayList.size()]), 100);
return false;
}

protected void onCreate(Bundle savedInstanceState) {
...

this.sshotView = getWindow().getDecorView().findViewById(R.id.parent);
...

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();
switch (id) {

case R.id.action_shareScreenshot:
boolean checkPermission = checkPermission();
Bitmap screenShot = getScreenShot(this.sshotView);
if (!checkPermission) {
return true;
}
shareScreenshot(store(screenShot));
return true;

case R.id.option2:
...
return true;
}

return false;
}

private void shareScreenshot(File file) {
Parcelable fromFile = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".com.redtiger.applehands.provider", file);
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setAction("android.intent.action.SEND");
intent.setType("image/*");
intent.putExtra("android.intent.extra.SUBJECT", XmlPullParser.NO_NAMESPACE);
intent.putExtra("android.intent.extra.TEXT", XmlPullParser.NO_NAMESPACE);
intent.putExtra("android.intent.extra.STREAM", fromFile);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Communication Platform Available", Toast.LENGTH_SHORT).show();
}
}

public static Bitmap getScreenShot(View view) {
View rootView = view.getRootView();
rootView.setDrawingCacheEnabled(true);
Bitmap createBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
return createBitmap;

public File store(Bitmap bitmap) {
String str = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Screenshots";
File file = new File(str);
if (!file.exists()) {
file.mkdirs();
}
file = new File(str + "/sshot.png");
try {
OutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "External Storage Permission Is Required", Toast.LENGTH_LONG).show();
}
return file;
}
}

I placed the following permissions and provider in my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.redtiger.applehands">

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

<application

...

<provider
android:name="com.redtiger.applehands.util.GenericFileProvider"
android:authorities="${applicationId}.com.redtiger.applehands.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>

...

</application>

</manifest>

I created a file called provider_paths.xml (please see below) to direct the FileProvider where to save the screenshot. The file contains a simple tag that points to the root of the external directory.
The File was placed in the resource folder res/xml (if you don't have an xml folder here, just create one and place your file there).
provider_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>


text:
Q: Converting curl to ansible uri POST request I have the following curl command:
curl -i -XPOST "http://localhost:8086/write?db=somedb" --data-binary "total,type=stats value=25 $epoch"

I can add data to this database using this command easily. However, I'd like a URI equivalent to this command, which I can't seem to find online. I know a get request looks like this:
http://example:8086/query?q=show%20databases

How would I do my POST request with the data that I currently have?

A: You can find the detail answer from Ansible uri module, here https://docs.ansible.com/ansible/latest/modules/uri_module.html
Example for your particular question:
- uri:
    url: http://localhost:8086/write?db=somedb
    method: POST
    body_format: raw
    body: "total,type=stats value=25 $epoch"
    status_code: 200


text:
Q: How to get compressed file data from a ZIP file in Java? Using java.util.zip, I can reach the uncompressed files (which is the normal, expected behavior). I can also reach the metadata about each file (via java.util.zip.ZipFile) Is there a way to actually get the compressed data (byte stream) of a file within a ZIP, that is,  before Java uncompresses it? Similarly, is there any libraries for lower level ZIP operations for Java?
EDIT: Obviously, I can do this by reading through the ZIP file as a byte stream and interpreting the whole file but that would involve tons of complications about Zip file. Essentially, this would mean creating a library from scratch for reading/handling zip files. I don't want that.


text:
Q: What is the meaning of this code? Here is the code sample provided in .Net Sdk:
Private Sub ReadOrderData(ByVal connectionString As String)
    Dim queryString As String = _
        "SELECT OrderID, CustomerID FROM dbo.Orders;"

    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(queryString, connection)
        connection.Open()

        Dim reader As SqlDataReader = command.ExecuteReader()

        ' Call Read before accessing data.
        While reader.Read()
            Console.WriteLine(String.Format("{0}, {1}", _
                reader(0), reader(1)))
        End While

        ' Call Close when done reading.
        reader.Close()
    End Using
End Sub

My question: Is that this reader(0) actually the shortcut for calling this property reader.item(0)?

A: reader(0) refers to the very first field in the retrieved row. However you better reference field by name, OrderID in this case.
Take a look at SqlDataReader.Item Property.
This is indexed property. You can find some details here.

A: reader(0) , reader (1) and so on refers to columns/ fields of the row u r retriving,
reader(0)---> column 1
reader(1)---> column 2
...
You can use direct field names in place of these 'readers'. But in books/tutorials, code is always written like that.


text:
Q: SolrCloud: high availability? Don't see it working I have setup the SolrCloud a while age, but it was never quite working the way I thought it should. My concern is about high availability. Maybe I didn't understand something, but it seemed to me that when some node goes down in SolrCloud, the other nodes should still continue to work, right?
My system has only 2 nodes. The number of shards is 1, i.e. both nodes are kind of like "mirrors" or copies of each other. My intent was to achieve a system where if one node goes down, the other one keeps operating.
Ever since I've installed the cloud I have noticed that if either one of 2 nodes is shut down, I can't access the other node's web UI no matter what until the second node comes up as well.
Why is this happening?
btw, the SolrCloud is version 4.4.0 1504776 - sarowe, and Zookeeper is also spread across the 2 nodes. Is this because of Zookeeper clustered across 2 machines?

A: I believe that Zookeeper is the problem. A Zookeeper ensemble must be of 2N+1 instances and tolerate N down nodes. If you have only 2 than you are in the configuration of 2*1+1=3 nodes in the ensemble. Only one down node is tolerated and you need at least 2 nodes up. As you have only 2 zk, if any of them is down than your ZK ensemble is also down.
To achieve high availability, it is recommended to deploy an independent Zookeeper ensemble with at least 3 instances on 3 differents machines to eliminate SPoF.


text:
Q: flutter Dart Sticky Header from Json i am trying to create flutter sticky header list from json. i am finding it difficult to group by date from json i like to understand more about how to manupluate list and maps. if any body can help.
[
  {
    "_id": "5bbe598c20a312e8f3a51692",
    "index": 0,
    "guid": "853882bb-5432-4efa-9886-38491397cb22",
    "isActive": false,
    "balance": "$3,493.46",
    "picture": "http://placehold.it/32x32",
    "age": 22,
    "eyeColor": "green",
    "name": {
      "first": "Maryellen",
      "last": "Moody"
    },
    "company": "SURETECH",
    "registered": "Fri Jul 21 1995 05:54:11 GMT+0000 (UTC)"
  },
  {
    "_id": "5bbe598c325e76f346816167",
    "index": 1,
    "guid": "672ac480-f8fc-47e8-a960-bac230f11dab",
    "isActive": true,
    "balance": "$3,081.07",
    "picture": "http://placehold.it/32x32",
    "age": 39,
    "eyeColor": "green",
    "name": {
      "first": "Duffy",
      "last": "Knight"
    },
    "company": "CYCLONICA",
    "registered": "Fri Jul 21 1995 09:54:11 GMT+0000 (UTC)"
  },
  {
    "_id": "5bbe598c0ce158b98ebafcf2",
    "index": 2,
    "guid": "4528d59a-2eb1-4726-ae4b-5cc8d9495d5e",
    "isActive": true,
    "balance": "$2,588.97",
    "picture": "http://placehold.it/32x32",
    "age": 29,
    "eyeColor": "brown",
    "name": {
      "first": "Traci",
      "last": "Grimes"
    },
    "company": "DOGNOST",
    "registered": "Sun Jul 31 2011 03:25:47 GMT+0000 (UTC)"
  },
  {
    "_id": "5bbe598cc666e2e9561ad82e",
    "index": 3,
    "guid": "085883af-3ad4-4779-ac4d-5c5374d81144",
    "isActive": true,
    "balance": "$3,928.99",
    "picture": "http://placehold.it/32x32",
    "age": 26,
    "eyeColor": "brown",
    "name": {
      "first": "Reyna",
      "last": "Bond"
    },
    "company": "MOREGANIC",
    "registered": "Sun Jul 31 2011 06:25:47 GMT+0000 (UTC)"
  }
]

i am trying to get records for same date and group them with sticky header
Fri Jul 21 1995 - sticky header
$3,493.46 - Maryellen
$3,081.07 - Duffy
Sun Jul 31 2011
$2,588.97 - Traci
$3,928.99 - Reyna
packages i am trying to impliment
https://pub.dartlang.org/packages/sticky_header_list
https://pub.dartlang.org/packages/sticky_headers
i am new to flutter. but i am in love with it. trying to undersand logics

A: Steps:

*

*load json and convert to data object

*group data object by date

*convert group data into views
Check the following codes, it should work as your expected.
// main.dart
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:sticky_headers/sticky_headers.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in IntelliJ). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: CompanyPage(title: "Company Page")
    );
  }
}

class Name {
  final String first;
  final String last;
  Name({this.first, this.last});

  Name.fromJson(Map<String, dynamic> json)
      : first = json['first'],
        last = json['last'];
}

class Company {
  final String id;
  final int index;
  final String guid;
  final bool isActive;
  final String balance;
  final String picture;
  final int age;
  final String eyeColor;
  final Name name;
  final String company;
  final DateTime registered;

  Company({
    this.id, this.index, this.guid, this.isActive,
    this.balance, this.picture, this.age, this.eyeColor,
    this.name, this.company, this.registered
  });

  Company.fromJson(Map<String, dynamic> json)
      : id          = json['_id'],
        index       = json['index'],
        guid        = json['guid'],
        isActive    = json['isActive'],
        balance     = json['balance'],
        picture     = json['picture'],
        age         = json['age'],
        eyeColor    = json['eyeColor'],
        name        = Name.fromJson(json['name']),
        company     = json['company'],
        registered  = _toDateTime(json['registered']);

  /// Fri Jul 21 1995 05:54:11 GMT+0000 (UTC)
  static DateTime _toDateTime(String dateTime) {
    return DateFormat("EEE MMM d yyyy HH:mm:ss").parseUtc(dateTime);
  }
}

class CompanyViewInfo {
  final Widget header;
  final Widget child;
  CompanyViewInfo({this.header, this.child});
}

class CompanyPage extends StatefulWidget {
  final String title;
  CompanyPage({Key key, this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _CompanyPageState();
}

class _CompanyPageState extends State<CompanyPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text(widget.title)),
        body: FutureBuilder(
            future: _getCompanyList(),
            builder: (context, snapshot) {
              if(snapshot.hasError) print(snapshot.error);
              if (snapshot.data == null) return Center(child: CircularProgressIndicator());

              final groupList = _groupByDate(snapshot.data);
              return ListView.builder(
                itemBuilder: (context, index) =>
                    StickyHeader(
                        header: groupList[index].header,
                        content: groupList[index].child
                    ),
                itemCount: groupList.length,
              );
            })
    );
  }
}

Future<List<Company>> _getCompanyList() async {
  final jsonString = await rootBundle.loadString("assets/companies.json");
  return List.castFrom(json.decode(jsonString)).map((c) => Company.fromJson(c)).toList();
}

List<CompanyViewInfo> _groupByDate(List<Company> companyList) {
  final map = groupBy(
      keySelector: (Company c) => DateFormat("EEE MM d yyyy").format(c.registered),
      list: companyList
  );

  return toList(
      mapF: (String date, List<Company> list) {
        final header = Container(
          height: 50.0,
          color: Colors.blue[700],
          padding: EdgeInsets.symmetric(horizontal: 16.0),
          alignment: Alignment.centerLeft,
          child: Text(date, style: TextStyle(color: Colors.white)),
        );

        final child = Text(list.map((c) => "${c.balance} - ${c.name.first}").join(" "));

        return CompanyViewInfo(header: header, child: child);
      },
      map: map
  );
}

Map<K, List<T>> groupBy<T, K>({K Function(T) keySelector, List<T> list}) {
  Map<K, List<T>> destination = Map();

  for (T element in list) {
    final key = keySelector(element);
    final value = destination[key] ?? List();
    value.add(element);
    destination[key] = value;
  }

  return destination;
}

List<R> toList<K, V, R>({R Function(K, V) mapF, Map<K, V> map}) {
  List<R> destination = List();
  map.forEach((k, v) => destination.add(mapF(k, v)));
  return destination;
}

in pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  intl: ^0.15.7
  sticky_headers: "^0.1.7"

assets:
  - assets/companies.json

remember to put companies.json on your_project_root/assets/companies.json


text:
Q: Transfer file(s) to a folder on a server I have been trying to come up with a strategy that will allow me to transfer a file over a network (or internet in near future) from a client to a server's folder (DB server, in my case). I already have a Client-Server application running. Several clients connect to a server and perform their tasks. The server has the SQL Server 2008 DB as well. I do not want to upload file to database. I know that using credentials and/or impersonation, one can transfer a file using the System.IO library to a network-shared folder. Now, my client is on a company Intranet. Therefore, all communication is over local network and no internet is involved. Nevertheless, there is a prospect of involving a WP7 client applet as well. If that were the case, eventually the client will want to use the system over internet as well. For all other communication, I will have to expose the SQL server over the internet by getting a fixed/static IP address.
The only thing that bothers me is file transfer. The users constantly upload CVs, legal documents (all in PDF only) to a folder on the server. They also retrieve it to view them. I was wondering if there is a possibility to involve socket programming and the socket-server portion is in a windows service running on the server.
Is that a viable approach? Several users will be uploading and retrieving at the same time.
Kindly share your experience in this case.


text:
Q: Update query is causing a crash in vb.net i am trying to write a function that takes 2 indexes as argument and takes value from a table with that indexes. With theese values code must update the same table. Basicly database updating from DataGridview.
nothing worked so i commented out the SQL line and make it very very simple. But here is another problem. it just crashes with this --> "'[13680] WindowsApp2.exe' program exited with the code -1073740940 (0xc0000374)." (i translate it to English)
tried everything please help. The database i am querying is on Ms Access by the way.
Private Function Update_Notes(rowIndex As Integer, colIndex As Integer)
        If Environment.UserName = DataGridView1.Rows(DataGridView1.SelectedCells.Item(0).RowIndex).Cells.Item(1).Value.ToString() Then
        'Get the values
        con.Open()
        Dim hakedKod As String
        Dim ddate As Date
        Dim note As String
        Dim updateNoteId As Long
        hakedKod = DataGridView2.Item(1, rowIndex).Value
        ddate = DataGridView2.Item(2, rowIndex).Value
        note = DataGridView2.Item(3, rowIndex).Value.ToString
        updateNoteId = DataGridView2.Item(0, rowIndex).Value

        Dim cmd As New OleDb.OleDbCommand
        cmd.Connection = con
        Dim sql As String

        sql = "UPDATE TBL_Notes SET [Not]='12aa' WHERE [Kimlik] = 28"

        '@hakedKod, [Tarih] = @ddate, [Not] = @note WHERE [Kimlik] = @id"

        'initialize parameters for sterilization and date error stuff
        cmd.Parameters.AddWithValue("@id", updateNoteId)
        cmd.Parameters.AddWithValue("@hakedkod", hakedKod)
        cmd.Parameters.AddWithValue("@ddate", ddate)
        cmd.Parameters.AddWithValue("@note", note)

        cmd.CommandText = sql

        Dim i As Integer
        Try
            i = cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            DataGridView2_Loader()
        End Try
        con.Close()
    Else
        MsgBox("maalesef kayıt için değişiklik yetkiniz bulunmamaktadır.")
    End If

End Function

A: Functions have a return type and include the keyword Return followed by the value you wish to return.
I don't like huge If blocks so I negated it and returned to the calling code.
Connections should be declared in the method where they are used. They must be disposed and also commands need to be disposed. Using...End Using blocks take care of this closing and disposing even if there is an error.
Don't open the connection until directly before the .Execute....
Your CommandText only contains literals; no parameter names so the parameters values are never reflected in the execute.
I had to guess at the datatypes of the parameters. Check your database. I also had to guess at the name of the hakedkod column. The closest I came with Google Translate was minced meat. :-)
Access pays no attention to parameter names. They are only interested in the position. The position of the parameter in the sql string must match the order the parameters are added to the parameters collection.
Private ConnStr As String = "Your connection string"

Private Function Update_Notes(rowIndex As Integer, colIndex As Integer) As Integer
    If Environment.UserName <> DataGridView1.Rows(DataGridView1.SelectedCells.Item(0).RowIndex).Cells.Item(1).Value.ToString() Then
        Return 0
    End If
    Dim i As Integer
    Dim sql = "UPDATE TBL_Notes SET [Hak] = @hakedkod, [Tarih] = @ddate, [Not]= @note WHERE [Kimlik] = @id"
    Using con As New OleDbConnection(ConnStr),
            cmd As New OleDbCommand(sql, con)
        cmd.Parameters.Add("@hakedkod", OleDbType.VarChar).Value = DataGridView2.Item(1, rowIndex).Value.ToString
        cmd.Parameters.Add("@ddate", OleDbType.Date).Value = CDate(DataGridView2.Item(2, rowIndex).Value)
        cmd.Parameters.Add("@note", OleDbType.VarChar).Value = DataGridView2.Item(3, rowIndex).Value.ToString
        cmd.Parameters.Add("@id", OleDbType.Integer).Value = CInt(DataGridView2.Item(0, rowIndex).Value)
        con.Open()
        i = cmd.ExecuteNonQuery()
    End Using
    Return i
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim row As Integer
    Dim col As Integer
    Dim retVal As Integer
    Try
        retVal = Update_Notes(row, col)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    If retVal > 0 Then
        DataGridView2_Loader()
    Else
        MsgBox("maalesef kayıt için değişiklik yetkiniz bulunmamaktadır.")
    End If
End Sub


text:
Q: Is the Managed Extensibility Framework (MEF) what ASP.NET Core 2 uses internally for IoC? I am trying to gauge if Managed Extensibility Framework (MEF) is something I can use for extending an ASP.NET Core 2.x MVC website.  I saw ExtCore also.  My desire is to use it to build infrastructure for plugins in my application.
What I cannot figure out is if MEF is legacy from Silverlight or if MEF is what Core actually uses for it's IoC.  I know MEF is in CoreFX, but that's all I know for sure.
I'd like to use MS's IoC DI here if it is viable and not legacy.  Is MEF legacy or is it used by Core itself?
Some questions I looked at, most were very old,
Is there a replacement for MEF in .NET Core (or ASP.NET 5)
In ASP.NET Core, does the IoC ASP Startup Class solve what the Managed Extensibility Framework solved with a catalog and container?
 (The last one is a question I asked at the end of 2016.)


text:
Q: SQL/PHP I have the start and end locations but want to find the joining legs from a table I have a problem looping through my tableLegs for a bus timetable to find the array of legs legID that the passenger would need to take to get from a to b, take for example the passenger want to start at LocID of c and travel to LocID of p, I would like the array of legs that make up that trip LegID's (01, 02, 04), hope that is easy enough to follow.
tableLegs
=============================================
LegID    startLocID   endLocID   departTime
 01          a           e        9:00
 02          e           i        10:00
 03          i           m        11:00
 04          i           q        11:00

tableLegStops
=========================================
LegID     stopNo    LocID     TripTime
  01         1         a       0 min
  01         2         b       20 min
  01         3         c       30 min
  01         4         d       40 min
  01         5         e       60 min
  02         1         e       0 min
  02         2         f       20 min
  02         3         g       30 min
  02         4         h       40 min
  02         5         i       60 min
  03         1         i       0 min
  03         2         j       20 min
  03         3         k       30 min
  03         4         l       40 min
  03         5         m       60 min
  04         1         i       0 min
  04         2         n       20 min
  04         3         o       30 min
  04         4         p       40 min
  04         5         q       60 min

To give you a basis for what I am trying to achieve here, it's for a bus website where each trip is made up of different legs.

A: This task is known as searching for a shortest path in a graph. There exists an implementation of Dijkstra algorithm for solving this in terms of MySQL stored procedure.
But this would probably require from you to change your table structure a bit, because the graph uses only two types of entities: nodes and edges. So you should decompose your legs into edges, and then deduce the legs back after you get the shortest path in edges.

A: You can use the the A* search algorithm for this. Se http://en.wikipedia.org/wiki/A_star


text:
Q: Closed expression for a given permutation product I am looking a formula for $\chi(\tau^{-1}g)$, where $g\in S_n$ and $\chi(g)$ denotes the number of cycles in the cycle notation and let $\tau$ be the cyclic permutation, ie.: $(12\dots n)$. If I have the value of $\chi(g)$, is there any closed expression for $\chi(\tau ^{-1}g)$?
For example, let $n=4$, when $\chi(g)=4$, ie.: $g=id$ then $\chi(\tau^{-1}g)=1$ so I have a pair $(4,1)$, when $\chi(g)=3$ then $\chi(\tau^{-1}g)=2$, thus I have $(3,2)$ pair, etc.

A: The value of $\chi(\tau g)$ depends on $g$, not just on $\chi(g)$. To see that, see what happens when $g=\tau$ and when $g = \tau^{-1}$.


text:
Q: Create new method I'm working with HP UFT. This tool use VBScript to automatics test.
Is it possible to create new method in function library.
I mean something like this.
Browser("Browser").Page("Page").WebEdit("login").MyMethod()

How can I do that?

A: Go to the Design menu, and select Function Definition Generator...
You'll get the following UI

Basically this is a helper for RegisterUserFunc.
By selecting the Register to a test object check-box (and which type of test object) the function you add will be available as a regular test object function.
Note that you can override an existing function, for example you can change Set to see if the value is "~today~" add today's date.

A: Adding User Defined Functions is actually pretty easy: define the function, decide on the object type you wish to add the function to, and use RegisterUserFunc to put it all together:
Function BrokenImage(ImageObject)
BrokenImage = True
ImageObject.WaitProperty "visible", True, 1000
ImageLoaded = False
StartTime = Now()
Do
    If ImageObject.Object.naturalHeight > 0 And ImageObject.Object.naturalHeight > 0 Then
        BrokenImage = False
        Exit Do
    End If
    If DateDiff("s", StartTime, Now()) > 10 Then Exit Do
Loop While ImageLoaded = False
End Function

RegisterUserFunc "Image", "BrokenImage", "BrokenImage"

Once you've got the function defined, you call it as you would any other object method:
If Browser().Page().Image().ImageBroken() = true Then Print "Broken Image"

You can also add additional parameters which will then be passed to the new method.


text:
Q: "What is/are new here is/are ..." Original sentence: "What are new here are (1) XYZ and (2) PDQ."
Correcting this sentence in a text and it just feels wrong. In order to make sure I change it correctly, I tried searching for:

*

*The type of inversion this structure is, and thus,

*The rule for verb agreement.

Alas, no luck. The best I could do was try different combinations in Google Scholar, among which I found 138 instances of "What is new here are" (and, of course, 3940 results for "is ... is").
"Is ... are" feels much better, and the only explanation I can think of is that "is" agrees with "what", while "are" corresponds to what follows. Still, I can't really face the world with confidence in that explanation.
Can anybody point to the specific rule regarding this structure?

A: I agree that the option with "is" sounds better. However,it must be noted that a plural verb after "what" is also possible before a plural noun in an informal style.


text:
Q: Can two objects in global scope have the same name? Consider the following snippet:
struct foo_struct {
   int a;
   int b;
};

struct foo_struct *foo;
struct foo_struct foo_global;

int foo(int x)
{
  ....
  return 0;
}

int main(void)
{
   foo = &foo_global;
  ...
}

So I have two identifiers but for different objects (is it correct to call a
function an object?).  Is this strictly illegal, or does the standard define such
case as "undefined behavior". What part of the standard describe this?

A: I get:

a.c:9: error: 'foo' redeclared as different kind of symbol
a.c:6: note: previous declaration of 'foo' was here

I very much doubt this is legal. You can disambiguate foo = &foo_global because you can't "overwrite" a function, but void *var = foo would be ambiguous (is foo a function pointer or the struct foo_struct pointer?).
Now the standard:

6.2.1 §2
  For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope. Different entities designated by the same identifier either have different scopes, or are in different name spaces. [...]

So the identifiers must have different scopes or different name spaces.

6.2.1 §4
  If the declarator or type specifier that declares the identifier
  appears outside of any block or list of parameters, the identifier has file scope, which
  terminates at the end of the translation unit. [...]
6.2.1 §6
  Two identifiers have the same scope if and only if their scopes terminate at the same
  point.

These indicate both identifiers have the same scope (file scope), which terminates at the end of the translation unit.

6.2.3 §1
  [...] [T]here are separate name spaces for various categories of identifiers, as follows:

*

*label names [...]

*the tags of structures, unions, and enumerations [...]

*the members of structures or unions [...]

*all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).

The name spaces are the same, because both are ordinary identifiers.
Therefore, they have the same scope and the same name space, which doesn't satisfy 6.2.1 §2.

A: Did you try to compile it ?
With gcc, this is not legal and produces of course an error
error: 'foo' redeclared as different kind of symbol
error: previous declaration of 'foo' was here

A: You can have a variable which type is a pointer to a funcion so when you call it, are you call the function or the function pointed by the variable with the same name? It is ambiguous. I think it's illegal. There is no problem for example in java, because there you can't have a variable that points to a function so the use of the parenthesis disambiguate if you are referring the function or the variable.
typedef void (*functiontype)();
functiontype func;

void f1 () {
    ...
}
void func () {
    ...
}
void main() {
    func = &f1;
    func();
}


text:
Q: How to specify theme in Rmarkdown notebook depending on output format? How do I tell to knitr to use theme_classic if I export my Rmd notebook to PDF and use dark_theme_gray from ggdark package if I export my Rmd notebook to HTML?

A: Try this. (Sorry. I had no ggdark installed. So I just used theme_gray for HTML output). knitr provides helper functions to check for is_html_output or is_latex_output.
---
title: "test"
output:
  pdf_document: default
  html_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# Plot

```{r}
library(ggplot2)

p <- ggplot(mtcars, aes(hp, mpg)) +
  geom_point()

if (knitr::is_html_output()) {
  p + theme_gray()
} else if (knitr::is_latex_output()) {
  p + theme_classic()
}
```


text:
Q: Magento : Page selection is missing with custom product list I have written a controller which generates a product collection based on the requested category and a attribute filter.
I generate the render with this code :
public function AfficherCollection($collection){
 if ($collection){
  Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
  $magento_block = Mage::getSingleton('core/layout');
  $productsHtml  = $magento_block->createBlock('catalog/product_list');
  $productsHtml ->setTemplate('catalog/product/list.phtml')->setCollection($collection);
  echo $productsHtml->toHTML();
 }
}

The render works well but the problem is the page selector is missing.
But if I call my page with ?p=2 in page argument ; I have the desired products, so there are not any functional problems but still a page layout problem.
Have you got an idea ?
Thank you!

A: Why are you totally bypassing the standard magento functionnalities and framework ?
You should use the Layout layer of magento framework..  It's him that handles all the product_list logic :
See for example catalog.xml layout file :
<catalog_category_view>
    <reference name="content">
        <block type="catalog/category_view" name="category.products" template="catalog/category/view.phtml">
            <block type="catalog/product_list" name="product_list" template="catalog/product/list.phtml">
                <block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
                    <block type="page/html_pager" name="product_list_toolbar_pager"/>
                    [...]

You can see that the pager is added by XML layout update


text:
Q: Grouping together data from arrays Without using anything like List, ArraySort, Classes, Structs, Objects, LINQ etc how would I group together say a list of ages I took from a survey, each element in the array representing one person's age.
Then have a method that counts how many people are in each age, then groups those people into 5 age groups, 0-18, 18-30, 31-45, 46-64, and 65 and older.  Say like there are are 8 people who are age 18-30 something like that.
I thought I had this down by combining two ways of doing it, first by incrementing the counting array by the array with the data, and the other to group the data with a while loop but it just seems to display the ages themselves.

A: Initializing
int[] input = new int[] { 5, 10, 20, 35, 50, 68 };
int[,] ageGroups = new int[5, input.Length];
int[] ageCounters = new int[5];

Grouping
foreach(int age in input)
{
    if(age >= 0 && age < 18)
    {
        ageGroups[0, ageCounters[0]] = age;
        ageCounters[0]++;
    }
    else if(age >= 18 && age <= 30)
    {
        ageGroups[1, ageCounters[1]] = age;
        ageCounters[1]++;
    }
    else if(age >= 31 && age <= 45)
    {
        ageGroups[2, ageCounters[2]] = age;
        ageCounters[2]++;
    }
    else if(age >= 46 && age <= 64)
    {
        ageGroups[3, ageCounters[3]] = age;
        ageCounters[3]++;
    }
    else if(age >= 65)
    {
        ageGroups[4, ageCounters[4]] = age;
        ageCounters[4]++;
    }
}

Displaying
for(int i = 0; i < 5; i++)
{
    for(int j = 0; j < ageCounters[i]; j++)
    {
        Console.Write(ageGroups[i, j] + " ");
    }
    Console.WriteLine();
}


text:
Q: How can I safely connect 230V AC to this relay? I have this high inrush relay (type G5RL-1A-E-HR.) Page 5 of the datasheet only mentions pin names from the bottom. The relay will switch on/off AC side of an SMPS.
There is no polarity mentioned for the input DC control voltage.
Can I wire the relay this way:

If I need to solder the AC wires to the pins of this relay, what would be the robust way to do it?

For the AC pins, I was planning to use this stripboard, but would that handle 230V with less than 1A RMS maybe with an SMPS inrush current of 10A?

A: The relay coils (except latch-type ones) are not polarised elements. So they can work with any polarity.
For soldering, you should consider mechanical stress and isolation as well. A stripboard "might" be suitable but if the wires are strong (thick?) and strained enough then they can strip off the copper. So you should take some precautions against an accidental short.

maybe with an SMPS inrush current of 10A?

Well, that's a very low inrush current.
PS: Personally, I'd switch both L and N to make the things "safer". Just saying.

A: Do not hand solder wires directly on the pins on a relay intended for PCB mounting. Instead you should place this relay in some suitable socket that fits your application. For example there are DIN rail sockets with screw terminals which would be suitable like this one. There are lots of different manufacturers and flavours available.
Another reason for using sockets is that when it breaks, you can easily replace it by hand without soldering anything.


text:
Q: How can i encrypt a string in Dart same like in c# using RijndaelManaged This is my c# code for string encryption using RijndaelManaged,
I'm not able to encrypt like same in flutter, i tried many packages. but no result.
i need to encrypt a string in flutter and i need to decrypt in c#
public static string key = Environment.GetEnvironmentVariable("ENCR_KEY");
private const int Keysize = 256;
private const int DerivationIterations = 100;

public string Encrypt(string plainText)
{
    var saltStringBytes = Generate256BitsOfRandomEntropy();
    var ivStringBytes = Generate256BitsOfRandomEntropy();
    var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
    using (var password = new Rfc2898DeriveBytes(key, saltStringBytes, DerivationIterations))
    {
        var keyBytes = password.GetBytes(Keysize / 8);
        using (var symmetricKey = new RijndaelManaged())
        {
            symmetricKey.BlockSize = 128;
            symmetricKey.Mode = CipherMode.CBC;
            //symmetricKey.Padding = PaddingMode.PKCS7;
            using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
            {
                using (var memoryStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        var cipherTextBytes = saltStringBytes;
                        cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                        cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                        memoryStream.Close();
                        cryptoStream.Close();
                        return Convert.ToBase64String(cipherTextBytes);
                    }
                }
            }
        }
    }
}

private static byte[] Generate256BitsOfRandomEntropy()
{
    var randomBytes = new byte[16];
    using (var rngCsp = new RNGCryptoServiceProvider())
    {
        rngCsp.GetBytes(randomBytes);
    }
    return randomBytes;
}

public string Decrypt(string cipherText)
{
    string password = key;
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        var salt = cipherBytes.Take(16).ToArray();
        var iv = cipherBytes.Skip(16).Take(16).ToArray();
        var encrypted = cipherBytes.Skip(32).ToArray();
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, salt, 100);
        encryptor.Key = pdb.GetBytes(32);
        encryptor.Padding = PaddingMode.PKCS7;
        encryptor.Mode = CipherMode.CBC;
        encryptor.IV = iv;
        using (MemoryStream ms = new MemoryStream(encrypted))
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Read))
            {
                using (var reader = new StreamReader(cs, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}

When i try encrypted cipher to decrypt in c#. I'm getting this error,
"Padding is invalid and cannot be removed."
This is my Dart code
import 'dart:convert';
import 'package:pointycastle/block/aes_fast.dart';
import 'dart:typed_data';
import 'package:pointycastle/export.dart';
import 'package:pointycastle/key_derivators/pbkdf2.dart';
import 'package:pointycastle/paddings/pkcs7.dart';
import 'package:pointycastle/pointycastle.dart';

const KEY_SIZE = 32; // 32 byte key for AES-256
const ITERATION_COUNT = 2;
const SALT = "XXXXXXXXXXXXXXXXX";
const INITIAL_VECTOR = "ZZZZZZZZZZZZZZZZ";
const PASS_PHRASE = "YYYYYYYYYYYYYYYYYYY";

Future<String> cryptString(String text) async {
  String encryptedString = "";

  final mStrPassPhrase = toUtf8(PASS_PHRASE);

  encryptedString = AesHelperMethod2.encrypt(
    mStrPassPhrase,
    toUtf8(text),
    mode: AesHelperMethod2.CBC_MODE,
  );

  return encryptedString;
}

Future<String> decryptString(String text) async {
  String decryptedString = "";

  final mStrPassPhrase = toUtf8(PASS_PHRASE);

  decryptedString = AesHelperMethod2.decrypt(mStrPassPhrase, toUtf8(text),
      mode: AesHelperMethod2.CBC_MODE);

  return decryptedString;
}

///MARK: AesHelper class
class AesHelperMethod2 {
  static const CBC_MODE = 'CBC';
  static const CFB_MODE = 'CFB';

  static Uint8List deriveKey(dynamic password,
      {String salt = '',
      int iterationCount = ITERATION_COUNT,
      int derivedKeyLength = KEY_SIZE}) {
    if (password == null || password.isEmpty) {
      throw new ArgumentError('password must not be empty');
    }

    if (password is String) {
      password = createUint8ListFromString(password);
    }

    Uint8List saltBytes = createUint8ListFromString(salt);
    Pbkdf2Parameters params =
        new Pbkdf2Parameters(saltBytes, iterationCount, derivedKeyLength);
    KeyDerivator keyDerivator =
        new PBKDF2KeyDerivator(new HMac(new SHA1Digest(), 64));
    keyDerivator.init(params);

    return keyDerivator.process(password);
  }

  static Uint8List pad(Uint8List src, int blockSize) {
    var pad = new PKCS7Padding();
    pad.init(null);

    int padLength = blockSize - (src.length % blockSize);
    var out = new Uint8List(src.length + padLength)..setAll(0, src);
    pad.addPadding(out, src.length);

    return out;
  }

  static Uint8List unpad(Uint8List src) {
    var pad = new PKCS7Padding();
    pad.init(null);

    int padLength = pad.padCount(src);
    int len = src.length - padLength;

    return new Uint8List(len)..setRange(0, len, src);
  }

  static String encrypt(String password, String plaintext,
      {String mode = CBC_MODE}) {
    String salt = toASCII(SALT);
    Uint8List derivedKey = deriveKey(password, salt: salt);
    KeyParameter keyParam = new KeyParameter(derivedKey);
    BlockCipher aes = new AESFastEngine();

    var ivStr = toASCII(INITIAL_VECTOR);
    Uint8List iv = createUint8ListFromString(ivStr);

    BlockCipher cipher;
    ParametersWithIV params = new ParametersWithIV(keyParam, iv);
    switch (mode) {
      case CBC_MODE:
        cipher = new CBCBlockCipher(aes);
        break;
      case CFB_MODE:
        cipher = new CFBBlockCipher(aes, aes.blockSize);
        break;
      default:
        throw new ArgumentError('incorrect value of the "mode" parameter');
        break;
    }
    cipher.init(true, params);

    Uint8List textBytes = createUint8ListFromString(plaintext);
    Uint8List paddedText = pad(textBytes, aes.blockSize);
    Uint8List cipherBytes = _processBlocks(cipher, paddedText);
    final enc = base64.encode(cipherBytes);
    print("enc : " "$enc");
    return base64.encode(cipherBytes);
  }

  static String decrypt(String password, String ciphertext,
      {String mode = CBC_MODE}) {
    String salt = toASCII(SALT);
    Uint8List derivedKey = deriveKey(password, salt: salt);
    KeyParameter keyParam = new KeyParameter(derivedKey);
    BlockCipher aes = new AESFastEngine();

    var ivStr = toASCII(INITIAL_VECTOR);
    Uint8List iv = createUint8ListFromString(ivStr);
    Uint8List cipherBytesFromEncode = base64.decode(ciphertext);

    Uint8List cipherIvBytes =
        new Uint8List(cipherBytesFromEncode.length + iv.length)
          ..setAll(0, iv)
          ..setAll(iv.length, cipherBytesFromEncode);

    BlockCipher cipher;

    ParametersWithIV params = new ParametersWithIV(keyParam, iv);
    switch (mode) {
      case CBC_MODE:
        cipher = new CBCBlockCipher(aes);
        break;
      case CFB_MODE:
        cipher = new CFBBlockCipher(aes, aes.blockSize);
        break;
      default:
        throw new ArgumentError('incorrect value of the "mode" parameter');
        break;
    }
    cipher.init(false, params);

    int cipherLen = cipherIvBytes.length - aes.blockSize;
    Uint8List cipherBytes = new Uint8List(cipherLen)
      ..setRange(0, cipherLen, cipherIvBytes, aes.blockSize);
    Uint8List paddedText = _processBlocks(cipher, cipherBytes);
    Uint8List textBytes = unpad(paddedText);

    return new String.fromCharCodes(textBytes);
  }

  static Uint8List _processBlocks(BlockCipher cipher, Uint8List inp) {
    var out = new Uint8List(inp.lengthInBytes);

    for (var offset = 0; offset < inp.lengthInBytes;) {
      var len = cipher.processBlock(inp, offset, out, offset);
      offset += len;
    }

    return out;
  }
}

///MARK: HELPERS
Uint8List createUint8ListFromString(String s) {
  Uint8List ret = Uint8List.fromList(s.codeUnits);

  return ret;
}

String toUtf8(value) {
  var encoded = utf8.encode(value);
  var decoded = utf8.decode(encoded);
  return decoded;
}

String toASCII(value) {
  var encoded = ascii.encode(value);
  var decoded = ascii.decode(encoded);
  return decoded;
}

A: The C# encrypt() method does the following:

*

*Generating a random 16 bytes salt and a random 16 bytes IV

*Deriving a key with PBKDF2 using the following parameters

*

*Key size 32 bytes

*Digest: Sha-1

*Iteration count: 100 (generally much too small for PBKDF2!)

*Encrypting with AES in CBC mode and PKCS#7 padding

*Concatenating salt, IV and ciphertext in that order and Base64 encoding

These functional building blocks must be replicated in the Dart code: For this you need a function that generates random values. So far, there is no such thing in the posted code. Also, the deriveKey() function for key derivation needs to be refactored. Other functionalities that could be encapsulated in functions are encryption with AES in CBC mode and PKCS#7 Padding as well as concatenation and encoding of the data.

*

*Possible implementation to generate random values:

SecureRandom getSecureRandom() {
  List<int> seed = List<int>.generate(32, (_) => Random.secure().nextInt(256));
  return FortunaRandom()..seed(KeyParameter(Uint8List.fromList(seed)));
}

*

*Refactoring of the deriveKey() method

Uint8List deriveKey(Uint8List salt, Uint8List passphrase){
  KeyDerivator derivator = KeyDerivator('SHA-1/HMAC/PBKDF2');
  Pbkdf2Parameters params = Pbkdf2Parameters(salt, 100, 256~/8);
  derivator.init(params);
  return derivator.process(passphrase);
}

*

*Implementation of a method that encrypts with AES in CBC mode and PKCS#7 padding:

Uint8List encryptAesCbcPkcs7(Uint8List plaintext, Uint8List key, Uint8List iv){
  CBCBlockCipher cipher = CBCBlockCipher(AESEngine());
  ParametersWithIV<KeyParameter> params = ParametersWithIV<KeyParameter>(KeyParameter(key), iv);
  PaddedBlockCipherParameters<ParametersWithIV<KeyParameter>, Null> paddingParams = PaddedBlockCipherParameters<ParametersWithIV<KeyParameter>, Null>(params, null);
  PaddedBlockCipherImpl paddingCipher = PaddedBlockCipherImpl(PKCS7Padding(), cipher);
  paddingCipher.init(true, paddingParams);
  Uint8List ciphertext = paddingCipher.process(plaintext);
  return ciphertext;
}

*

*And finally, a method for concatenating and encoding the data:

String concatAndEncode(Uint8List salt, Uint8List iv, Uint8List ciphertext){
  BytesBuilder saltIvCiphertext = BytesBuilder();
  saltIvCiphertext.add(salt);
  saltIvCiphertext.add(iv);
  saltIvCiphertext.add(ciphertext);
  String saltIvCiphertextB64 =  base64Encode(saltIvCiphertext.toBytes());
  return saltIvCiphertextB64;
}

Then these functional blocks only need to be wired:
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:pointycastle/export.dart';

...

Uint8List plaintext = Uint8List.fromList(utf8.encode("The quick brown fox jumps over the lazy dog"));
Uint8List passphrase = Uint8List.fromList(utf8.encode("my passphrase"));

// Generate random 16 bytes salt and random 16 bytes IV
SecureRandom secureRandom = getSecureRandom();
Uint8List salt = secureRandom.nextBytes(16);
Uint8List iv = secureRandom.nextBytes(16);

// Derive 32 bytes key via PBKDF2
Uint8List key = deriveKey(salt, passphrase);

// Encrypt with AES-256/CBC/PKCS#7 padding
Uint8List ciphertext = encryptAesCbcPkcs7(plaintext, key, iv);

// Concat salt|nonce|ciphertext and Base64 encode
String saltIvCiphertextB64 =  concatAndEncode(salt, iv, ciphertext);

print(saltIvCiphertextB64); // e.g. 3igL9PVjgWpCTwYHP2GluZ/8lUaNblnGFEjZFDEiGvdnjoR/RkXIEtcPmgsnC4MmsfesGXo8Jls2vnCISoVAkzIZvadxbw5Dq1QddeMPnS0=

A ciphertext generated with this Dart code can be decrypted with the C# code.


text:
Q: play audio in sequence Unity I'm working on a game in Unity.
I have a list of sounds.
When the player collides with an object, I want to play the 1st sound in the sound array. The second time player collides with that same object, I want to play the 2nd sound and so on.
When it reaches the end of the array, it will loop through the list again.
So I try to make a loop for that, and I called the function inside onTrigger2d. in player class.
However, it always plays the 1st sound in the list with every collision.
This is the code:
public class PlayNotes : MonoBehaviour
{

    public AudioSource adSource;
    public AudioClip[] adClips;

    public void PlayNote()
    {
        //--1.Loop through each audio clip--
        for ( int i = 0; i < adClips.Length; i++)
        {
            //--2.Assign current audio clip to audiosource--
            adSource.clip = adClips[i];

            //--3.play audio--
            adSource.Play();

        }

    }

}

A: Currently you are starting all sounds at once! Remember that your entire loop is executed in one single go. Actually I would rather expect only the last sound in your array to be played.

In general I would rather use AudioSource.PlayOneShot in your use case in order to not interrupt currently playing sounds but allow multiple concurrent sounds. E.g. for letting a sound finish playing with reverb etc while the next hit already triggers the next sound so they blend together. If you use AudioSource.Play it will stop playing the current clip and only play the new one.
And then simply add a counter for the currently played clip index with wrap around like e.g.
public class PlayNotes : MonoBehaviour
{
    public AudioSource adSource;
    public AudioClip[] adClips;

    // Index of the currently played sound
    private int index;

    public void PlayNote()
    {
        // Play current sound
        // I would rather use PlayOneShot in order to allow multiple concurrent sounds
        adSource.PlayOneShot(adClips[index]);

        // Increase the index, wrap around if reached end of array
        index = (index + 1) % adClips.Length;
    }
}


text:
Q: Pivot Table Sum Items, But Average Grand Total I have a Standard Pivot Table it has Date from the Columns and Numbers in the Value,
Column: Date | Numbers
I want the Numbers in the Rows to be Calculated as Sum, but I want the Grand Total to Average those Sums Rows
How is this possible?

A: Assuming you have PowerPivot, which you should if you have 2016, and assuming a table called Table1 loaded into the data model, you can add a measure for the sum, called say TotalNumber, which is just:
=SUM(Table1[Numbers])

Then add another measure which is the one you'll use in the pivot table:
=IF(HASONEVALUE(Table1[Date]),[TotalNumber],averagex(VALUES(Table1[Date]),Table1[TotalNumber]))


text:
Q: Problem when using writer_pdf_Export filter in UNO LibreOffice I installed LibreOffice [LibreOffice 6.1.3.2 10(Build:2)] and sdk on Ubuntu 16.03.
I used the java sample DocumentConverter in the sdk package to convert an odt in different formats.
With "MS WORD 97" or "Text" there is no problem but with "writer_pdf_Export" it ends in Exception
OK
java -jar /home/js/libreoffice6.1_sdk/LINUXexample.out/class/JavaDocumentHandlingExamples/DocumentConverter.jar "./test" "MS WORD 97" "doc" "/home/js/libreoffice6.1_sdk/LINUXexample.out/misc/JavaDocumentHandlingExamples/converted_files"
Connected to a running office ...

The converted documents will stored in "/home/js/libreoffice6.1_sdk/LINUXexample.out/misc/JavaDocumentHandlingExamples/converted_files!
[test]
   test1.odt

KO
java -jar /home/js/libreoffice6.1_sdk/LINUXexample.out/class/JavaDocumentHandlingExamples/DocumentConverter.jar "./test" "writer_pdf_Export" "pdf" "/home/js/libreoffice6.1_sdk/LINUXexample.out/misc/JavaDocumentHandlingExamples/converted_files"
Connected to a running office ...

The converted documents will stored in "/home/js/libreoffice6.1_sdk/LINUXexample.out/misc/JavaDocumentHandlingExamples/converted_files!
[test]
com.sun.star.task.ErrorCodeIOException: SfxBaseModel::impl_store <file:////home/js/libreoffice6.1_sdk/LINUXexample.out/misc/JavaDocumentHandlingExamples/converted_files/test1.pdf> failed: 0x81a(Error Area:Io Class:Parameter Code:26)
    at   com.sun.star.lib.uno.environments.remote.Job.remoteUnoRequestRaisedException(Job.java:158)
    at com.sun.star.lib.uno.environments.remote.Job.execute(Job.java:122)
    at com.sun.star.lib.uno.environments.remote.JobQueue.enter(JobQueue.java:312)
    at com.sun.star.lib.uno.environments.remote.JobQueue.enter(JobQueue.java:281)
    at com.sun.star.lib.uno.environments.remote.JavaThreadPool.enter(JavaThreadPool.java:81)
    at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge.sendRequest(java_remote_bridge.java:618)
    at com.sun.star.lib.uno.bridges.java_remote.ProxyFactory$Handler.request(ProxyFactory.java:145)
    at com.sun.star.lib.uno.bridges.java_remote.ProxyFactory$Handler.invoke(ProxyFactory.java:129)
    at com.sun.proxy.$Proxy5.storeAsURL(Unknown Source)
    at DocumentConverter.traverse(DocumentConverter.java:137)
    at DocumentConverter.main(DocumentConverter.java:216)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.star.lib.loader.Loader.main(Loader.java:132)
  test1.odt

I need to use the UNO interface through java to convert to any format, and I really need pdf also...
Any help?

A: Are you doing "storeAsURL" or "storeToURL"?
"storeAsURL" is analogous to "Save As" -- for when you are saving a document in an editable format.
"storeToURL" is analogous to "Export" -- for generating an output in an uneditable format.
So I suspect that, if you switch from "storeAsURL" to "storeToURL", you'll get the PDF you wanted.


text:
Q: ajax call only once on first time click of an element I am designing a chatting application just like WhatsApp web . in that right now I have dummy data for chats. so suppose, if I click on any chat then corresponding chat logs are displayed but these chat logs are dummy data. same way I have done for other chats also but now what I want is if I click on any of the chat then an ajax call should happen and chat logs are rendered and displayed dynamically but this ajax call should happen only one for every chat that means if I click for first time on some chat an ajax call should happen but if click the second time no ajax call should happen.
any suggestions..?

A: Question: I understood that, once you click on a chat and got data, from the next time ajax call should not be made which will be an extra call.
Solution: The solution for your question will be, first time when you get response from the server, save it in localStorage, A localStorage is a powerful feature of browser which stores data in the browser session.
Implemenatation:
An example api call,
$.post(
    "chat-api-url",
    { chat: "chatId" },
    function(data) {
        localStorage.setItem('chatId', 'data')
    }
);

So, now after click in jquery check condition,
if(localStorage.getItem('chatId') == undefined)
{
    $.post(
    "chat-api-url",
    { chat: "chatId" },
        function(data) {
            localStorage.setItem('chatId', data)
            this.chatData = data;
        }
    );
} else{
    this.chatData = localStorage.getItem('chatId');
}

PS:
localStorage.setItem stores into localstorage
localStorage.getItem retrieves from. localstorage
Here is a documeantation regarding different storages


text:
Q: Telegram BOT Api: how to send a photo using PHP? The sendPhoto command require an argument photo defined as InputFile or String.
The API doc tells:
Photo to send. You can either pass a file_id as String to resend a photo
that is already on the Telegram servers, or upload a new photo using
multipart/form-data.

And
InputFile

This object represents the contents of a file to be uploaded. Must be
posted using multipart/form-data in the usual way that files are
uploaded via the browser.

So I tried this method
    $bot_url    = "https://api.telegram.org/bot<bot_id>/";
    $url = $bot_url . "sendPhoto?chat_id=" . $chat_id;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Content-Type:multipart/form-data"
    ));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        "photo"     => "@/path/to/image.png",
    ));
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/root/dev/fe_new.png"));
    $output = curl_exec($ch);

The curls is executed, but Telegram reply this to me:
Error: Bad Request: Wrong persistent file_id specified: contains wrong
characters or have wrong length

I also tried replacing @/path... with a file_get_contents, but in this case Telegram give me an empty reply (and curl_error is empty !).
What the way to send a photo to telegram using php + curl ?

A: This code helps me alot which I get from php.net website here
Visit http://php.net/manual/en/class.curlfile.php#115161
(Vote Up this code in php website).
I just change headers in this code for telegram bot to send image just copy this function
function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {

          // invalid characters for "name" and "filename"
          static $disallow = array("\0", "\"", "\r", "\n");

          // build normal parameters
          foreach ($assoc as $k => $v) {
              $k = str_replace($disallow, "_", $k);
              $body[] = implode("\r\n", array(
                  "Content-Disposition: form-data; name=\"{$k}\"",
                  "",
                  filter_var($v),
              ));
          }

          // build file parameters
          foreach ($files as $k => $v) {
              switch (true) {
                  case false === $v = realpath(filter_var($v)):
                  case !is_file($v):
                  case !is_readable($v):
                      continue; // or return false, throw new InvalidArgumentException
              }
              $data = file_get_contents($v);
              $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
              $k = str_replace($disallow, "_", $k);
              $v = str_replace($disallow, "_", $v);
              $body[] = implode("\r\n", array(
                  "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
                  "Content-Type: image/jpeg",
                  "",
                  $data,
              ));
          }

          // generate safe boundary
          do {
              $boundary = "---------------------" . md5(mt_rand() . microtime());
          } while (preg_grep("/{$boundary}/", $body));

          // add boundary for each parameters
          array_walk($body, function (&$part) use ($boundary) {
              $part = "--{$boundary}\r\n{$part}";
          });

          // add final boundary
          $body[] = "--{$boundary}--";
          $body[] = "";

          // set options
          return @curl_setopt_array($ch, array(
              CURLOPT_POST       => true,
              CURLOPT_POSTFIELDS => implode("\r\n", $body),
              CURLOPT_HTTPHEADER => array(
                  "Expect: 100-continue",
                  "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
              ),
          ));
      }

Basic Try:Now just use this code by sending photo name with path and chat id
here is it how:-
$array1=array('chat_id'=><here_chat_id>);
$array2=array('photo'=>'index.jpg') //path
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.telegram.org/<bot_token>/sendPhoto");
curl_custom_postfields($ch,$array1,$array2);//above custom function
$output=curl_exec($ch);
close($ch);

For sending png or other methods change curl_custom function according to your need.

A: This is my working solution, but it requires PHP 5.5:
$bot_url    = "https://api.telegram.org/bot<bot_id>/";
$url        = $bot_url . "sendPhoto?chat_id=" . $chat_id ;

$post_fields = array('chat_id'   => $chat_id,
    'photo'     => new CURLFile(realpath("/path/to/image.png"))
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);

A: I searched a lot online but didn't find the answer. But, your question solved my problem ... I just changed your code and that answered it for me ...
I changed your code to this:
$chat_id=chat Id Here;

$bot_url    = "https://api.telegram.org/botYOUR_BOT_TOKEN/";
$url = $bot_url . "sendPhoto?chat_id=" . $chat_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    "photo"     => "@path/to/image.png",
));
curl_setopt($ch, CURLOPT_INFILESIZE, filesize("path/to/image.png"));
$output = curl_exec($ch);
print$output;

A: You can use this API: https://github.com/mgp25/Telegram-Bot-API
example:
$tg->sendPhoto($chat_id, $image, $caption);

You can use either a stored image or URL.

A: <?php

$BASH_Command='curl -s -X POST "https://api.telegram.org/bot<YourToken>/sendPhoto?chat_id=<YourID>" -F photo="@/path/to/imagefile.jpeg" -F caption="TheImage" > /dev/null &';

echo exec($BASH_Command);
?>

A: This a bad idea, but you can use some like that:
#!/bin/bash

set -x
set -e

BDIR=/tmp/${RANDOM}
TG_TOKEN=""
TG_CHAT_ID=

mkdir -p ${BDIR}
chmod -R 777 ${BDIR}
su postgres -c "pg_dumpall -f ${BDIR}/postgre.sql"
tar czf ${BDIR}/${HOSTNAME}.tar.gz /var/lib/grafana/ /etc/grafana/ ${BDIR}/postgre.sql

curl -F caption="$(date)" -F chat_id="${TG_CHAT_ID}" -F document=@"${BDIR}/${HOSTNAME}.tar.gz" https://api.telegram.org/bot${TG_TOKEN}/sendDocument

rm -rf ${DBIR}

A: I thought I should extend the answer to include uploading from an external url but it still involves a process of saving the image to a folder first. Then I added a caption to the image.
    $bot_url    = "https://api.telegram.org/bot<bot_id>/";
    $url        = $bot_url . "sendPhoto?chat_id=" . $chat_id ;
    $caption = 'Telegram Image SendPhoto function';
    $img = '/path/to/save_image.png'; //local path where image should be saved

    /* Get the image from the URL and save to your own path. You need to add
    allow_url_fopen=On to your php.ini file for the below code to work */

    file_put_contents($img, file_get_contents("https://your_image.com/pic.jpg"));
    $post_fields = array('chat_id'   => $chat_id,
    'photo'     => new CURLFile(realpath($img)),
    'caption' => $caption
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
   "Content-Type:multipart/form-data"
    ));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    $output = curl_exec($ch);
    curl_close($ch); //close curl

That's all!