text:
Q: How to add back button with confirmation message in android webview ( kotlin ) I created a android webview in kotlin. I want to add back button with previous page web view check and and no web view final confirmation with yes no exit option. Right now webview window directly closed in first back press.
Kindly suggest how can I achieve this ?
This my homeactivity.kt
package murait.the.android.mania

import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.webkit.*
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.navigation.ui.AppBarConfiguration
import com.google.android.gms.ads.*
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import com.google.android.material.navigation.NavigationView
import murait.the.android.mania.databinding.ActivityHomeBinding
import android.webkit.WebSettings

class HomeActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityHomeBinding
    private val url = "https://www.demopage.com/"
    private var currentUrl = ""
    private val FILECHOOSER_RESULTCODE = 190
    private var mInterstitialAd: InterstitialAd? = null
    private var interAdRequest: AdRequest? = null
    private var progressDialog: ProgressDialog? = null
    private var mUploadMessage: ValueCallback<Array<Uri>>? = null
    private var prefManager: PrefManager? = null
    private var mAdIsLoading: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityHomeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.appBarHome.toolbar)

        MobileAds.initialize(this) {}

        prefManager = PrefManager(baseContext)
        progressDialog = ProgressDialog(this)
        progressDialog?.setMessage("Loading...")

        val actionBarDrawerToggle = ActionBarDrawerToggle(
            this,
            binding.drawerLayout,
            binding.appBarHome.toolbar,
            R.string.app_name,
            R.string.app_name
        );

        loadBannerAds()
        loadInterAds()

        if (isOnline()) {
            binding.appBarHome.contentMain.llError.rlContent.visibility = View.GONE
            binding.appBarHome.contentMain.webView.visibility = View.VISIBLE
            startWebView(url)
        } else {
            binding.appBarHome.contentMain.llError.rlContent.visibility = View.VISIBLE
            binding.appBarHome.contentMain.webView.visibility = View.GONE
            if (progressDialog != null && progressDialog?.isShowing == true)
                progressDialog?.dismiss()
        }
    }

    private fun loadInterAds() {
        var interAdRequest = AdRequest.Builder().build()

        InterstitialAd.load(
            this, getString(R.string.interstitial_full_screen), interAdRequest,
            object : InterstitialAdLoadCallback() {
                override fun onAdFailedToLoad(adError: LoadAdError) {
                    mInterstitialAd = null
                    mAdIsLoading = false
                }

                override fun onAdLoaded(interstitialAd: InterstitialAd) {
                    mInterstitialAd = interstitialAd
                    mAdIsLoading = false
                }
            }
        )
    }

    private fun showInterAds(url: String) {
        if (mInterstitialAd != null) {
            mInterstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdDismissedFullScreenContent() {
                    binding.appBarHome.contentMain.webView.loadUrl(url)
                    loadInterAds()
                }

                override fun onAdFailedToShowFullScreenContent(adError: AdError?) {

                }

                override fun onAdShowedFullScreenContent() {
                    mInterstitialAd = null;
                }
            }
            mInterstitialAd?.show(this)
        } else {
            binding.appBarHome.contentMain.webView.loadUrl(url)
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun startWebView(url: String) {

        binding.appBarHome.contentMain.webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                prefManager?.addVar()
                if (mInterstitialAd != null && prefManager?.tVar?.rem(PrefManager.ADS_SHOW_TIME) == 0) {
                    showInterAds(url.toString())
                } else {
                    view?.loadUrl(url.toString())
                }
                return true
            }

            //Show loader on url load
            /*override fun onLoadResource(view: WebView?, url: String?) {
                if (progressDialog == null) {
                    progressDialog = ProgressDialog(this@HomeActivity)
                    progressDialog?.setMessage("Loading...")
                }
                if (progressDialog != null && progressDialog?.isShowing == false)
                    progressDialog?.show()
                prefManager!!.addVar()
            }*/

            override fun onPageFinished(view: WebView?, url: String?) {
                try {
                    if (progressDialog!!.isShowing) {
                        progressDialog!!.dismiss()
                        prefManager!!.addVar()
                        progressDialog = null
                    }
                } catch (exception: Exception) {
                    exception.printStackTrace()
                }
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                //super.onReceivedHttpError(view, request, errorResponse);
                if (progressDialog != null && progressDialog?.isShowing == false) progressDialog?.dismiss()
            }
        }
        binding.appBarHome.contentMain.webView.webChromeClient = object : WebChromeClient() {
            override fun onShowFileChooser(
                webView: WebView,
                filePathCallback: ValueCallback<Array<Uri>>,
                fileChooserParams: FileChooserParams
            ): Boolean {
                mUploadMessage?.onReceiveValue(null)
                mUploadMessage = filePathCallback
                val i = Intent(Intent.ACTION_GET_CONTENT)
                i.addCategory(Intent.CATEGORY_OPENABLE)
                i.type = "*/*"
                startActivityForResult(
                    Intent.createChooser(i, "File Chooser"),
                    FILECHOOSER_RESULTCODE
                )
                return true
            }

        }

        // Other webview options
        binding.appBarHome.contentMain.webView.settings.javaScriptEnabled = true
        binding.appBarHome.contentMain.webView.settings.domStorageEnabled = true
        // Other webview options
        binding.appBarHome.contentMain.webView.settings.loadWithOverviewMode = true
        binding.appBarHome.contentMain.webView.settings.useWideViewPort = true
        binding.appBarHome.contentMain.webView.scrollBarStyle = WebView.SCROLLBARS_OUTSIDE_OVERLAY
        binding.appBarHome.contentMain.webView.isScrollbarFadingEnabled = false
        binding.appBarHome.contentMain.webView.settings.builtInZoomControls = false
        binding.appBarHome.contentMain.webView.settings.allowContentAccess = true

        binding.appBarHome.contentMain.webView.setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            val i = Intent(Intent.ACTION_VIEW)
            i.data = Uri.parse(url)
            startActivity(i)
        })

        currentUrl = url
        //Load url in webview
        //Load url in webview
        binding.appBarHome.contentMain.webView.loadUrl(url)
    }

    private fun loadBannerAds() {
        val adRequest = AdRequest.Builder().build()
        binding.appBarHome.contentMain.adView.loadAd(adRequest)

        binding.appBarHome.contentMain.adView.adListener = object : AdListener() {
            override fun onAdLoaded() {
                binding.appBarHome.contentMain.adView.visibility = View.VISIBLE
            }

            override fun onAdFailedToLoad(adError: LoadAdError) {
                binding.appBarHome.contentMain.adView.visibility = View.GONE
            }

            override fun onAdOpened() {
                // Code to be executed when an ad opens an overlay that
                // covers the screen.
            }

            override fun onAdClicked() {
                // Code to be executed when the user clicks on an ad.
            }

            override fun onAdClosed() {
                // Code to be executed when the user is about to return
                // to the app after tapping on an ad.
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        //menuInflater.inflate(R.menu.home, menu)
        return true
    }

    override fun onBackPressed() {
        if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            binding.drawerLayout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    private fun closeDrawer() {
        binding.drawerLayout.closeDrawer(GravityCompat.START)
    }

    override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
        closeDrawer()
        when (menuItem.getItemId()) {

        }
        return false
    }

    private fun isOnline(): Boolean {
        val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
        val netInfo = cm.activeNetworkInfo
        return netInfo != null && netInfo.isConnectedOrConnecting
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        super.onActivityResult(requestCode, resultCode, intent)
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage || intent == null || resultCode != RESULT_OK) {
                return
            }
            val dataString = intent.dataString
            mUploadMessage!!.onReceiveValue(arrayOf(Uri.parse(dataString)))
            mUploadMessage = null
        }
    }
}

This my activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        android:id="@+id/app_bar_home"
        layout="@layout/app_bar_home"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.drawerlayout.widget.DrawerLayout>

A: I think this super.onBackPressed() in onBackPressed causes immediate exit:
override fun onBackPressed() {
    if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
        binding.drawerLayout.closeDrawer(GravityCompat.START)
    } else {
        super.onBackPressed()
    }
}

In stead of just a bare super.onBackPressed(), check if WebView#canGoBack. If yes, WebView#goBack. If not, show Snackbar to confirm to close. In below example, webView is the WebView instance (it may be binding.appBarHome.contentMain.webView in your code):
    } else {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            Snackbar.make(
                findViewById(android.R.id.content),
                "Are you sure to close?",
                Snackbar.LENGTH_LONG
            ).setAction("close") { super.onBackPressed() }.show()
        }
    }

A: The recommended way these days is to add a callback to the OnBackPressedDispatcher. You can add a bunch of these to create a hierarchy of handlers, so you can have one that checks if you'll lose unsaved data, one that checks if you're about to back out of the app, etc. (One of the examples they give is for handling WebView back navigation)
The callbacks are prioritised by the order they were added, most-recent first, and you can enable and disable them to "turn them on and off" and allow a lower-priority callback to handle the back press. If none are added/enabled, it just does the usual onBackPressed handling.
You'd have to interface with your WebView and coordinate telling it to go back through the history, and having it tell your Fragment/Activity that it has no more pages to back through (so you can show a warning dialog), but I guess you want something like this:
class HomeActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    lateinit var backPressedCallback: OnBackPressedCallback

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        backPressedCallback = onBackPressedDispatcher.addCallback(this) {
            callWebViewBack()
        }
    }
    ...

    fun callWebViewBack() {
        // send a "Back" message to your webview
    }

    fun onWebViewBackedOut() {
        // this is a terrible name, but when your webview gets the "Back" message
        // but it has no more history to back through, it needs to call this function
        // so the Activity can display the confirmation dialog here
        showExitConfirmationDialog()
    }

    // when you handle the result from your dialog, you can call this to disable
    // the handler that tells the webview to go back, then send the back button event
    // (which will invoke the next callback in the chain, handling something else,
    // if you've added one, otherwise it'll do the usual back button behaviour)
    fun exitWebView() {
        backPressedCallback.disable()
        onBackPressed()
    }
}


text:
Q: What data structure should I use to hold a collection of functions in F# Some features of the data structure worth mentioning:
1. The functions will NOT all have the same signatures (my main issue)
2. The data structure does not have to be immutable
I'm comfortable with all the main vanilla data structures, my concern is around what "generalized type" is the best umbrella type to represent a function in such a collection of functions. In particular, is their anything better than just boxing them as obj / System.Object?
When the function is being "packed" into the data structure I will know it's signature. This can be stored in some way and linked to this function such that it can be used to "unpack" the function into the correct form when it is needed.
I am assuming that I can create function signature types and store them in a collection of their own - perhaps this is a bad assumption though? In other words:
let f1: float-> float
let f2: string->bool->float

Can the typeof(f1) and typeof(f2) be stored in the same data structure. I would think that since they are both of type Type this should be possible
In reply to the comment below by @ildjarn: The expected signatures could be any 1-5 input parameter combinations of the usual suspects like float, string, bool, date and with the result parameter varying equally over float | string | bool.
Taking the above into account, how best can the functions be stored for later retrieval and application (partial or full) and or composition with other functions.
EDIT
The simplest approach I can come up with is the following:
let f1 x = exp x
let t1 = f1.GetType()
let o1 = box f1 // alternate syntax
let f11 = o1 :?> t1 // ?? FAILS HERE!!!!!
f11 3.0

But I don't know how to downcast from the object back to the function type I had prior to boxing.

A: Build yourself a discriminated union (DU) for the different sigs:
type Function<'a, 'b, 'c, 'd> =
| Unary of ('a -> 'd)
| Binary of ('a -> 'b -> 'd)
| Ternary of ('a -> 'b -> 'c -> 'd)

then make say Function<'a, 'b, 'c, 'd> list to hold your functions. This should work well enough, so long as the signatures are not too heterogeneous. Because you still require to have at most as many different kinds of signatures as you have cases in your DU.
A fully working example might look like this:
open System

type Operator =
| Parse of (string -> int)
| Unary of (int -> int)
| Binary of (int -> int -> int)
| Print of (int -> unit)

type Data =
| Int of int
| String of string

type StackContent =
| Data of Data
| Operator of Operator

let input = [
    Data (String "3")
    Operator (Parse Int32.Parse)
    Data (String "5")
    Operator (Parse Int32.Parse)
    Operator (Binary (+))
    Operator (Unary (~-))
    Operator (Print (printfn "%d"))]

let eval input =
    let rec eval = function
        | Data d :: inputTail, stack -> eval (inputTail, d::stack)
        | Operator (Parse parse) :: inputTail, String s :: stackTail -> eval (inputTail, Int (parse s) :: stackTail)
        | Operator (Binary (++)) :: inputTail, Int l :: Int r :: stackTail -> eval (inputTail, Int (l ++ r) :: stackTail)
        | Operator (Unary (!)) :: inputTail, Int i :: stackTail -> eval (inputTail, Int !i :: stackTail)
        | Operator (Print print) :: inputTail, Int i :: stackTail ->
            print i
            eval (inputTail, stackTail)
        | [], [] -> ()
        | input, stack -> failwithf "the following thing is not properly typed\nInput: %A\Stack: %A" input stack
    eval (input,[])

eval input

A: This depends on the context in which you are doing this, but you'll need to wrap the functions and the arguments in some way. You could box them and work with obj values (and then use reflection), you could wrap them in discriminated unions and you could likely do other things.
The discriminated union approach is probably the easiest. You could have a DU for different kinds of values that you support:
type Value =
  | Int of int
  | String of string

A function then takes a list of values and produces a value (you can make it option, because the function might fail if it gets incorrect arguments):
type Function = Value list -> Value option

To define your collection of functions, you can create a list. Each function will pattern match on the input to make sure it is getting the expected values:
let functions =
  [ ( function
      | [ Int n; String t ] ->
          Some(String(sprintf "The %s is %d" t n))
      | _ -> None) ]

Then you can create a list of arguments and call the function:
let arguments = [ Int 42; String "Answer" ]
functions.[0] arguments

This is really just one of multiple options, but it is the simplest one to start from. The disadvantage is that you need to explicitly unwrap the parameters and wrap the results in Value - but you could probably later automate that using some reflection or type casting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How "this" keyword actually works inside Intent constructor arguement? Intent construcotr's arguements require object of Context class but down here inside this code I am passing "this" which means object of MainActivity class object. How it works? because it requires Context Class instance but i am passing MainActivity's instance.
const val EXTRA_MESSAGE = "com.example.myfirstApp.MESSAGE"

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun sendMessage(view: View){
        val editText = findViewById<EditText>(R.id.editText)
        val message = editText.text.toString()
        val intent =Intent(this,DisplayMessageActivity::class.java).apply{
// if I use MainActivity() instead of this , gives me error
            putExtra(EXTRA_MESSAGE, message)
        }
        startActivity(intent)
    }
}

Here, this means MainActivity's instance, but if I use MainActivity() instead of this it gives me error. Whereas this and MainActivity() are same thing here.

A: In Android Activity, Service, BroadcastReceiver, Application all extends Context. So you can pass them in place of Context.
You can see all the class that an Activity class extends here.


text:
Q: Updating a record in JET (Access) using VB.NET I am trying to update a record in Access through VB.NET. This is my code thus far. The objective is to search a barcode, it returns the data associated with it and the user is able to change the data and save the updated data. I have everything except the update part. This is my save button with the update code. I hope I made this clear.
EDIT: Sorry. I forgot to tell you all my problem. It returns 0 rows affected, no error message.
 Private Sub btnEditProductSave_Click(sender As System.Object, e As System.EventArgs) Handles btnEditProductSave.Click
    'Creates Transaction and Connection Objects
    Dim Transaction As OleDb.OleDbTransaction = Nothing
    Dim connection As OleDb.OleDbConnection = Nothing

    Try

        'Assign the Connection
        connection = New OleDb.OleDbConnection(My.Settings.POS_NEWConnectionString)
        'Opens the Connection and begins the Transaction
        connection.Open()
        Transaction = connection.BeginTransaction

        Dim barcode As String = txtEditProductBarcode.Text
        Dim name As String = txtEditProductName.Text
        Dim supplier As String = cbEditProductSupplier.SelectedValue
        Dim sell As Decimal = Val(txtEditProductSellPrice.Text)
        Dim quantity As Integer = numQuantity.Value
        Dim discount As Decimal = Val(txtEditProductDiscount.Text)
        Dim department As Integer = Val(txtEditProductDepartment.Text)

        Dim SQL As String = "UPDATE PRODUCT SET ProductName = @productName, SupplierId = @supplier, SellPrice = @sellPrice, Quantity = @quantity, DiscountPrice = @discount, DepartmentNumber = @dept WHERE ProductBarcode = @barcode"

        'Creates the Command for the Transaction
        Dim CT1 As New OleDb.OleDbCommand

        'Assigns a connection and transaction to a new command object
        CT1.Connection = connection
        CT1.Transaction = Transaction

        CT1.Parameters.AddWithValue("@barcode", barcode)
        CT1.Parameters.AddWithValue("@productName", name)
        CT1.Parameters.AddWithValue("@supplier", supplier)
        CT1.Parameters.AddWithValue("@sellPrice", sell)
        CT1.Parameters.AddWithValue("@quantity", quantity)
        CT1.Parameters.AddWithValue("@discount", discount)
        CT1.Parameters.AddWithValue("@dept", department)

        CT1.CommandText = SQL

        Dim number As Integer = CT1.ExecuteNonQuery

        MsgBox(number & " of row were affected")

        CT1.Dispose()

    Catch ex As System.Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    End Try
End Sub

A: Parameters in OleDb are in index order, not name.
Try it this way (barcode parameter last):
    CT1.Parameters.AddWithValue("@productName", name)
    CT1.Parameters.AddWithValue("@supplier", supplier)
    CT1.Parameters.AddWithValue("@sellPrice", sell)
    CT1.Parameters.AddWithValue("@quantity", quantity)
    CT1.Parameters.AddWithValue("@discount", discount)
    CT1.Parameters.AddWithValue("@dept", department)
    CT1.Parameters.AddWithValue("@barcode", barcode)

You also have a BeginTransaction but no commit.
It should look something like this:
Dim tx As OleDb.OleDbTransaction = connection.BeginTransaction

// blah - blah - blah

tx.Commit()


text:
Q: Wiring up the Search Charm in Universal WinRT apps I haven't seen any examples of how to use the Search Charm in a Universal App.
Usually you wire up the Search Charm using:
SearchPane.GetForCurrentView().QuerySubmitted += new TypedEventHandler<SearchPane, SearchPaneQuerySubmittedEventArgs>(OnQuerySubmitted);
However that doesn't exist in the Shared App.xaml nor does the Windows.ApplicationModel.Search namespace.
Anyone seen how to accomplish this?

A: I think you just need to override the OnSearchActivated method in App.xaml.cs:
protected override async void OnSearchActivated(SearchActivatedEventArgs args)
{
    await LoadApplicationAsync(args.PreviousExecutionState);
    // TODO: Handle search query in args
}

LoadApplicationAsync contains the logic which can usually be found in the OnLaunched method.
See my sample project:
https://xp-dev.com/svn/mytoolkit/-%20Samples/SampleWindowsStoreApp/App.xaml.cs
https://xp-dev.com/svn/mytoolkit/-%20Samples/SampleWindowsStoreApp/Views/SearchSamplePage.xaml.cs


text:
Q: How to shift the bits of binary number either to the left or right without losing the shifted bits in python Let's say for example that I have this 16-bit binary 0b1010001110011011 and i want to shift it by 6 bits to the left so the result is 0b1110011011101000.
When i tried print(bin(example << 6)) the result is 0b1010001110011011000000


text:
Q: Force download file php after has been saved in directory? Im creating a large mysql database which has business numbers of companies.
I have finaly been able to create the code which allows to save results as csv in a specific directory called "/uploads". everything works fine. Now i need to have a button that downloads file the file after query&save the csv file.
the code is this:
 <?php
include 'includes/connection.php';

if(isset($_POST['submit']))
{
$cap = $_POST ['cap'];
$prov = $_POST ['provincia'];
$citta = $_POST ['citta'];

$filename = 'uploads/'.strtotime ("now").'.csv';

$sql = mysql_query("SELECT * FROM business_total  WHERE cap LIKE'%$cap%' AND provincia LIKE '%$prov%' AND citta LIKE '%$citta%'") or die(mysql_error());
$num_rows = mysql_num_rows($sql);
echo 'totale risultato: '.''.$num_rows.''.'
';
if($num_rows >= 1)
{

$row = mysql_fetch_assoc($sql);
$fp = fopen($filename,"w");

$seperator = "";
$comma = "";

//$name è la prima righa, quella dei valori
foreach($row as $name => $value)
{
    $seperator.= $comma.''.str_replace('','""',$name);
    $comma =",";

}
$seperator .="\n";

fputs($fp,$seperator);
mysql_data_seek($sql, 0);

//Primo row per le testate, questo row per il contenuto query

while($row = mysql_fetch_assoc($sql))
{

$seperator = "";
$comma = "";

//$name è la prima righa, quella dei valori
foreach($row as $name => $value)
{
    $seperator.= $comma.''.str_replace('','""',$value);
    $comma =",";

}
$seperator .="\n";

fputs($fp,$seperator);
}
fclose($fp);

}
else
{
echo 'Non ci sono risultati compatibili con la tua ricerca';
}

}

?>

  <form method="post" action="index.php">

 <input type="text" name="cap" placeholder="Cerca per cap"/>

  <input type="text" name="provincia" placeholder="Cerca per prov"/>

  <input type="text" name="citta" placeholder="Cerca per citta"/>

   <input type="submit" name="submit" value="submit"/>

 </form>

A: I solved the problem.
added this piece before th php close tag (?>)
here is the code:
                        $qfile = $filename;

                        echo $qfile;

                if (file_exists($qfile)) {
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename='.basename($qfile));
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($qfile));
                    readfile($qfile);
                    exit;
    }

 ?>


text:
Q: How to find duplication values in multidimensional arrays using recursion I have an array named A as following:
  {
    name: 'activityRelatedManager',
    meta: {
      title: 'Activity Related Manager',
      permissions: []
    },
    children: [
      {
        name: 'activityPublish',
        meta: { title: 'Publish Activity', permissions:[] }
      },
      {
        name: 'activityManager',
        meta: { title: 'Manage Activity', permissions:[] }
      },
      {
        name: 'activityTypeManager',
        meta: { title: ' Manage Activity Type', permissions:[] }
      },
      {
        name: 'activityLocationManager',
        meta: { title: ' Manage Activity Location', permissions:[] }
      }
    ]
  },

I also have an array named B like this:
[
    {
      "id": 1,
      "name": "activityRelatedManager",
      "permissions": [
        "activity:publish"
      ]
    },
    {
      "id": 2,
      "name": "activityManager",
      "permissions": [
        "activity:index",
        "activity:show"
      ]
    },
    {
      "id": 3,
      "name": "activityTypeManager",
      "permissions": []
    }
]

What i want to do is to find the duplicated values based on 'name' key in B, and then assign the permissions value to A. The result should be something like this:
  {
    name: 'activityRelatedManager',
    meta: {
      title: 'Activity Related Manager',
      permissions: ["activity:publish"]
    },
    children: [
      {
        name: 'activityManager',
        meta: { title: 'Manage Activity', permissions:["activity:index", "activity:show"] }
      },
      {
        name: 'activityTypeManager',
        meta: { title: ' Manage Activity Type', permissions:[] }
      }
    ]
  },

I think the assignment is easy, but how to find the duplication?
  A.map(ele => {
    if (!ele.name || (!ele.meta && !ele.meta.permissions)) return
    for (let i = 0; i < B.length; i++) {
      const element = B[i]
      if (ele.name === element.name) {
        ele.meta.permissions = element.permissions
      }
    }
    if (ele.children) {
      makePermissionRouters(B, A.children)
    }
  })
  return clientAsyncRoutes

I'd appreciate it if someone can help me solve this question.

A: I would break out a utility function here, a deep version of a filterMap function, which takes a predicate and a transformation function and recursively filters out every level of children according to the predicate and then transforms the remaining ones with the supplied function.
You can use this by first reformatting B to be a mapping -- here we call it perms -- between names and lists of permissions, then calling this deepFilterMap with a predicate that checks if the object's name is in perms and a transform that sets meta.permissions to that value.
This version of deepFilterMap is specific to structures where the descendant nodes are in an array called children.  We could make it more generic, but that would involve another parameter to the function.  It's an interesting exercise, but perhaps overkill here.

const deepFilterMap = (pred, transform) => (tree) =>
  pred (tree)
    ? {
        ... transform (tree),
        ... (tree.children
              ? {children: tree .children
                                .filter (pred)
                                .map (deepFilterMap (pred, transform))
                }
              : {}
            )
      }
    : {}

const transform = (A, B) => {
  const perms = Object .fromEntries (B .map (
    ({name, permissions}) => [name, permissions])
  )

  return deepFilterMap (
    ({name}) => name in perms,
    ({name, meta, ...rest}) => ({
      name,
      meta: {...meta, permissions: perms [name]},
      ...rest
    })
  ) (A)
}

const A = {name: "activityRelatedManager", meta: {title: "Activity Related Manager", permissions: []}, children: [{name: "activityPublish", meta: {title: "Publish Activity", permissions: []}}, {name: "activityManager", meta: {title: "Manage Activity", permissions: []}}, {name: "activityTypeManager", meta: {title: " Manage Activity Type", permissions: []}}, {name: "activityLocationManager", meta: {title: " Manage Activity Location", permissions: []}}]};
const B = [{id: 1, name: "activityRelatedManager", permissions: ["activity: publish"]}, {id: 2, name: "activityManager", permissions: ["activity: index", "activity: show"]}, {id: 3, name: "activityTypeManager", permissions: []}];

console .log (transform (A, B))
.as-console-wrapper {min-height: 100% !important; top: 0}

We could, of course, inline the work of deepFilterMap into our main function.  Overall, we would have fewer lines of code.  But to my mind, breaking down the complexity in this manner is much more maintainable.  And you have a potentially reusable function available now.


text:
Q: How can I remove an entire folder under Storage? I have a problem deleting my entire folder on firebase storage. I always get a 'storageRef.listAll is not a function' error when I specify the reference to the path. I would like to delete the complete path with all possibly existing images.
const storage = getStorage();

const storageRef = ref(
  storage,
  `${aktuellerUser._id}/artikelBilder/`
);

storageRef
  .listAll()
  .then((listResults) => {
    const promises = listResults.items.map((item) => {
      return item.delete();
    });
    Promise.all(promises);
  })
  .catch((error) => {
    console.log(error);
  });

error TypeError: storageRef.listAll is not a function

A: You are using the new Firebase Modular SDK where listAll() is a top level function and not a method on StorageReference. Similarly, you need to use deleteObject() to delete a file now instead of .delete() method as shown below:
import {
  getStorage,
  ref,
  listAll,
  deleteObject
} from "firebase/storage";

listAll(storageRef)
  .then(async (listResults) => {
    const promises = listResults.items.map((item) => {
      return deleteObject(item);
    });

    await Promise.all(promises);
  })


text:
Q: How kubernetes port-forward choose pod when forward to a deployment? Let say there's a deployment named my-deployment which is consisted of 3 pods, now we use port-forward forward a local port to this deployment :
kubectl port-forward deployment/my-deployment 8888 9999

My question is : when I visit localhost:8888 serveral times then which pod would be forwarded to ? Always forward to a fixed pod(like first pod) ? Or forward it by random ? Or use round-roubin strategy ?

A: when I visit localhost:8888 serveral times then which pod would be forwarded to ?
Will forward to the first pod sorted by name.
Always forward to a fixed pod(like first pod) ?
Fixed.
Or forward it by random ? Or use round-roubin strategy ?
Fixed to the first pod sorted by name.
Presumed you have performed a port-forward command and curl successfully. Now if you scale the deployment to 0; then scale up; if you curl again now you will get an error. This is because the pod that the port forwarded to has been terminated during the scale to 0.


text:
Q: How to use wavesurfer.js with a node bundler? I am trying to use wavesurfer.js with node bundler, as indicated here:
https://www.npmjs.com/package/wavesurfer.js?activeTab=readme
but I can not get it working, I get the following error:
Uncaught SyntaxError: The requested module './../node_modules/wavesurfer.js/dist/wavesurfer.js' does not provide an export named 'default' (at TwoPlayers.js:2:9)

(I tried to import a module that I build without any troubles..., It seems like wavesurfer.js is not prepared to be load with import??)
Mi source code is:
import { LitElement, html, css } from "lit-element";
import  WaveSurfer    from 'wavesurfer.js';

import { MyFunction2 } from './demo'

// import * as WaveSurfer  from 'wavesurfer.js';

class TwoPlayers extends LitElement {
    static styles = css`
    :host {
        display: block;
        border-radius: 0.5rem;
        padding: 0.2rem 0.5rem;
        background-color: #475119;
        color: #fff;
        font-weight: bold;
    }
    `;

In the examples folder always is used as a library loaded in the HTML, but there aren't any example using node bundler.
Has anyone managed to get it working with node using import?
Thanks in advance

A: Using  this way to import the package:
import 'wavesurfer.js';

It will work, and you can use WaveSurfer object
The documentation say to use:
import WaveSurfer from 'wavesurfer.js';

but it is not working


text:
Q: Electric potential surrounding an offset point charge I am self learning electromagnetic fields by going through the homework assignments found here. I am stuck on the first question of the second assignment...

Their solution says that this is equivalent to solving for a dipole separated by a distance $d$. The solution being...
$$\Phi(\vec r) = \frac{qdcos(\theta)}{4\pi\epsilon_o r^2},\,z>0$$
While I understand why this works, I would like to solve without the dipole setup. Could someone please help me with the solution?
EDIT:
I have decided to just attempt to better understand the dipole solution; I do not understand why we can make this step:
$$\Phi(\vec r)=\frac{q}{4\pi\epsilon_o}\left(\frac{dcos(\theta)}{r^2-\frac{d^2}{4}cos^2(\theta)}\right)\Longrightarrow\Phi(\vec r) = \frac{qdcos(\theta)}{4\pi\epsilon_o r^2}$$
Why does $\frac{d^2}{4}cos^2(\theta)=0$ when $z>0$?

A: The surface charge density must be such that E is perpendicular to the surface, that is, it must cancel the parallel component of the field of the point charge. Use Gauss's law for that.

A: There are, as I see it, two different problems here:

*

*How does the method of images allow us to relate the stated problem of a point charge and infinite plate to the (simpler) problem of a dipole? The answer to this (as I have explained in a comment above) can be seen in any textbook on electrodynamics (I would suggest Chapter 3.2 of Griffiths' Electrodynamics).

*Once this has been understood, it can be shown that in the region $z>0$, $$\Phi(r) = \frac{q}{4\pi \epsilon_0}\left(\frac{d\cos{\theta}}{r^2 - \frac{d^2}{4}\cos^2{\theta} }\right),$$ which reduces to $$\Phi(r) = \frac{q d \cos{\theta}}{4\pi \epsilon_0 r^2}.$$ This is an approximation, it is not generally true. However, there is something in the question that allows you to make this approximation. I will not give you the answer (it's really quite simple) because this is very much a "homework-style" question, but check to see if there are any assumptions in the problem that you have not used yet (or which might sound superfluous, but aren't).


text:
Q: Eliminating island sub-polygons I'm wondering if this is the right way to do this, or if there's an easier way.
For illustration sake, take this SpatialPolygons object:
main = cbind(c(0, 0, 1, 1),
             c(0, 1, 1, 0))
hole = main/3 + 1/3
island = cbind(c(1.05, 1.05, 1.55, 1.55),
               c(0, .5, .5, 0))
P = Polygons(list(Polygon(main),
                  Polygon(hole, hole = TRUE),
                  Polygon(island)), ID = 1)
SP = SpatialPolygons(list(P))
plot(SP, col = 'red')

I'd like to clip the "island" polygon while retaining the topology of the "main" polygon -- namely, that is has a hole (in my case, it has several holes, but this should do).
Here's what I came up with:
#extract sub-polygons of this polygon
subP = SP@polygons[[1L]]@Polygons
#use the area to identify the largest
areas = sapply(subP, slot, 'area')
#keep holes or the largest actual polygon
keep = sapply(subP, function(p) p@hole | p@area == max(areas))
#construct a new SpatialPolygons object from scratch using index
rem = SpatialPolygons(list(Polygons(subP[keep], ID = 1)))
plot(rem, col = 'red')

That strikes me as being a bit circuitous -- am I missing a method that would handle this more directly? Other related questions I've seen speak more about a SpatialPolygons object that's made up of many polygons instead of one polygon and many Polygons (alas rendering this nuanced search all but impossible).

A: I spent way too much time thinking about this before remembering my unproblematic fave, the rmapshaper package. I think you should try using ms_explode to get to singlepart objects (or sp::disaggregate, per that tool's own recommendation, for SPDFs), and then experiment with the tolerances on ms_filter_islands.
The brute force method would involve looking for non-hole polygon parts whose coordinates aren't in use elsewhere in the object, but all that recursive searching seems like it would be pretty inefficient, even on a fortified object.

A: When I saw your question I was thinking about this question here ("Transform raster donuts to circles") and the corresponding answer from @Kersten. The solution is based on a Mathematical Morphology application. Python is used in this answer.
There is also a CRAN - Package called mmand (https://cran.r-project.org/web/packages/mmand/index.html). Hopefully doing the same stuff.
Depending on your data you could convert you polygons to a raster, doing some 'Mathematical Morphology' and convert the raster back to polygons.


text:
Q: How to call PlayStore outside App in Android I am developing an android app.
I would like to open PlayStore from my app.
I write down the following code.
final String appPackageName = getPackageName();
try {
     startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
     startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
}

PlayStore is called correctly, however it seems to be called inside my app.(When I push home button while the PlayStore screen appears, and then I push my app icon, the PlayStore is displayed.)
I would like to call PlayStore outside my app.
Could you tell me how to solve this problem?

A: This will open Playstore app.
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.android.vending");
ComponentName comp = new ComponentName("com.android.vending", "com.google.android.finsky.activities.LaunchUrlHandlerActivity"); // package name and activity
launchIntent.setComponent(comp);
launchIntent.setData(Uri.parse("market://details?id=" + YOUR_MARKET_ID));

startActivity(launchIntent);


text:
Q: Missing First Letter of Short Description in Magento I can add the short description to the back end with no worries, but when I look at the front end it is missing the first letter.
An example of this: http://www.bluescribecloud.com/index.php/nautical/bells/bronze-ship-s-bell-4.html
As you can see when you click on the page, to the right of the image is The Short Description text and the first letter is missing. This is the same for every product.
You can see the correct description in the description part at the bottom of the products name.
On a side note, is it possible to have it so that the short description ends with 3 trailing ellipses rather than ending abruptly?
Thanks!!!

A: There certainly seems to be some issue when you echo'ed the description in you template file. Find the template used, and fix the issue, or you can mention the code here.

A: Bingo, change the code to this;
<?php if ($_product->getShortDescription()):?>

<?php $des = $_helper->productAttribute($_product, nl2br($_product->getShortDescription()), 'short_description');?>

<?php if(strlen($des) > 200) {
echo substr($des,0,200).'...';
} else {
echo $des; } ?>

<?php endif;?>


text:
Q: Extend or configure Eclipse compare files functionality Eclipse has built in functionality for comparing files, but how can I configure that functionality? Say I create a new file type and want an external program do perform the diff. How do I set that up?
Can I create an Eclipse plugin to add my own plugin for handling file comparisons? Or perhaps that is the answer to the first question...

A: You  may want to look at the EMF Compare Project which helps build compare editors for EMF models. If you don't have an EMF model for your file type, you can either create one or look through the source code of EMF Compare to see how it works.
The developer guide explains how to use the code to write your custom viewers.

A: There is a plugin integrating Beyond Compare into Eclipse. As it is open source, you might get a clue by looking at its sources.


text:
Q: Is there a combine Input format for hadoop streaming? I have many small input files, and I want to combine them using some input format like CombineFileInputFormat to launch fewer mapper tasks. I know I can use Java API to do this, but I don't know whether there's a streaming jar library to support this function while I'm using Hadoop streaming.

A: Hadoop streaming uses TextInputFormat by default but any other input format can be used, including CombineFileInputFormat. You can change the input format from the command line, using the option -inputformat. Be sure to use the old API and implement org.apache.hadoop.mapred.lib.CombineFileInputFormat. The new API isn't supported yet.
$HADOOP_HOME/bin/hadoop jar \
      $HADOOP_HOME/hadoop-streaming.jar \
      -inputformat foo.bar.MyCombineFileInputFormat \
      -Dmapred.max.split.size=524288000 \
      -Dstream.map.input.ignoreKey=true \
      ...

Example of CombineFileInputFormat


text:
Q: Error: celsius cannot be resolved to a variable Getting error with the following code:
import java.util.Scanner;
public class FahrenheitToCelsius{

 public static void main(String[]args){
    convertFToC();
 }

  /*gets input representing fahrenheit and displays celsius equivalent*/
  public static void convertFToC(){
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter Fahrenheit temperature");
    double fahrenheit = scan.nextInt();
    System.out.println(fahrenheit + " degrees Fahrenheit is " +
      fMethod(celsius) + " degrees Celsius");
  }

  /* calculates and returns the celsius equivalent */
  public static double toCelsius(double fahr){
    int BASE = 32;
    double CONVERSION_FACTOR = 9.0/ 5.0;
    double celsius = ((fahr-BASE)/(CONVERSION_FACTOR));
    return celsius;
  }
}

I get the following:
Error: celsius cannot be resolved to a variable

I need to use fMethod to call the toCelsius in the System.out.println however i keep getting this error.

A: You haven't shown fMethod at all, but it looks like you just want:
System.out.println(fahrenheit + " degrees Fahrenheit is " + toCelsius(fahrenheit)
                   + " degrees Celsius");

You can't use celsius in main because it's a local variable in the toCelsius method. Instead, you need to call that method and use the return value.

A: System.out.println(fahrenheit + " degrees Fahrenheit is " + fMethod(celsius) + " degrees Celsius"); //Step 4

should probably read
System.out.println(fahrenheit + " degrees Fahrenheit is " + toCelsius(fahrenheit) + " degrees Celsius"); //Step 4

A: You call fMethod which doesn't exist and pass the value of celsius when I think you meant fahrenheit.
The variable celsius is local to toCelsius() and is therefore not resolvable inside convertFToC().

A: You need to call your toCelsius(double fahr) method, like this:
System.out.println(fahrenheit + " degrees Fahrenheit is " + toCelsius(fahrenheit) + " degrees Celsius"); // Step 4

A: in the method convertFToC()
You get the fahrenheit from the user and call fMethod(celsius)
You were supposed to call fMethod(farenheit)
More important:
If you read the compiler error message, you get not just the error, but the file name and the line number. If you go to the line number, you see a celcius variable out of nowhere.
This is easy. I know asking on SO is easier, but you will never learn to read error messages and solve problems this way.
Learn to read and understand error messages. They are there for a reason.

A: On a line marked step4 you have an undeclared variable named celsius. Should be fahrenheit perhaps?

A: You are using celsius here:
System.out.println(fahrenheit + " degrees Fahrenheit is " + fMethod(celsius) + " degrees Celsius");

However, you did declare celsius only in toCelsius and that's out of scope.


text:
Q: new Date() возвращает NaN в Safari Перепробовала вообще все, что гугл выдавал - не работает: приведение к числу (parseInt(), Number()) или строке, через  setDate().
Сталкивались ли вы с таким и как лечили?
Моя функция обрабатывает дату в шаблоне VUE, приходящую из JSON
<p>{{ getFormattedDate(document.date.date) }}</p>

getFormattedDate: function (value, separator = '.') {
      if (!value) {
        return false;
      }

      let date = new Date(value);
      date.setDate(date.getDate());

      let day = date.getDate() < 9 ? `0${ date.getDate()}` : date.getDate();
      let mount = date.getMonth() < 9 ? `0${ date.getMonth() + 1 }` : date.getMonth() + 1;
      let year = date.getFullYear();

      return `${ day }${ separator }${ mount }${ separator }${ year }`;
    }


text:
Q: Fastlane - fastlane init causes No such file or directory exception I'm trying to add fastlane to my android app. However when I try to run fastlane init I'm reciving an error :
C:\xxx\xxx\xxx\xxx>fastlane init
[✔]

[17:49:09]: Error accessing file, this might be due to fastlane's directory handling
[17:49:09]: Check out https://docs.fastlane.tools/advanced/#directory-behavior for more details

Traceback (most recent call last):
        17: from C:/Ruby27-x64/bin/fastlane:23:in `<main>'
        16: from C:/Ruby27-x64/bin/fastlane:23:in `load'
        15: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.198.1/bin/fastlane:23:in `<top (required)>'
        14: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.198.1/fastlane/lib/fastlane/cli_tools_distributor.rb:122:in `take_off'
        13: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.198.1/fastlane/lib/fastlane/commands_generator.rb:42:in `start'
        12: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.198.1/fastlane/lib/fastlane/commands_generator.rb:353:in `run'
        11: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/commander-4.6.0/lib/commander/delegates.rb:18:in `run!'
        10: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.198.1/fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb:115:in `run!'
         9: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.198.1/fastlane_core/lib/fastlane_core/analytics/analytics_session.rb:22:in `action_launched'
         8: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.198.1/fastlane_core/lib/fastlane_core/analytics/analytics_session.rb:59:in `should_show_message?'
         7: from C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.198.1/fastlane_core/lib/fastlane_core/module.rb:28:in `fastlane_user_dir'
         6: from C:/Ruby27-x64/lib/ruby/2.7.0/fileutils.rb:211:in `mkdir_p'
         5: from C:/Ruby27-x64/lib/ruby/2.7.0/fileutils.rb:211:in `each'
         4: from C:/Ruby27-x64/lib/ruby/2.7.0/fileutils.rb:226:in `block in mkdir_p'
         3: from C:/Ruby27-x64/lib/ruby/2.7.0/fileutils.rb:226:in `reverse_each'
         2: from C:/Ruby27-x64/lib/ruby/2.7.0/fileutils.rb:228:in `block (2 levels) in mkdir_p'
         1: from C:/Ruby27-x64/lib/ruby/2.7.0/fileutils.rb:250:in `fu_mkdir'
C:/Ruby27-x64/lib/ruby/2.7.0/fileutils.rb:250:in `mkdir': No such file or directory @ dir_s_mkdir - Z:/.fastlane (Errno::ENOENT)

I'm using Ruby 2.7.0p0 cause I know there are issues with other versions. Any ideas what can be wrong ?


text:
Q: How do we maximize core and winding losses in an electromagnet (and calculate them) for variable DC input? Bigger Picture:
Imagine a magnet approaching the solenoid with some initial constant velocity on \$v_0\$ on x axis. The approaching magnet will induce an EMF and induced current in solenoid. We want to maximize the power loss so that the solenoid acts as a brake. We intend to do so by maximizing the power losses in the solenoid (both winding and core).
Technical Setup:
Most of the time we deal with minimizing copper and core losses in an electromagnet. Let us now consider an electromagnet with a core: the shape, size, material etc. and all the other variables are left free for design.
Given an electromagnet in which the winding is supplied with some variable DC input current and voltage, and their values can be determined by two given functions over time \$t: V(t)\$ and \$I(t)\$. The maximum input voltage and current are 10s of volts and at most 10 A. We can thus simply determine the value of input power:
\$P(t)= V(t).I(t)\$
Technical Objective:
We need to maximize the power losses in the electromagnet (in form of eddy currents etc.) in terms of percentage w.r.t. to total input power to the winding. How do we achieve this?
Question 1: To maximize the core losses what shape, size, material, etc. for the core do we need? Wikipedia (https://en.wikipedia.org/wiki/Magnetic_core) mentions: > If the core is electrically conductive, the changing magnetic field induces circulating loops of current in it, called eddy currents, due to electromagnetic induction. The loops flow perpendicular to the magnetic field axis. The energy of the currents is dissipated as heat in the resistance of the core material. The power loss is proportional to the area of the loops and inversely proportional to the resistivity of the core material.
So should we as a rule of. thumb choose a highly conductive solid core (soft iron with maximum diameter in case of a cylindrical shape)?
How do we deal with this rigorously from an engineering point of view (both design and calculating the power losses)? Can we achieve losses of over 75% (of input power)?
Question 2: What kind of winding parameters do we need ((1). gauge of wire, (2) number of turns (3) shape of solenoid) to maximize the winding losses?

A: It seems based on your comments that you just want to stop the magnet.  Whether there is a core or not is irrelevant.
Let's consider the case of a magnet entering into a coil of wire wound around a plastic bobbin.  A cross section is shown below.

In order to stop the magnet, you need to make the magnet transfer its kinetic energy into the coil.
The coil is an inductor and therefore it can store energy.
$$E(t) = \frac12i(t)^2L(x(t))$$
Where...

*

*E(t) is the stored energy.

*i(t) is the coil current.

*L(x(t)) is the coil inductance.  Note that L varies which varies with magnet position x.  Usually, it will vary with the square of the depth to which the magnet is inserted into the coil.

We can also say that...
$$V(x(t)) = L(x) * \frac{di}{dt}$$
Where...

*

*di/dt is the rate of change of current in the coil.

*V(x(t)) is the inductor voltage (induced by motion of the magnet).

The inductance will be proportional to the square of the number of turns.  So we may write...
$$ L(x(t)) = \beta(x(t)) * N^2 $$
Where...

*

*Beta(x(t)) is a function that depends on the position of the magnet relative to the coil, the geometry of the magnet and coil, their relative position.  Usually, Beta varies proportional to x^2 and proportionally to the permeability of the magnet material.

*N is the number of turns of wire.

As the magnet enters the bobbin the field lines move through the wires with a perpendicular component.  As they move it will induce a voltage in the wires.
$$V(x(t)) = \alpha(x(t)) * N * \frac{dx}{dt}$$
Where...

*

*Alpha(x(t)) is a "coupling factor" that depends on the position of the magnet relative to the coil, the geometry of the magnet and coil, their relative position, and the strength of the magnet.

*V(x(t)) is the induced voltage.

*dx/dt is the velocity of the magnet as it enters.

*x(t) is the position of the magnet relative to the solenoid.
An important thing to note is that all other things being equal, if you use thinner wire but pack more turns into the same volume, then alpha(x(t)) should be largely unaffected, but V will increase proportional to the number of turns.
Now to maximizing braking...

*

*Note that current must flow in a loop.  So, the ends of the solenoid wires must be part of a circuit.  If the wires were open, you would not transfer energy to the coil.

*Secondly, any resistance in series with the coil will reduce the amount of current that builds up, and therefore reduce the energy.  Ideally, we want the resistance as low as possible.
In the case of shorting the coil ends together, assuming no coil resistance, a fixed motion of the magnet, and combining the above equation we get...
$$E = \frac12\int \frac{\alpha(x(t))}{\beta(x(t))N}\frac{di}{dt}$$
The alpha and beta terms just depend on the geometry.  We don't even need to find them to know that if all other things are equal, the maximum braking occurs with a low number of turns and low resistance.  Both of those factors are minimized by just using a metal tube (thicker tube walls are better here).
Also note that alpha and beta are probably going to be pretty hard to calculate by hand.  Normally one would build a model in some EM solver tool and calculate them that way.

A: If you do want to maximize eddy current losses...

*

*Laminated cores reduce losses, so don't use them.

*Cores made of magnetic powder with an insulating binder material reduce losses.

*Solid conductive metal cores maximize losses. For example, a solid iron core.

But note that...

*

*For a DC current the core losses will be zero.

*For a very slowly changing current the core losses will still be very close to zero.

The main thing that will be dissipating heat in a solenoid with a DC current through it is the resistance of the wires that are wound around the core.
In fact, if the solenoid is not moving and you are putting a DC current into it, then all of the input power is turning into heat via the winding resistance.
Also note that the current doesn't need to change direction to have an AC component. For example, you could have:
$$I = 5~\mathrm{A}+4~\mathrm{A}\cdot\sin(2\cdot\pi\cdot f\cdot t)$$
In this case the current would vary between 1 A and 9 A at frequency f. The current never completely changes direction but has an AC component of 4 A.


text:
Q: Preprocess images using OpenCV for pytesseract OCR I want to use OCR (pytesseract) to recognize the text located in images like these:

I have thousands of these arrows. Until now the procedure is as follows: I first resize the image (for another process). Then I crop the image to get rid of the most part of the arrow. Next I draw a white rectangle as a frame to remove further noise but still have distance between text and image borders for better text recognition. I resize the image again to ensure a height of capital letters to ~30 px (https://groups.google.com/forum/#!msg/tesseract-ocr/Wdh_JJwnw94/24JHDYQbBQAJ). Finally I binarize the image with a threshold of 150.
Full code:
import cv2

image_file = '001.jpg'

# load the input image and grab the image dimensions
image = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
(h_1, w_1) = image.shape[:2]

# resize the image and grab the new image dimensions
image = cv2.resize(image, (int(w_1*320/h_1), 320))
(h_1, w_1) = image.shape

# crop image
image_2 = image[70:h_1-70, 20:w_1-20]

# get image_2 height, width
(h_2, w_2) = image_2.shape

# draw white rectangle as a frame around the number -> remove noise
cv2.rectangle(image_2, (0, 0), (w_2, h_2), (255, 255, 255), 40)

# resize image, that capital letters are ~ 30 px in height
image_2 = cv2.resize(image_2, (int(w_2*50/h_2), 50))

# image binarization
ret, image_2 = cv2.threshold(image_2, 150, 255, cv2.THRESH_BINARY)

# save image to file
cv2.imwrite('processed_' + image_file, image_2)

# tesseract part can be commented out
import pytesseract
config_7 = ("-c tessedit_char_whitelist=0123456789AB --oem 1 --psm 7")
text = pytesseract.image_to_string(image_2, config=config_7)
print("OCR TEXT: " + "{}\n".format(text))

The problem is that the text located in the arrow is never centered. Sometimes I remove part of the text with the method described above (e.g. in image 50A).
Is there a method in image processing to get rid of the arrow in a more elegant way? For instance using contour detection and deletion? I am more interested in the OpenCV part than the tesseract part to recognize the text.
Any help is appreciated.

A: If you look at the pictures you will see that there is a white arrow in the image which is also the biggest contour (especially if you draw a black border on the image). If you make a blank mask and draw the arrow (biggest contour on the image) then erode it a little bit you can perform a per element bitwise conjunction of the actual image and eroded mask. If it is not clear look at the bottom code and comments and you will see that it is actually pretty simple.
# imports
import cv2
import numpy as np

img = cv2.imread("number.png")  # read image
# you can resize the image here if you like - it should still work for both sizes
h, w = img.shape[:2]  # get the actual images height and width
img = cv2.resize(img, (int(w*320/h), 320))
h, w = img.shape[:2]

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # transform to grayscale
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]  # perform OTSU threhold
cv2.rectangle(thresh, (0, 0), (w, h), (0, 0, 0), 2)
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]  # search for contours
max_cnt = max(contours, key=cv2.contourArea)  # select biggest one
mask = np.zeros((h, w), dtype=np.uint8)  # create a black mask
cv2.drawContours(mask, [max_cnt], -1, (255, 255, 255), -1)  # draw biggest contour on the mask
kernel = np.ones((15, 15), dtype=np.uint8)  # make a kernel with appropriate values - in both cases (resized and original) 15 is ok
erosion = cv2.erode(mask, kernel, iterations=1)  # erode the mask with given kernel

reverse = cv2.bitwise_not(img.copy())  # reversed image of the actual image 0 becomes 255 and 255 becomes 0
img = cv2.bitwise_and(reverse, reverse, mask=erosion)  # per-element bit-wise conjunction of the actual image and eroded mask (erosion)
img = cv2.bitwise_not(img)  # revers the image again

# save image to file and display
cv2.imwrite("res.png", img)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

A: You can try simple Python script:
import cv2
import numpy as np
img = cv2.imread('mmubS.png', cv2.IMREAD_GRAYSCALE)
thresh = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY_INV )[1]
im_flood_fill = thresh.copy()
h, w = thresh.shape[:2]
im_flood_fill=cv2.rectangle(im_flood_fill, (0,0), (w-1,h-1), 255, 2)
mask = np.zeros((h + 2, w + 2), np.uint8)
cv2.floodFill(im_flood_fill, mask, (0, 0), 0)
im_flood_fill = cv2.bitwise_not(im_flood_fill)
cv2.imshow('clear text', im_flood_fill)
cv2.imwrite('text.png', im_flood_fill)

Result:


text:
Q: Get remaining session time via ajax request without updating session I'm writing session reminder which pops up and counts down session time. The problem is with client side timer, it doesn't know about session update in other browser tab. So i need to check the time via ajax request in server side before showing reminder popup.
By doing this remaining session time should not be updated.
I'm using IIS 8, .NET MVC 4

A: You can mark your Controller as session-less, perhaps this can help you.
Try adding this attribute to your controller class:
[SessionState(SessionStateBehavior.Disabled)]
public class MyController
{
    ....


text:
Q: Loop through object items I have pretty complicated object and I need to loop through multiple levels of items. This got tricky very fast and Im stuck now.
What I've tried (Note that I added an error I get):
var stuffCount = Object.keys(stuff).length;

//Loop through initial items in object
for( i = 0; i < stuffCount; i++ ) {

    // Error occurs on this line:
    // Uncaught TypeError: Cannot read property 'points' of undefined
    var pointCount = stuff[i].points.length;

    var coordinates = [];

    //Loop through points in initial items
    for( r = 0; r < pointCount; r++ ) {

        coordinates.push(new google.maps.LatLng(
            stuff[i].points[r].lat,
            stuff[i].points[r].lng ));
    }

}

Object: It's even more complicated but I made it as simple as possible for the sake of this question.
var stuff = {

    first: {

        center: {
            lat: 11,
            lng: 22
        },
        points: [
            {
                lat: 11,
                lng: 22
            },
            {
                lat: 33,
                lng: 44
            },
            {
                lat: 55,
                lng: 66
            },
        ]
    },

    second: {

        center: {
            lat: 11,
            lng: 22
        },
        points: [
            {
                lat: 11,
                lng: 22
            },
            {
                lat: 33,
                lng: 44
            },
            {
                lat: 55,
                lng: 66
            },
        ]
    },

    third: {

        center: {
            lat: 11,
            lng: 22
        },
        points: [
            {
                lat: 11,
                lng: 22
            },
            {
                lat: 33,
                lng: 44
            },
            {
                lat: 55,
                lng: 66
            },
        ]
    },
}

Im trying to make code smaller by using loops. It's used to show polygons on Google Maps. I could do it one by one but code is going to be pretty big because I have like 100 of them + I want it to be dynamic so that I can easily add new polygons in future without changing a lot of code.
What's wrong with my code?

A: The problems is that you are trying to retrieve keys from your stuff object using a numbered index. You actually don't need the count of keys, use a for...in loop instead like so:
//Loop through initial items in object
for(var i in stuff) {

    // Error occurs on this line:
    // Uncaught TypeError: Cannot read property 'points' of undefined
    var pointCount = stuff[i].points.length;

    var coordinates = [];

    //Loop through points in initial items
    for( r = 0; r < pointCount; r++ ) {

        coordinates.push(new google.maps.LatLng(
            stuff[i].points[r].lat,
            stuff[i].points[r].lng ));
    }

}

A: You're getting confused about the keys. You should be doing:
var stuffKeys = Object.keys(stuff);

//Loop through initial items in object
for( i = 0; i < stuffKeys.length; i++ ) {
    var pointCount = stuff[stuffKeys[i]].points.length;

    var coordinates = [];

    //Loop through points in initial items
    for( r = 0; r < pointCount; r++ ) {

        coordinates.push(new google.maps.LatLng(
            stuff[stuffKeys[i]].points[r].lat,
            stuff[stuffKeys[i]].points[r].lng ));
    }
}

What you have originally is asking for stuff[0]... which doesn't exist. You need stuff[the first key in stuff]...

A: What you're trying to do is get the points attribute out of 'first', so stuff['first'].points.
But instead, what you're doing is stuff[0].points, and 0 is not the key.
This is non-optimized, but should convey what you need to do:
stuff[Object.keys(stuff)[0]].points

A: You should use for in to iterate through object properties. for can be used for iterating in array type property.

A: What's wrong with your code? You are iterating through an object keys as if it were an array
stuff['first'] is not the same as stuff[0]
How can you manage this? I would use lodash, to iterate like this:
_.each(stuff, function(item,name)
{
    _.each(item.points, function(point)
    {
        // do whatever
    });
});

A: You should use a for in loop to iterate through the object. See below example:
var stuffCount = Object.keys(stuff).length; //you don't need this

for (var obj in stuff) {

    var pointCount = stuff[obj].hasOwnProperty("points") ? stuff[obj].points.length : null;
    console.log(pointCount);

}


text:
Q: "To the best of one's ability" - Synonym? I'm trying to rephrase

We help children move and play to the best of their ability.

It's about children with movement concerns,
so this seems semantically correct to me.
I just need a different phrase.
Can you suggest anything other than "as well as they can"?
I've reviewed the suggested duplicate, but it doesn't answer my question.

A: How about as freely as possible?

"We help children move and play as freely as possible".

Collins:

freely
4. adverb [ADVERB after verb]
If something or someone moves freely, they move easily and smoothly, without any obstacles or
resistance.
The clay court was slippery and he was unable to move
freely.
COBUILD Advanced English Dictionary. Copyright © HarperCollins Publishers

A: You could consider utmost either as a noun or as an adjective.
As a noun:
"We help children move and play to their utmost."
As an adjective:
"We help children move and play to their utmost ability."
Merriam-Webster:

utmost adjective
ut·most | \ˈət-ˌmōst,  especially Southern -məst\
Definition of utmost (Entry 1 of 2)
2 : of the greatest or highest degree, quantity, number, or amount
utmost noun
Definition of utmost (Entry 2 of 2)
2 : the highest, greatest, or best of one's abilities, powers, and resources

A: If you want to use a phrase that means the same thing and also doesn't imply somebody's disability, you could say:

We help children maximize their potential.

This can apply not only to movement but to anything else they do. If you want to mention play or movement specifically, you can qualify it by prefacing it with something like when it comes to recreation.
Using it in the context of children with disabilities is fine, but it can be equally used for anyone, so it doesn't have any kind of unstated assumptions behind it.


text:
Q: Adding a list to a dictionary with the simplest code in python 3.x The inventory parameter is a dictionary representing the player's inventory and the addedItems parameter is a list. The addToInventory() function should return a dictionary that represents the updated inventory.The program should output the following:
Inventory:

45 gold coin
1 rope
1 ruby
1 dagger

Total number of items: 48

Here's my code:
def addToInventory(inventory, addedItems):
    print('Inventory:')
    totalItem = 0
    for i in range(len(addedItems)):
        if addedItems[i] in inventory:
        inventory[str(addedItems[i])] += 1
    if addedItems[i] not in inventory:
        inventory[str(addedItems[i])] = 1
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        totalItem += int(v)

    print('Total number of items:' + str(totalItem))

inv = {'gold coin':42,'rope':1}
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
inv = addToInventory(inv,dragonLoot)

I was wondering how to work on the for loop bit. It seems strange to me now (and way too long). Thx!

A: You really should use a Counter for this, which is a subclass of the builtin dictionary.
It has three advantages for your use case:

*

*It is very easy to add two Counter instances (i.e. two inventories together).

*It is very easy to update a Counter.

*The Counter will automatically return 0 when you look up any item that is not in the inventory.

Demo:
>>> from collections import Counter
>>> inventory = Counter({'gold': 45,
...                      'rope': 1,
...                      'ruby': 1,
...                      'dagger': 1}
... )
>>>
>>> def addToInventory(inventory, addedItems):
...     inventory.update(addedItems)
...
>>> addToInventory(inventory, ['gold', 'gold', 'gold', 'dagger'])
>>> inventory
Counter({'gold': 48, 'dagger': 2, 'rope': 1, 'ruby': 1})
>>> addToInventory(inventory, {'ruby':100})
>>> inventory
Counter({'ruby': 101, 'gold': 48, 'dagger': 2, 'rope': 1})
>>> inventory['gold']
48
>>> inventory['flux capacitor']
0

A: You can make it look like this:
for i in range(len(addedItems)):
    inventory[i] = inventory.get(i, 0) + 1


text:
Q: Verify TCP connection is from same machine by MAC address Please don't criticise the solution. It's not my design and yes, it sucks.
On a computer running Linux, and using C, we need to verify that a TCP connection made to a process is from the same machine. Doing it by IP address is problematic since the OS is generating two IP addresses and the process only knows one. Anyway, verifying by IP address is a bit poor.
We want to do the verification by comparing the "remote" MAC address to the local MAC address. We already get the local MAC address. All I need to know is how to get the "remote" MAC address. It's in the packet that gets sent when forming the connection (and in all subsequent ones too). How do we drag it out of the ethernet layer?
Before anyone says this again, I KNOW you cannot get the MAC address of the remote host if it's not on the same subnet/LAN. That's fine. Presumably we'll get something like 00:00:00:00:00:00 and since that is different to the local MAC address it will be different - just what we want.
--
So, to summarise, we have a TCP connection socket fd, we've received a data packet, how do we then find the MAC address of the remote host, the MAC address that was in the packet's header?

A: The MAC address of a live same-subnet TCP connection will almost certainly be in the ARP cache.
On Linux, you could examine the ARP cache by looking in /proc/net/arp. Here is what it looks like on my Ubuntu box:
aix@aix:~$ cat /proc/net/arp
IP address       HW type     Flags       HW address            Mask     Device
10.0.0.32        0x1         0x2         00:1e:4f:f5:be:dc     *        eth0
10.10.10.1       0x1         0x2         00:1f:6c:3e:02:e3     *        eth0

There's probably some callable API that you could use to get to the same data if you're averse to parsing the pseudo-file.

A: If I understand correctly, you are not trying to tell remote machines apart, but to use the idea that the source and destination MAC would match on traffic sent from a machine to itself in order to allow only local traffic.
This seems rather roundabout, and has been pointed out, insecure.
A somewhat better idea might be to have the TCP client listen only on the loopback interface (127.0.0.1) and not on INADDR_ANY.  Or go a step further and use a unix-domain socket instead of a TCP one (a common method used by X servers today to prevent the possibility of remote connections)

A: How about configuring a firewall (internal or external) to block or MAC-filter external traffic on the port in question?

A: A loopback connection (whether it's over the loopback interface or some other interface) it not routed over any ethernet device and therefore does not have a MAC address associated with it.
I suggest you just use getsockname and getpeername to get the local and remote IP address and compare that they are equal. That will work without any a priori knowledge of the configured IP addresses of your system.
Further, if you want to be IPv4/v6 agnostic, you could use getnameinfo with the NI_NUMERIC flag to convert both addresses to numeric string representations and strcmp them.