text:
Q: Avoid repeating an expression in a LINQ to Entities query I have the following query:
val = val.Select(item => new SimpleBill { CTime = item.CTime, Description = item.Description, ID = item.ID,
      IDAccount = item.IDAccount, OrderNumber = item.OrderNumber, PSM = item.PSM, Sum = item.Sum,
      Type = (BillType)item.Type,
      ByteStatus = ((Bill)item).Payments.OrderByDescending(payment => payment.ID).FirstOrDefault().Status,
      LastPaymentDate = ((Bill)item).Payments.OrderByDescending(payment => payment.ID).FirstOrDefault().CTime,
      LastPaymentSum = ((Bill)item).Payments.OrderByDescending(payment => payment.ID).FirstOrDefault().Sum });
      }

Is it possible to avoid repeating the ((Bill)item).Payments.OrderByDescending(payment => payment.ID).FirstOrDefault() part 3 times? I tried turning it into a method and into a delegate - the code compiled in both cases, but produced an exception at runtime.

A: You can use the let contstruct as follows:
val = from item in val
let lastPayment = ((Bill)item).Payments
   .OrderByDescending(payment => payment.ID)
   .FirstOrDefault()
select new SimpleBill
{
    lastPayment.CTime,
    //Rest of fields
}

However, as you may noticed this uses the LINQ Query syntax vs. Method syntax. IIRC let is only available in the former.


text:
Q: Javascript autocomplete xml get plus attribute I am trying to use a javascript for an autocomplete.
I have seen online some examples, but I don't find something that does to my case.
I would want to effect two functions together, her before autocomplete the second to pass another value to another input.
I have a xml with various attributes.
<ROOT>
<ROW COMCOD="01344" COMLIB="SAINT-DENIS-LES-BOURG" CODPOS="01000" IDCOMM="1" ETRANG="N" COLMEE="N" CSAGES="0104P01" FUSION="N"/>
<ROW COMCOD="01914" COMLIB="BROU" CODPOS="01000" IDCOMM="2" ETRANG="N" COLMEE="O" CSAGES="" FUSION="N"/>
<ROW COMCOD="01053" COMLIB="BOURG-EN-BRESSE" CODPOS="01000" IDCOMM="3" ETRANG="N" COLMEE="N" CSAGES="0104P01" FUSION="N"/>
<ROW COMCOD="01053" COMLIB="BOURG EN BRESSE CEDEX" CODPOS="01001" IDCOMM="4" ETRANG="N" COLMEE="N" CSAGES="0104P01" FUSION="N"/>
<ROW COMCOD="01183" COMLIB="GUEREINS" CODPOS="01090" IDCOMM="5" ETRANG="N" COLMEE="N" CSAGES="0104P03" FUSION="N"/>
<ROW COMCOD="01225" COMLIB="LURCY" CODPOS="01090" IDCOMM="6" ETRANG="N" COLMEE="N" CSAGES="0104P03" FUSION="N"/>

When use autocomplite I want to take the value COMLIB and to fill the input of the consumer.
I would also want however to pass the value CODPOS to another input.
Am I following this example, that correctly makes me use autocomplite but I doesn't know how to also take the CODPOST and to insert it in

I'm trying this example
     $(document).ready(function() {
 var myArr = [];

 $.ajax({
   type: "GET",
   url: "myxml.xml", // change to full path of file on server
   dataType: "xml",
   success: parseXml,
   complete: setupAC,
   failure: function(data) {
     alert("XML File could not be found");
   }
 });

 function parseXml(xml)
 {
   //find every query value

   $(xml).find("ROW").each(function()
   {

      myArr.push($(this).attr("COMLIB"));

   });
 }

 function setupAC() {
   $("input#searchBox").autocomplete({
   source: myArr,
   minLength: 3,
   select: function(event, ui) {

    $("input#searchBox").val(ui.item.value);

   }
  });
 }
});

<form name="search_form" id="searchForm" method="GET" action="search_results.html">
<label for="searchBox">Keyword Search</label>
<input type="text" id="searchBox" name="searchString" />
<input type="text" id="CODPOS" name="CODPOS" />

<button name="searchKeyword" id="searchKeyword">Sumbit</button>
</form>

You have some suggestion or some links to give me?
Thanks

A:  function parseXml(xml)
  {
    //find every query value

    $(xml).find("ROW").each(function()
    {
     COMLIB = $(this).attr('COMLIB');
      CODPOS = $(this).attr('CODPOS');
      myArr.push({'value':COMLIB",'CODPOS':CODPOS});

    });
  }

   $("input#searchBox").autocomplete({

    source: myArr,
    minLength: 3,
    select: function(event, ui) {
     event.preventDefault();

    $("input#searchBox").val(ui.item.value);
    $("input#CODPOS").val(ui.item.CODPOS);

    }
   });

redpajama_set_name: RedPajamaStackExchange


text:
Q: App settings not Connect Local database I am currently Working MVC5 project. Previous Project  working hosted database .i have created database local i have insert user value login .after create local database i am trying to connect its login not  working .  HomeSqlDBRepository using to read string database  value
Here Login method Login code
 public class LoginRepository
    {
        HomeSqlRepository _repository = new HomeSqlRepository();
        public async Task<LoginModelViewModel> ValidateLogin(LoginModel model) {
            model.ThrowIfNull();
            var ConnectionString = AppSettingsReader.ReadString("thenna");
            IDictionary<string, object> dictionary = new Dictionary<string, object>();
            dictionary.Add("username", model.UserEmail);
            dictionary.Add("password", model.Password);
            return await _repository.GetItemAsync<LoginModelViewModel>("dbo.validateuser", dictionary);
        }
        public async Task<LoginModelViewModel> GetProfileDetails(int uid)
        {
            var ConnectionString = AppSettingsReader.ReadString("thenna");
            IDictionary<string, object> dictionary = new Dictionary<string, object>();
            dictionary.Add("uid", uid);
            return await _repository.GetItemAsync<LoginModelViewModel>("dbo.GetUserProfile", dictionary);
        }

homesqlrepository
public abstract class HomeSqlDBRepository
    {
        public string ConnectionString { get; set; } = AppSettingsReader.ReadString("thenna");
        const int MaxItemCount = 1000;
        public enum SqlExecuteType
        {
            Scalar, NonQuery, Reader
        }
        public async Task<string> ExecuteSqlAsync(string procname, SqlExecuteType executiontype, IDictionary<string, string> parameters)
        {
            string ret = "";

            using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
            {
                using (SqlCommand sqlCmd = new SqlCommand(procname, sqlConn))
                {
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    foreach (KeyValuePair<string, string> kvp in parameters)
                    {
                        sqlCmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
                    }
                    sqlConn.Open();
                    if (executiontype == SqlExecuteType.Scalar)
                        ret = (await sqlCmd.ExecuteScalarAsync()).ToString();
                    else if (executiontype == SqlExecuteType.NonQuery)
                        ret = (await sqlCmd.ExecuteNonQueryAsync()).ToString();
                    sqlConn.Close();
                }
            }

Appsettings config
  <add key="thenna" value="server=DESKTOP-QD6A981\SQLEXPRESS;database=montage;user id=sa;password=root;trusted_connection=false;" />-

  <add key="CustomAuthentication.LoginUrl" value="/Account/LogOn" />
  <add key="CustomAuthentication.Cookie.Name" value=".CUSTOM_AUTH" />
  <add key="CustomAuthentication.Cookie.Expiration" value="1" />
  <add key="CustomAuthentication.Cookie.Timeout" value="20" />

AppSettingsReader using  cloud configuration manager
 public static class AppSettingsReader
    {
        public static string ReadString(string key)
        {
            try
            {
                return CloudConfigurationManager.GetSetting(key).ToString();
            }
            catch(System.Exception ex)
            {
                throw ex;
            }
        }
}

where i did mistake  login not Working  . what cloud configuration manager ? why  using this ?


text:
Q: How many distinct flat connections are there on a flat bundle? Given a flat smooth vector bundle (i.e. with constant transition functions), how many distinct flat connections could we put on it? If the flat connection is not unique, is it unique up to gauge equivalence (i.e. automorphism of bundles with connection)?

A: On any given vector bundle $E$ there is a space of flat connections on it modulo gauge, as you say. If the structure group of the bundle is $G$, it is an appropriate subset of the space $\text{Hom}(\pi_1 X, G)/\sim$, where here I'm modding out by conjugacy; each such representation gives rise to a vector bundle, so you restrict to the subset such that the vector bundle has the right isomorphism type.
There is no general way of saying what this is for an arbitrary vector bundle over an arbitrary manifold. Instead I'll stick with comments about specific cases.
1) Complex line bundles. $E$ supports a flat connection of and only if $c_1(E)$ is torsion. Suppose for convenience $X$ has a CW decomposition with a single 0-cell. Given the corresponding representation $f: \pi_1(X) \to U(1)$, you can extract $c_1(E)$ on the level of cellular cochains by, for each loop in the 1-skeleton, picking a lift $\tilde f(e)$ of $f(e)$ to $\Bbb R$; and if $a$ is a 2-cell, the boundary of $a$ can be written as some word $w$ in the $e$; define $c_1(a) = \tilde f(w)$. It is straightforward to verify that this defines an integer-valued cocycle, and slightly less straightforward to see it determines the same cohomology class as $c_1(E)$. So you can determine the space of flat connections on a complex line bundle completely at the level of representations.
2) If $D$ is a flat connection on a bundle $E$, the linearization of the flat connection equation at $D$ is $Da = 0$, $a \in \Omega^1(\mathfrak g_E)$. The linearization of modding out by gauge is modding out by the image of $D$, so we see that the dimension "should be" $\dim H^1(\mathfrak g_E,D)$; more precisely this is the Zariski tangent space of the moduli space of flat connections at $D$. (Note that if $E$ is a line bundle the induced connection on $\mathfrak g_E$ is trivial, and in that case this is just the same as the usual $b_1(X)$ in the complex case, an 0 in the real case.) In general, the euler characteristic $\chi(E)$ of the bundle is independent of the choice of flat connection on it. (I never worked this out by hand, but one side of the Atiyah-Singer index theorem should be $\chi(\mathfrak g_E)$, and the other should be $\chi(D)$, the Euler characteristic of the de Rham complex of $\mathfrak g_E$ with the operator induced by $D$.) This can be a helpful tool for understanding what $b_1(D)$ is. As an example, take the trivial $SU(2)$-bundle over a surface. In this case, $\chi(E) = 3\chi(\Sigma_g)$, and Poincare duality says we only need to know $b_0(D)$ and $b_1(D)$. $b_0(D)$ is the space of parallel sections of $E$ with respect to $D$; if the connection is reducible to a connection on a $U(1)$-bundle, $b_0(D) = 1$; if it's reducible to a connection on a real line bundle, $b_0(D) = 3$; and if it's irreducible, $b_0(D) = 0$. So $b_1(D)$ is completely determined in this case by whether or not the connection $D$ is reducible, and 'how reducible' it is.


text:
Q: possible to have characters preceding * in FileDialog filter? I want to create a FileDialog whose filter only allows files matching the expression xyz*.xlsm; this would allow files like xyz123.xlsm and xyzzat.xlsm to be selected, but not xyz123.docx or abc123.xlsm.
I'm using this code:
Sub testfd()

Dim fd As FileDialog

Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.Filters.Add "xyz*", "xyz*.xlsm", 1
If fd.Show = -1 Then
    Debug.Print fd.SelectedItems(1)
Else
    Debug.Print "xyz"
End If

End Sub

However, the fd.Filters.Add line generates this run-time error:
Invalid procedure call or argument

Using the filter *.xlsm works normally.
Is it impossible to use .Filters.Add the way I've laid out in my code above?  If so, how can I make sure that the user only selects files that start and end with a given character sequence?

A:
If you badly need it, why not create it from scratch? It is slightly time consuming but simple. I remember doing it once... –  Siddharth Rout 39 mins ago

Here is a quick example that I created for you (took approx 40 mins to create it).
Create a userform as shown in the image below and then name them as shown.

Userform Code
Paste this code in the user form
Option Explicit

Dim justStarted As Boolean

Private Sub UserForm_Initialize()
    With ListBox1
        .ColumnCount = 2
        .ColumnWidths = "70;60"
        .ListStyle = fmListStylePlain
    End With
    justStarted = True
End Sub

Private Sub UserForm_Activate()
    justStarted = False
    Populate
End Sub

'~~> Manually changing folder
Private Sub InitialPath_Change()
    If InitialPath = "" Or justStarted = True Then Exit Sub

    If Dir(InitialPath) <> "" Then
        Populate
    Else
        ListBox1.Clear
        TextBox2.Text = ""
    End If
End Sub

'~~> Listbox Single Click - File Selection
Private Sub ListBox1_Click()
    If ListBox1.ListIndex < 0 Then Exit Sub

    If ListBox1.List(ListBox1.ListIndex, 1) = "File" Then _
    TextBox2.Text = ListBox1.List(ListBox1.ListIndex)
End Sub

'~~> Listbox Double Click - Folder Open
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    If ListBox1.ListIndex < 0 Then Exit Sub

    If ListBox1.List(ListBox1.ListIndex, 1) = "Folder" Then
        If Right(Me.InitialPath, 1) <> "\" Then
            InitialPath = Me.InitialPath & "\" & ListBox1.List(ListBox1.ListIndex, 0) & "\"
        Else
            InitialPath = Me.InitialPath & ListBox1.List(ListBox1.ListIndex, 0) & "\"
        End If

        Populate
    End If
End Sub

'~~> Open Button
Private Sub CommandButton1_Click()
    If Len(Trim(TextBox2.Text)) = 0 Then Exit Sub

    If Right(Me.InitialPath, 1) <> "\" Then InitialPath = Me.InitialPath & "\"

    If Dir(InitialPath & TextBox2.Text) <> "" Then
        MsgBox "You selected " & InitialPath & TextBox2.Text
    Else
        MsgBox "Please select a valid file"
    End If
End Sub

'~~> Exit Button
Private Sub CommandButton2_Click()
    Unload Me
End Sub

'~~> Populate Listbox
Sub Populate()
    Dim sFile As Variant, sFolder As Variant
    Dim sFilter As String
    Dim pos As Long: pos = 0

    ListBox1.Clear

    Dim objFSO As Object, objFolder As Object, objSubFolder As Object
    Dim i As Integer

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder(InitialPath)

    For Each objSubFolder In objFolder.subfolders
        With ListBox1
            .AddItem
            .List(pos, 0) = objSubFolder.Name
            .List(pos, 1) = "Folder"
            pos = pos + 1
        End With
    Next objSubFolder

    sFilter = Split(Filter, "(")(1)
    sFilter = Split(sFilter, ")")(0)
    Filter = sFilter

    sFile = Dir(InitialPath & Trim(sFilter))

    While (sFile <> "")
        With ListBox1
            .AddItem
            .List(pos, 0) = sFile
            .List(pos, 1) = "File"
            pos = pos + 1
        End With
        sFile = Dir
    Wend
End Sub

Module
From a module you can call it as
Sub Sample()
    With MyFileBrowser
        .InitialPath = "C:\Users\Siddharth\Desktop\"
        .Filter = "My Files,(*ture*.*)"
        .Caption = "Open"
        .Show
    End With
End Sub

In Action

Disclaimer:

*

*Error Handling Not done.

*Works with only Single Filters

*Filter textbox is locked for editing

A: Probably you won't need a solution anymore but this may be helpful for other users who, like myself, looked for a solution of this problem.
There is a way to filter files beyond the file type filters. In the following example I want to see only html files in the folder that start with a string contained in "AccountNr".
To achieve this I add the AccountNr string plus an asterisk to the InitialFileName.
The folder's path is not changed by this addition in the InitialFileName. The selector field in the FileDialog window will show the AccountNr string with the asterisk.
(The basic code was found in stackoverflow, I modified it for my needs)
Private Function GetURL(AccountNr)
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd

        .InitialFileName = "C:\Users\xxxed\Downloads\YY\" & AccountNr & "*"
                'set directory (initial file path) & AccountNr

        .AllowMultiSelect = False

        ' Set the title of the dialog box.
        .Title = "Please select the file."

        ' Clear out the current filters, and add our own.
        .Filters.Clear
        .Filters.Add "HTML Files", "*.html" 'This filters files with "AccountNr*.html"
        .Filters.Add "All Files", "*.*"     'alternative filter: all types

        ' Show the dialog box. If the .Show method returns True, the
        ' user picked at least one file. If the .Show method returns
        ' False, the user clicked Cancel.
        If .Show = True Then
            GetURL = .SelectedItems(1)      'This is the file name and path
        Else
            GetURL = ""
        End If
    End With
End Function


text:
Q: Amazon s3 fast fileset download? I have an iphone app that sometimes has to download a set of files from a bucket on a Amazon AWS S3 account.
A typical such download will involve maybe 100 files. Most of these files are very small though and all combined, we are still under 3MB.
At the moment, I use the listObjectsInBucket function and then loop on all files and use the API/SDK function getObject to get them one by one.
The problem is that it takes a very long time to do it that way so I would like to have some advice regarding a faster strategy that would work in my scenario (many small files that have to stay available individually so that they can be modified by a CMS).
Thanks in advance.

A: If you want the files to remain resident in the application's local storage, it might make sense to store all the files locally along with metadata on the files (i.e. checksum, last modified timestamp, etc.).  You could then compare this metadata against metadata you store in S3 metadata fields, syncing up only those files where the metadata differs.


text:
Q: How to integrate dart sass @use with a framework like Bulma? I'm trying to use Dart Sass' @use to customize Bulma, but as far as I understand it, when I do e.g.
@use "utilities/_all" with (
$blue: #0f52ba,
//etc
);

I can't then use e.g.
@use 'layout/hero';

Because the hero sass file expects a global $colors which would be redefined here as _all.$colors.
I also tried to load the utilities/_all without namespace like this
@use 'utilities/_all' as * whith (
//etc
);

To no avail… When debugging, I indeed see as set respectively _all.$colors and $colors but the hero files always throw this error:
Error: Undefined variable.
   ╷
14 │   @each $name, $pair in $colors
   │                         ^^^^^^^
   ╵
  layout/hero.sass 14:25  @use


text:
Q: "Yowl", "howl" and "wail" What is the difference between the synonymous words: yowl, howl and wail?
Based on dictionaries, these too similar words overlap in meaning as below:

Howl
1) If a dog or wolf howls, it makes a long, sad sound
2) to make a loud sound, usually to express pain, sadness, or another strong emotion.
Yowl
  - To make a long, high, unhappy cry, usually when hurt or fighting.
Wail
  - To make a long, high cry, usually because of pain or sadness.

For instance, I cannot distinguish the following sentences from each other:

*

*The wolf / dog is yowling.

*The wolf / dog is howling.

*The wolf / dog is wailing.

*He was yowling in pain.

*He was howling in pain.

*He was wailing in pain.

Please explain me what is your taking on each case?
Meanwhile, please provide me with some examples where each word can be used uniquely so that I could differentiate them.
Thank you

A: Howl and yowl aren't generic words for cries; they're specific sounds made by specific animals. Howling is how wolves and dogs call to each other (it's a social thing), like this. Yowling is a sound cats make when fighting or courting, like this (it's a different sound from a meow).
Howl is also used for other similar sounds, but yowl is seldom used for anything but that specific cat sound; if it's used for anyone else, it implies they're acting like a cat.
A wail is a prolonged cry of sadness, especially one that varies in pitch (kind of like a wolf's howl, but wail is not used for that). It contrasts with a sob, which is a short cry that's repeated. (It also used to be a common word for crying in general, but that's archaic.) Both wail and sob are normally used for humans, but wail is also used for similar sounds made by animals or even machines.
So wolves howl, but don't yowl or wail. Cats yowl, but don't howl or wail (unless they're crying in an unusual manner). Sad humans may wail and sob (but the usual word is cry); humans in pain will may cry out or scream or maybe howl (if it's loud and full-throated), but not yowl.
Typical uses:

*

*The wolves aren't howling at the moon, they're howling at each other.

*The cats were fighting, with a lot of hissing and yowling.

*A famous cliché: there will be wailing and gnashing of teeth (which means crying and grinding of teeth)


text:
Q: Is there any way to get the k smallest elements from a list without sorting it in Python? I want to retrieve k smallest elements from a list in python. But I want to achieve this with less than O(n log n)(that is, without sorting the list) complexity. Is there any way to do so in Python. If yes please let me know. Thanks in advance.

A: I think Quickselect is what you are looking for.

Quickselect uses the same overall approach as quicksort, choosing one element as a pivot and partitioning the data in two based on the pivot, accordingly as less than or greater than the pivot. However, instead of recursing into both sides, as in quicksort, quickselect only recurses into one side – the side with the element it is searching for. This reduces the average complexity from O(n log n) to O(n), with a worst case of O(n2).
-- https://en.wikipedia.org/wiki/Quickselect

A: I can think of a few ways sorting/non-sorting solution for this problem:

*

*Rank Selection Algorithm - like quicksort, we can find pivot rank then decide on whether to go left or right, O(N) time

*Build a Min Heap O(N), extract k times - O(N + kLogN) time

*Priority Queue - like max heap (remove biggest element if there is a new smaller), but instead we can loop through the entire array, build a heap of k size - O(N + NlogK)

*Bubble Sort - bubble smallest few element upwards - O(k*N)

A: Use the heapq.nsmallest, it performs with partial heap-sort


text:
Q: Select multiple files with Intent.ACTION_GET_CONTENT I'm trying to select multiple files with an Intent, but it seems like I'm missing on something.
I create an Intent.ACTION_GET_CONTENT Intent, put Intent.EXTRA_ALLOW_MULTIPLE as extra in  (it seems to perfectly fit the purpose) and create a chooser (optional), which chooses the application that should be able to pick multiple files and return them.
The Problem is that I can only pick a single file.
I tried multiple file explorers.
It's API 18 (4.3).
ACTIVITY_CHOOSE_FILE = 1;  //global constant
Button btn = (Button) this.findViewById(R.id.btnGetFiles);
btn.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    Intent chooseFile;
    Intent intent;
    chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
    chooseFile.setType("file/*");
    chooseFile.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    intent = Intent.createChooser(chooseFile, "Choose a file");
    startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
  }
});

I also added this to the Manifest (it had the same functionality before adding it):
        <intent-filter>
            <action android:name="android.intent.action.GET_CONTENT" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

Why can't I choose multiple files?
(For clarification: the problem is not, that multiple files aren't returned - I can't choose more than 1 file)

A: I got the same issue and ACTION_OPEN_DOCUMENT worked for me.
public void selectImages() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, your_initial_uri);
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
    startActivityForResult(intent, 1);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
// also check data.data because if the user select one file the file and uri will be in  data.data and data.getClipData() will be null
            for(int i = 0; i < data.getClipData().getItemCount(); i++) {
                Uri uri = data.getClipData().getItemAt(i).getUri();
                System.out.println("image" + i + "=" + uri.toString());
             }
        }
   }
}

A: Here's the solution in my case it worked for me and allows me to select any kind of file(s).
// Start intent from your method
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("*/*");
startActivityForResult(intent, 1001);

// Get the result from this Overriden method
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case 1001:

                // Checking whether data is null or not
                if (data != null) {

                    // Checking for selection multiple files or single.
                    if (data.getClipData() != null){

                        // Getting the length of data and logging up the logs using index
                        for (int index = 0; index < data.getClipData().getItemCount(); index++) {

                            // Getting the URIs of the selected files and logging them into logcat at debug level
                            Uri uri = data.getClipData().getItemAt(index).getUri();
                            Log.d("filesUri [" + uri + "] : ", String.valueOf(uri) );
                        }
                    }else{

                        // Getting the URI of the selected file and logging into logcat at debug level
                        Uri uri = data.getData();
                        Log.d("fileUri: ", String.valueOf(uri));
                    }
                }
                break;
        }
    }
}

A: I got same issue. Here my solution.
Java:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data)
    if(requestCode == PICKFILE_RESULT_CODE) {
       if(null != data) { // checking empty selection
          if(null != data.getClipData()) { // checking multiple selection or not
             for(int i = 0; i < data.getClipData().getItemCount(); i++) {
                Uri uri = data.getClipData().getItemAt(i).getUri();
             }
          } else {
             Uri uri = data.getData();
          }
       }
    }
 }

Kotlin:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            PICKFILE_RESULT_CODE -> if (resultCode === Activity.RESULT_OK) {
                if (null != data) {
                    if (null !=data.clipData) {
                        for (i in 0 until data.clipData.itemCount) {
                            val uri = data.clipData.getItemAt(i).uri
                            dumpImageMetaData(uri)
                        }
                    } else {
                        val uri = data.data
                        dumpImageMetaData(uri)
                    }
                }
            }
        }
    }

A:
Why can't I choose multiple files?

Presumably, the implemeters of "the application that should be able to pick multiple files and return them" have not implemented EXTRA_ALLOW_MULTIPLE support. Contact them and request this feature.

A: I know it's a bit outdated post but still if someone encounters it:
in this sample, we open default system file explorer to allow a user select multiple files of any type on his device:
Intent filesIntent;
filesIntent = new Intent(Intent.ACTION_GET_CONTENT);
filesIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
filesIntent.addCategory(Intent.CATEGORY_OPENABLE);
filesIntent.setType("*/*");  //use image/* for photos, etc.
startActivityForResult(filesIntent, REQUEST_CODE_FOR_ON_ACTIVITY_RESULT);


text:
Q: I tried to disable Mission Control and now Expose doesn't work I tried to disable Spaces by editing Mission Control. Now, Show Deskop and show Application Hot Corners don't work.
Have restarted my computer.

A: If you ran something like defaults write com.apple.dock mcx-expose-disabled -bool true, you can revert it by pasting this to Terminal:
defaults delete com.apple.dock mcx-expose-disabled; killall Dock


text:
Q: If $X_{n} \to X$ and $Y_{n} \to Y$ in probability, then $f(X_{n},Y_{n}) \to f(X,Y)$ in probability for $f$ continuous For a bivariate, real continuous function $f:\mathbb{R}^{2} \mapsto \mathbb{R}$, I need to show that $f(X_{n},Y_{n}) \to f(X,Y)$ in probability whenever $X_{n} \to X$ and $Y_{n}\to Y$ in probability.
This is essentially a bivariate version of the Continuous Mapping Theorem for convergence in probability, and so my attempt involves essentially just copying the proof for the univariate case. What I don't realize, however, is if there are any nuances that should creep into this anywhere because all we are given is that $X_{n} \to X$ and $Y_{n} \to Y$ in probability, and not that $(X_{n},Y_{n}) \to (X,Y)$ in probability (although, by convergence of vectors, it makes sense that we would be guaranteed this).
Anyway, here is what I did:

Let $\epsilon > 0$ be given. Then, for any $K \in \mathbb{R}_{+}^{2}$, $$P(|f(X_{n},Y_{n})-f(X,Y)|>\epsilon)\\ \leq P(|f(X_{n},Y_{n})-f(X,Y)|>\epsilon, \, |(X,Y)|\leq K, \, |(X_{n},Y_{n})|\leq K) + P(\{ |X,Y|>K\} \cup \{|X_{n},Y_{n}|>K\}) $$
We note that since $\{(x,y):|(x,y)\leq K\}$ is a compact set, $f$ is uniformly continuous there.
Therefore, $\exists \delta = \delta(\epsilon)$ s.t. $|f(X_{n},Y_{n})-f(X,Y)|\leq \epsilon$ for $|(X_{n},Y_{n})-(X,Y)|<\delta$ (where we consider the set where $|(X,Y)|\leq K$ and $|(X_{n},Y_{n})|\leq K$). And so, $$ \{|f(X_{n},Y_{n})-f(X,Y)|>\epsilon, \, |(X,Y)|\leq K, \, |(X_{n},Y_{n})|\leq K \} \subseteq \{ |(X_{n},Y_{n})-(X,Y)|>\delta \} $$
  Thus, we have $$ P(|f(X_{n},Y_{n})-f(X,Y)|>\epsilon) \leq P(|(X_{n},Y_{n})-(X,Y)|>\delta) + P(|(X,Y)|>K)+P(|(X_{n},Y_{n})|>K) \\ \leq P(|(X_{n},Y_{n})-(X,Y)|>\delta) + P(|(X,Y)>K) + P\left(|(X,Y)|>\frac{K}{2}\right) + P\left( |(X_{n},Y_{n})-(X,Y)|>\frac{K}{2}\right)$$
Now, let $\gamma > 0$ be arbitrary, and then we can choose $K$ sufficiently large such that the second and third terms in the last inequality are both less than $\gamma/2$.
Thus, we have, for sufficiently large $K$, $\displaystyle P(|f(X_{n},Y_{n})-f(X,Y)|>\epsilon) \leq P(|(X_{n},Y_{n})-(X,Y)|>\delta) + P\left(|(X_{n},Y_{n})-(X,Y)|>\frac{K}{2}\right)+ \gamma.$
Finally, taking the limit of both sides of this equation and using the fact that $X_{n}-X \to^{P}0$ and $Y_{n}-Y \to^{P} 0$, we have that $P(|f(X_{n},Y_{n})-f(X,Y)|>\epsilon) \leq \gamma$, and since $\gamma > 0$ was arbitrary, we have $f(X_{n},Y_{n})-f(X,Y) \to^{P} 0$, as desired.

Is this a correct proof to show that $X_{n} \to X$ and $Y_{n} \to Y$ in probability implies that $f(X_{n},Y_{n}) \to f(X,Y)$ in probability? If not, then what would be a correct proof? Thank you ahead of time for your time and patience!

UPDATE: As this proof stands, I believe it is incomplete. What I think I need to complete it is a proof of the result that says that the vector $(X_{n},Y_{n}) \to (X,Y)$ in probability if and only if $X_{n} \to X$ in probability and $Y_{n} \to Y$ in probability. Could someone please help me prove this? I think that once I have that, everything else I did here will be okay (please correct me if I'm wrong!) Thank you.

A: Lemma: Let $\{X_{n}\}$ be a sequence of random variables in a probability
space and let $X$ be a random variable. Then the following are equivalent:
(a) $X_{n}\rightarrow X$ in probability,
(b) Any subsequence of $\{X_{n}\}$ has a subsequence that converges
to $X$ in probability.
Proof: $(a)\Rightarrow(b)$ is obvious.
$(b)\Rightarrow(a)$. Prove by contradiction. Suppose the contrary
that there exists $\delta>0$ such that $x_{n}:=P\left([|X_{n}-X|\geq\delta]\right)$
does not converge to $0$. Then $\{x_{n}\}$ has a subsequence $\{x_{n_{k}}\}$
that is bounded away from $0$. That is, there exists $\epsilon>0$
and a subsequence $\{x_{n_{k}}\}$ such that $x_{n_{k}}\geq\epsilon$
for all $k$. Clearly $\{X_{n_{k}}\}_{k}$ does not have a subsequence
that converges to $X$ in probability, contradicting to the assumption (b).
//////////////////////////////////////////////////////////////////////////////////////////
For your problem: Let $f(X_{n_{k}},Y_{n_{k}})_{k}$ be an arbitrary
subsequence of $f(X_{n},Y_{n})_{n}$. Note that $X_{n_{k}}\rightarrow X$
in probability, so $\{X_{n_{k}}\}_k$ has a subsequence $\{X_{n_{k_{l}}}\}_{l}$
that converges pointwisely to $X$ $P-a.e.$ (a result due to Vitali).
$Y_{n_{k_{l}}}\rightarrow Y$ in probability as $l\rightarrow\infty$,
so it has a subsequence $\{Y_{n_{k_{l_{j}}}}\}_{j}$ that converges
to $Y$ pointwisely $P-a.e.$ Now $X_{n_{k_{l_{j}}}}\rightarrow X$
and $Y_{n_{k_{l_{j}}}}\rightarrow Y$ pointwisely $P$-a.e. Since $f$ is continuous,
it follows that $f(X_{n_{k_{l_{j}}}},Y_{n_{k_{l_{j}}}})\rightarrow f(X,Y)$
pointwisely $P$-a.e. and hence $f(X_{n_{k_{l_{j}}}},Y_{n_{k_{l_{j}}}})\rightarrow f(X,Y)$
in probability as $j\rightarrow\infty$. By the lemma, the results
follow.
////////////////////////////////////////////////////////////////////
Please do not completely trust my mathematics and one should examine the above argument carefully before accepting it. As I have not played with probability theory for a long time, I may commit mistake without realizing it. Please do not hesitate and point out my mistakes if you find them.

A: Answer to your more specific question
One way is obvious since $$P(d(X_n,X) < \epsilon) \ge P(d((X_n,Y_n),(X,Y)) <\epsilon) \to 1.$$ (because if $d((X_n,Y_n),(X,Y)) <\epsilon$ then it follows that $d(X_n,X) < \epsilon$.)
For the other way, note that by triangle, $$d((X_n,Y_n),(X,Y))\le d(X_n,X) + d(Y_n,Y)$$ so that if $d((X_n,Y_n),(X,Y))> \epsilon$ it follows that one of  $d(X_n,X)$ or $d(Y_n,Y)$ needs to be greater than $\epsilon/2$ (actually greater than $\epsilon/\sqrt 2$ for Euclidean distance, but it doesn't really matter). So $$ P(d((X_n,Y_n),(X,Y)) >\epsilon)  \le P((d(X_n,X) >\epsilon/2)\cup (d(Y_n,Y) >\epsilon/2)) \\\le P(d(X_n,X) >\epsilon/2) + P(d(Y_n,Y) >\epsilon/2) \to 0$$


text:
Q: Flutter show Login first time I want to show this login screen only on the first start up. After that it s possible to come to login screen by pressing "Account" button in another widget, I already did that. Only the shared prefs bool is my problem: I dont know where do I have to implement the bool, and how do i sent it to the root widget. Let me show the code:
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await init();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return runApp(ChangeNotifierProvider(
      child: const MyApp(),
      create: (BuildContext context) => ThemeService(
          isSysModeOn: prefs.getBool("isSystemMode") ?? true, isDarkOn: prefs.getBool("isDarkModeOn") ?? true)));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(create: (context) => NavbarCubit()),
        BlocProvider(create: (context) => sl<SignupBloc>()),
        BlocProvider(create: (context) => DrinkCubit()),
      ],
      child: Consumer<ThemeService>(builder: (context, themeService, child) {
        return MaterialApp(
            debugShowCheckedModeBanner: false,
            theme: AppTheme.lightTheme,
            darkTheme: AppTheme.darkTheme,
            themeMode: themeService.getSysMode
                ? ThemeMode.system
                : (themeService.getDarkMode ? ThemeMode.dark : ThemeMode.light),
            home: first_time ? const SignUpPage() : RootWidget());
      }),
    );
  }
}

the if question in the home: is manuall added, not working. I know i already did nearly the same thing with the Theme Data as you can see in the void main :D But how do I ask
bool first_time = true;

if(user_firstime_started_app == true){
first_time = false;
prefs.setBool(.....
....
}

something like this.

A: You can show a splash screen while you check if the user is logged in. If the user is logged in then replace and navigate to the home page or the login page.
Refer to this answer and replace the logic of seen with the logic of is logged in: https://stackoverflow.com/a/50655196/2008962.


text:
Q: Python - wrap same object to make it unique I have a dictionary that is being built while iterating through objects. Now same object can be accessed multiple times. And I'm using object itself as a key.
So if same object is accessed more than once, then key becomes not unique and my dictionary is no longer correct.
Though I need to access it by object, because later on if someone wants access contents by it, they can request to get it by current object. And it will be correct, because it will access the last active object at that time.
So I'm wondering if it is possible to wrap object somehow, so it would keep its state and all attributes the same, but the only difference would be this new kind of object which is actually unique.
For example:
dct = {}

for obj in some_objects_lst:
    # Well this kind of wraps it, but it loses state, so if I would
    # instantiate I would lose all information that was in that obj.
    wrapped = type('Wrapped', (type(obj),), {})
    dct[wrapped] = # add some content

Now if there are some better alternatives than this, I would like to hear it too.
P.S. objects being iterated would be in different context, so even if object is the same, it would be treated differently.
Update
As requested, to give better example where the problem comes from:
I have this excel reports generator module. Using it, you can generate various excel reports. For that you need to write configuration using python dictionary.
Now before report is generated, it must do two things. Get metadata (metadata here is position of each cell that will be when report is about to be created) and second, parse configuration to fill cells with content.
One of the value types that can be used in this module, is formula (excel formulas). And the problem in my question is specifically with one of the ways formula can be computed: formula values that are retrieved for parent , that are in their childs.
For example imagine this excel file structure:
  A          | B          | C
  Total        Childs Name Amount
1 sum(childs)
2              child_1      10
3              child_2      20

4 sum(childs)
  ...

Now in this example sum on cell 1A, would need to be 10+20=30 if sum would use expression to sum their childs column (in this case C column). And all of this is working until same object (I call it iterables) is repeated. Because when building metadata it I need to store it, to retrieve later. And key is object being iterated itself. So now when it will be iterated again when parsing values, it will not see all information, because some will overwritten by same object.
For example imagine there are invoice objects, then there are partner objects which are related with invoices and there are some other arbitrary objects that given invoice and partner produce specific amounts.
So when extracting such information in excel, it goes like this:
inoice1 -> partner1 -> amount_obj1, amount_obj2
invoice2 -> partner1 -> amount_obj3, amount_obj4.

Notice that partner in example is the same. Here is the problem, because I can't store this as key, because when parsing values, I will iterate over this object twice when metadata will actually hold values for amount_obj3 and amount_obj4
P.S Don't know if I explained it better, cause there is lots of code and I don't want to put huge walls of code here.
Update2
I'll try to explain this problem from more abstract angle, because it seems being too specific just confuses everyone even more.
So given objects list and empty dictionary, dictionary is built by iterating over objects. Objects act as a key in dictionary. It contains metadata used later on.
Now same list can be iterated again for different purpose. When its done, it needs to access that dictionary values using iterated object (same objects that are keys in that dictionary). But the problem is, if same object was used more than once, it will have only latest stored value for that key.
It means object is not unique key here. But the problem is the only thing I know is the object (when I need to retrieve the value). But because it is same iteration, specific index of iteration will be the same when accessing same object both times.
So uniqueness I guess then is (index, object).

A: I'm not sure if I understand your problem, so here's two options. If it's object content that matters, keep object copies as a key. Something crude like
new_obj = copy.deepcopy(obj)
dct[new_obj] = whatever_you_need_to_store(new_obj)

If the object doesn't change between the first time it's checked by your code and the next, the operation is just performed the second time with no effect. Not optimal, but probably not a big problem. If it does change, though, you get separate records for old and new ones. For memory saving you will probably want to replace copies with hashes, __str__() method that writes object data or whatever. But that depends on what your object is; maybe hashing will take too much time for miniscule savings in memory. Run some tests and see what works.
If, on the other hand, it's important to keep the same value for the same object, whether the data within it have changed or not (say, object is a user session that can change its data between login and logoff), use object ids. Not the builtin id() function, because if the object gets GCed or deleted, some other object may get its id. Define an id attribute for your objects and make sure different objects cannot possibly get the same one.


text:
Q: How to change url protocol in lightning-datatable field with type='url' I have a lightning-datatable with many fields, some of them having type="url". When I create the url attribute for these fields, like this:
element.url = element.active ? `${window.location.origin}/${rowElem.id}` : `##`;

I am getting an href like this:

How I can remove https:// protocol, to get
href="##"

A: It doesn't look like lightning-datatable (actually lightning-formatted-url, which it uses) directly supports other protocols besides http or https.  This is probably to prevent Cross-Site Scripting (XSS) vulnerabilities.  Even the mailto protocol appears to be unsupported.
You can specify a relative URL using /, ./, etc. See documentation for lightning-formatted-url.
To fulfill your requirement, you may need to create a custom data type for lightning-datatable.


text:
Q: local file path won't import I am trying to import the content of a .txt file to a string in my Xcode 9 project using Swift 4. When I use the full path name it imports successfully, current code:
let filePath = URL(fileURLWithPath: "/Users/main/Documents/ClaasPDI/PDIapp/PDIapp/holdMachines.txt")

do
{
    machineString = try String(contentsOf: filePath)

}
catch
{
    print("MACHINE INFORMATION DID NOT IMPORT")
}

I want to be able to import the data from the local path so it can be run on other computers besides mine. My swift files and holdMachines.txt are in the same folder PDIapp but when I change the code to:
let filePath = URL(fileURLWithPath: "holdMachines.txt")

it now crashes my app and says it could not access the file.
I also tried it with a / infront of the file name (below) but that also failed.
let filePath = URL(fileURLWithPath: "/holdMachines.txt")

How can I change my code to access the file through a local file path?

A: Put the text file in your Xcode project and use the following code to read it into a string:
let txtFile = Bundle.main.path(forResource: "holdMachines", ofType: "txt")
do {
        let contents = try? String(contentsOfFile: txtFile!, encoding: .utf8)
} catch let err {
        print(err.localizedDescription)
}


text:
Q: Error in creating EMA formula When I tried to use the EMA function on currencies pair, on the closing price, it seems to return me an error. The code and the error is as follows:
getSymbols('JPY=X', src= 'yahoo')
JPY.EMA.10 <- EMA(`JPY=X`.Close, n=10)
Error: unexpected symbol in "JPY.EMA.10 <- EMA(`JPY=X`.Close"

ps: Im a beginner in the area of R. Sorry if my question seems too trivial.
Regards
Harvey

A: It does indeed exist a ticker symbol with an equal sign in it.
Because of this the notation is going to be a little weird, but we can make it work easily:
library(quantmod)

getSymbols('JPY=X', src= 'yahoo')
#> Warning: JPY=X contains missing values. Some functions will not work if
#> objects contain missing values in the middle of the series. Consider using
#> na.omit(), na.approx(), na.fill(), etc to remove or replace them.
#> [1] "JPY=X"

EMA(`JPY=X`$`JPY=X.Close`, n = 10, na.rm = T)
#> Error in naCheck(x, n): Series contains non-leading NAs

We still get an error, but this is relative to the EMA function, not some syntax error.
You can fix the error with using na.omit(`JPY=X`) as suggested in the warnings.
We can also simplify our life assigning the variable to a more standard name:
JPY_Close <- na.omit(`JPY=X`$`JPY=X.Close`)
EMA(JPY_Close, n = 10)
#>                  EMA
#> 2007-01-01        NA
#> 2007-01-02        NA
#> 2007-01-03        NA
#> 2007-01-04        NA
#> 2007-01-05        NA
#> 2007-01-08        NA
#> 2007-01-09        NA
#> 2007-01-10        NA
#> 2007-01-11        NA
#> 2007-01-12 119.26700
#> 2007-01-15 119.47664
#> 2007-01-16 119.71543
#> 2007-01-17 119.87990
#> 2007-01-18 120.13083
#> 2007-01-19 120.32704
#> 2007-01-22 120.56212
#> ...


text:
Q: How to disable keyboard shortcuts on ASUS laptop I just purchased an ASUS N53S laptop and am having problems with the keyboard. Some keys (such as o, t, or y) are bound by default to software shortcuts. For example, o opens the Power 4 Gear menu, y opens the help menu etc.
I checked and have Sticky keys disabled and the Windows key does not seem to be stuck (although when I press the Windows key, it triggers the application Power 4 Gear as well as the control panel). This keyboard problem is driving me nuts. Any thoughts?

A: Those types of programs are usually as an application loading during the boot process. I would run HijackThis to see what is loading, particularly in the RUN keys, that is related to ASUS. You may realize which one it is by its name, but if not, Google the names of the ASUS programs to get descriptions. You are bound to hit on it, then check in in HijackThis, and let HJT delete it from the regustry for you.
If you are not sure, post back a screenshot of your HijackThis results, and send me a note @kcotreau.

A: My best guess would be to make sure you have the latest drivers installed for the system. That doesn't sound like normal behaviour for a new laptop's keyboard, and I would hope that an update to the machines drivers or firmware would make it work more appropriately. Here is a link:
http://www.service.asus.com/
Just go to "download now" and type in your model.
If that doesn't work...maybe the keyboard is not plugged in correctly? But that's a longshot, and may void your warranty if you try to unplug and replug the keyboard cable.
It certainly doesn't hurt to take  user815423426' recommendation either, you can probably just turn off all startup programs that have ASUS in their name or path safely.
I personally would use ccleaner for changing startup items. It doesn't quite show everything that something like Autoruns would show, but it's quick and it's simple.


text:
Q: How to modify the rows of a matrix, depending on the row (Making a Haar Matrix) I am writing a package that requires making very large Haar matrices ($2^{28} \approx 270$ million rows and columns).  For example:
$$
H_2 = \begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix}
$$
$$
H_4 = \begin{bmatrix} 1 & 1 & 1 & 1 \\ 1 & 1 & -1 & -1 \\ 1 & -1 & 0 & 0\\ 0 & 0 & 1 & -1 \end{bmatrix}
$$
(Note that the dimension is always a power of 2)
I have written a function that will build a Haar matrix of arbitrary size (2^J) using Kroneker products.
$$
H_{2N} = \begin{bmatrix} H_{N} \otimes [1, 1] \\ I_{N} \otimes [1, -1] \end{bmatrix}
$$
However, the iterative nature of such an algorithm is very wasteful memory-wise, and takes a VERY long time in R.
THANKFULLY, the expression of the which values of a particular row should be positive one or negative can be given in closed form, as follows:

*

*For a given value $J$, initialize a matrix of zero with dimension $2^J \times 2^J$

*Set the first row to all ones.

*For all other rows, the width of the sequence of non-zero numbers in any given row is
$$2^{J - \lfloor \log_2(row - 1) \rfloor} $$

*The start position for the aforementioned group is
$$\text{width} * \left((row - 1) - 2^{\lfloor \log_2(row - 1) \rfloor}\right)$$
Thus,

*

*positiveOneStart = width * (row - 1 - 2^floor(log(row - 1, 2))) + 1

*finalOnePosition = (start + width/2 - 1)

*negativeOneStart = finalOnePosition + 1

*finalNegativeOnePosition = positiveOneStart + width - 1

I wrote the following two functions:
rowFill <- function(row, H){

  if(row == 1){
    H[row, ] <<- 1
  }else{
    (log2row <- 2^floor(log(row - 1, 2)))
    (width <- dimension / log2row %>%
      round())
    (width <- suppressWarnings(as.integer(width)))

    (start = width * (row - 1 - 2^floor(log(row - 1, 2))) + 1 %>%
      round())
    (startOnes <- as.integer(start))

    (endOnes <- startOnes + width/2 -1)

    (startNegOnes <-  endOnes + 1)

    (endNegOnes <- startOnes + width - 1)

    H[row, startOne:endOnes] <<- (1)
    H[row, startNegOnes:endNegOnes] <<- (-1)
  }
}

When I use the idea above in a loop to fill the rows, it seems to work fine.
library(purrr)

J = 3
dimension <- 2^J
row <- 1:(dimension)
H = Matrix::Matrix(0, nrow = dimension, ncol = dimension) %>% methods::as("dgCMatrix")

H[1,] <- 1

for(row in 2:2^J){
width <- dimension / 2^floor(log(row - 1, 2)) %>%
  round()
width <- suppressWarnings(as.integer(width))

start = width * (row - 1 - 2^floor(log(row - 1, 2))) + 1 %>%
  round()
start <- as.integer(start)

endOnes <- start + width/2 -1

startNegOnes <-  endOnes + 1

endNegOnes <- start + width - 1

H[row,start:endOnes] <- 1
H[row,startNegOnes:endNegOnes] <- -1

}

H

It works!
8 x 8 sparse Matrix of class "dgCMatrix"

[1,] 1  1  1  1  1  1  1  1
[2,] 1  1  1  1 -1 -1 -1 -1
[3,] 1  1 -1 -1  .  .  .  .
[4,] .  .  .  .  1  1 -1 -1
[5,] 1 -1  .  .  .  .  .  .
[6,] .  .  1 -1  .  .  .  .
[7,] .  .  .  .  1 -1  .  .
[8,] .  .  .  .  .  .  1 -1

However, I want to avoid loops, as I am working on a matrix that is $2^{28}$ (really big), and loops they can be very slow. So I thought I'd try the purrr package function walk to modify the H matrix as a side-effect:
haarFill <- function(J){
  dimension <- 2^J
  row <- 1:(dimension)
  H = Matrix::Matrix(0, nrow = dimension, ncol = dimension) %>% methods::as("dgCMatrix")
  walk(.x = row, .f = rowFill, H)
}

However, this does not give me the desired result:
8 x 8 sparse Matrix of class "dgCMatrix"

[1,] 1  1  1  1  1  1  1  1
[2,] .  .  .  1 -1 -1 -1 -1
[3,] .  1 -1 -1  1  .  .  .
[4,] .  .  .  .  1  1 -1 -1
[5,] 1 -1  1  1  1  .  .  .
[6,] .  .  1 -1  1  .  .  .
[7,] .  .  .  .  1 -1  .  .
[8,] .  .  .  .  1  1  1 -1

Can anyone help me see what is wrong?  I have unit tested this thing to death, and I can't seem to figure out where the error is.


text:
Q: MFC Scroll Draw Error I have a CDialog and inside the Dialog there is a CWnd which contain a scroll bar. I wrote a function to handle scroll. When I do a scroll the items are blurred and duplicated. But when I minimize and open it again all seems ok. What would be the reason for this??..

A: It worked after I override the OnPaint() method.
void MyWnd::OnPaint()
{
    CPaintDC oDC(this);

    CRect oRect;
    GetClientRect(oRect);
    CBrush oBrush(RGB(255, 255, 255));

    oDC.FillRect(oRect, &oBrush);

}


text:
Q: When is $\tan(a+b)$ undefined? For what values of $a$ and $b$ is $\tan(a+b)$ undefined? What is the relationship between $a$ and $b$ when it is undefined?
What about for $\tan(a-b)$?

A: Since $\tan \alpha$ is undefined whenever $\alpha = \frac{\pi}{2} + k\pi$ where $k$ ranges through the integers. Then it follows by setting $\alpha = a \pm b$ that $$\tan (a \pm b) \text{ is undefined when } \\ \\ \bbox[15px, border:blue solid 1px]{a\pm b = \frac{\pi}{2} + k\pi}$$
Where $k \in \mathbb{Z}$.
Edit: I suppose that the relationship between $a$ and $b$ would be that $\tan (a \pm b)$ is undefined when $$a = \frac{\pi}{2} \mp b + k\pi $$

A: Always defined except when there is jump in sign of $\infty $  when $ a \pm b$  becomes odd multiples of $\pi/2.$

A: In degrees:
$\tan(90)$ is undefined.
Therefore is $a+b=90$ or $a-b=90$ create undefined solutions for whatever $a$ and $b$ that fit this equation.
The tan of any odd multiple of $90$ such as $90, 270, 450,$ etc. is also undefined.


text:
Q: Flutter: How to use HapticFeedback I have imported
import 'package:flutter/services.dart';

and then called
HapticFeedback.lightImpact();

nothing happens. What do I need to do to get it working?
I am testing with the latest Flutter version 1.6.6 on a Galaxy S8 running Android 9.0

A: Please also check whether, Vibration feedback setting was enabled on the device or not . I faced same issue but later found out that Haptic Feedback vibration was off on my device (I was testing it in Android 9) so, make sure to enable it.
To enable it,

Go to settings>sound&vibration>touch vibration

A: Try using this for Android:
Feedback.forTap(context);

More info: https://api.flutter.dev/flutter/material/Feedback-class.html

A: This is helped me
First Go to AndroidManifest and add
<uses-permission android:name="android.permission.VIBRATE" />

If the Flutter app is running stop it and run it again.
Then use this code
import 'package:flutter/services.dart';

And in Ontap or OnPressed Method
Clipboard.setData(ClipboardData());
HapticFeedback.heavyImpact();

That's all

A: Reading the function description it says:
"On Android, this uses HapticFeedbackConstants.KEYBOARD_TAP."
If the vibrations for the keyboard or 'haptic feedback for tap' are turned off (in the phone's settings), calling HapticFeedback.mediumImpact(); will not have an effect.
To fix the problem one would have to turn on Touch vibration in the phone's settings.

A: Please make sure that Vibration feedback is enabled on the android device, and make sure to add
 <uses-permission android:name="android.permission.VIBRATE" />

to the AndroidManifest.xml.
See more info here: https://github.com/flutter/flutter/issues/33750

A: import 'package:flutter/services.dart';

*

*import the services package

then inside onTap method
onTap: () {
    Clipboard.setData(ClipboardData(text: data));
    HapticFeedback.heavyImpact();
}
it worked for me.

A: If only activating  touch vibration on phone doesn't solve the issue , try switching between Vibrate on tap modes.Default setting is Off.
Vibrate on tap (Settings -Off(default),Ligh,Medium,Strong)


text:
Q: How can I send a wave towards something and have it respond with a specific value? Imagine a bat, for example. It uses its echo-location to send waves which get reflected back and thus return information about the surroundings. I want to do the same thing, but instead of just telling me there is a wall there, I want to return a number that I have "written" on the wall.
Suppose that I "write" the number 5 on the wall. How would I need to "write" the number 5 on the wall so that I can send some type of EM wave towards it and receive the number 5 in response?
Constraints/Assumptions:

*

*Whatever is done to the wall cannot be battery powered.

*There is nothing that can interfere with the travelling wave.

*The wave can be of any type in the electromagnetic spectrum.

*There will be other things "written" on other walls, so the wave will need to be able to distinguish from other "writings". If I "write" a 5 on one wall and a 6 on another, I need to be able to tell them apart. There can be $n$ number of writings on each wall, within some reasonable limit as defined by the solution.

Edit: - I noticed that most of the suggestions imply visible light. Although this is technically possible, I was hoping for something that was undetectable to the human eye/ear. For example, the RFID tag is more along the lines of what I was looking for. Basically, I need to send a signal and receive a signal back where the returning signal has a uniquely identifying value.

A: The high-tech way to make a return wave 'do what you want' is to
make a hologram.   A wall-hanging photographic plate, illuminated
by a monochromatic light source from a given direction, can
reproduce a monochrome image, in three dimensions, of anything
you choose to pose for the initial photographic exposure.
Light from off-target will generally only reveal a blur,
and light of a different color might give a distorted (larger
or smaller) image.   Multiple exposures with different
light sources can make multiple images onto a single surface,
each becoming distinct only with its associated reference
light source location and color.

A: you could paint the number on the wall with ultraviolet paint, and the detector would be an ultraviolet detector.
Or you could use ultrasound as detector and the number in a material that has high ultrasonic refraction.


text:
Q: Django: Can not get django-admin.py to run anything System: Windows 7x64
Django v. 1.4
Python v. 3.2
First time working with Django or python and I am beating my head against the wall.  I have installed everything for Django according to the install instructions.  The only step I skipped was the 'optional' virtualenv installation.
I am attempting to run the tutorial on djangoproject.com and I can't get startproject to work.  Here is my issues.
When attempting to use 'django-admin.py startproject mysite' or even just 'django-admin.py help' functions I get the following:

Traceback (most recent call last):
  File "C:\Python32\Scripts\django-admin.py", line 2, in

from django.core import management   File "C:\Python32\lib\site-packages\django\core\management__init__.py",
  line 54
except ImportError,e:
                   ^
  SyntaxError: invalid syntax

Where the ^ is pointing to the comma.
I have checked the permissions for the folder I am in and everything appears to be good there.  What am I doing wrong?

A: Django doesn't work with Python 3 (yet).
Install 2.7 instead.

A: You might also stick to Python 3.X and get django 1.5 that is currently in beta phase.

A: Python 3.3 offers experimental support. django-admin.py still won't run properly, but here's a workaround for you:
You can call the django-admin subcommands directly from your own python script.
from django.core import management
management.call_command("startproject", "mysite")

Almost everything else should be done from the manage.py file it generates, which should work fine with:
python manage.py runserver

or whatever command you're looking for. You may also be using "python33" instead of python.

A: General answer: that syntax line isn't valid in Python 3.2 (Django doesn't work with Python 3 yet). Here's a list of the 2.x versions you can use with particular versions of Django.
Specific answer: According to PEP-3110, the syntax for exceptions changed from except Exception, e to except Exception as e in Python 3, which is why that error's showing up.


text:
Q: How to Track button press event for asp.net in C# webform? I am trying to create a website in asp.net. I want to change ImageButton's image in pressed and unpressed state both.
So I need both pressed event and unpressed event in CSharp. How can I get that ?

A: Mouse down and mouse up events are not supported in sever-side code because of potential performance issues. However, you can write some client-side code which can trigger the wanted behaviour. I would advise writing javascript code for this.
http://www.w3schools.com/jsref/event_onmousedown.asp
http://www.w3schools.com/jsref/event_onmouseup.asp


text:
Q: warning: passing argument 1 of 'uart1_sendchar' makes pointer from integer without a cast [enabled by default] i am getting warning but i tried to get info from similar posts but didn't get satisfied result
printstring get unsigned char and send char take *char so do i have to type cast or something ?? please help
uartcustom.c: In function 'uart1_printString':
uartcustom.c:162:9: warning: passing argument 1 of 'uart1_sendchar' makes pointer
                             from integer without a cast [enabled by default]
uart1_sendchar(string[local_counter]); // print each character
     ^

Two functions which are used  are
uart1_sendchar
and uart1_printstring
/*****************************************************************************
 //     Uart 1 send char                         */
 /***************************************************************************/
void uart1_sendchar(char* tempchar)
{
    int temp;
    temp=write(device_uart1,&tempchar,1);
    if(temp < 0)
    {
        printf("port failed to write\n");
    }
}

/*****************************************************************************
//      Uart 1 printstring                       */
/*****************************************************************************/

void uart1_printString( unsigned char *string)
{
    int local_counter = 0;
    // loop through until reach string's zero terminator
    while (string[local_counter] != 0)
    {
        uart1_sendchar(string[local_counter]); // print each character
        local_counter++;
    }
}

A: string is unsigned char * so string[local_counter] is unsigned char
You probably want:
uart1_sendchar(&string[local_counter]);


text:
Q: Binomial Coefficient and the Number of Combinations when $k=0$ This must have been asked before, but I couldn't find it. I am looking for an explanation, intuitive if possible (less technical), for why $\binom{n}{0}$ equals $1$. I understand that mathematically $0!=1$, but I am looking for the verbal explanation.  $\binom{n}{k}$ is the number of combinations of size $k$ from a set of $n$ objects, what is the meaning of choosing $0$ objects out of $n$? Why is it $1$?

A: Another definiton of the binomial coefficient is: How many subsets with $k$ elements does a Set with $n$ elements have? Well, there is only one set with zero elements, which is the empty set and the empty set is a subset of every set. Thus, the empty set qualifies as subset for every set with arbitrary size $n$ and as long as $k$ is $0$, there will be only one solution.

A: Just think of sitting in front of $n$ distinct objects. In how many ways can you pick up one? Well, ${n \choose 1}=n$ ways, since you could either pick up the first, or the second, etc. The same reasoning of course goes for $k$ objects. Now imagine NOT picking up anything. In how many WAYS can you do this, i.e do nothing? Well in one way, just don't pick anything up.
If you want to think about unordered strings without repititions, or something like that, you could think about how many strings of zero charachters there are. That would be the empty string, and there is only one.
For a more set theoretical explaination, I believe Brians answer, in the comments above, is a good one, namely that a set has only one subset with zero members.
Edit: That there is only one unique empty set can be proven. Even though there might not be a nice proof that there's only one way to do nothing, the reasoning is the same. Think about how there could be more than one way to do nothing, what would make those ways different? (A possible 'proof' of this would most likely reduce to proving that there is only one empty set.)
I hope this was verbal enough. I am not sure how to explain it informally in a better way.


text:
Q: WPF MVVM handle datagrid cell change i try to catch CellEditEnding Event and get the row+column number and the new value to my view model.
i try this How do you handle data grid cell changes with MVVM?  but i get this exception

"the type 'GalaSoft_MvvmLight_Command' was not found.verify that you
  are not missing an assembly reference and that all reference assembly
  have been built". i have reference to GalaSoft.MvvmLight.WPF4.dll.

this is my dataGrid:
 <DataGrid MaxHeight="600" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto"
                  ItemsSource="{Binding BitTestParam,Mode=TwoWay}" GridLinesVisibility="None" RowBackground="{x:Null}" Background="{x:Null}"
                  BorderThickness="2" BorderBrush="Black" HeadersVisibility="Column" Foreground="Black" FontStyle="Italic" FontWeight="SemiBold">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="CellEditEnding">
                    <i:InvokeCommandAction Command="{Binding CellChangedCommand}" CommandParameter="{Binding}"/>
                    <!--<GalaSoft_MvvmLight_Command:EventToCommand PassEventArgsToCommand="True" Command="{Binding CellEditEndingCommand}"/>-->
                </i:EventTrigger>
            </i:Interaction.Triggers>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Input Param" Binding="{Binding InputNames}"/>
                <DataGridTextColumn x:Name="InputValuesColumn" Header="Param value" Binding="{Binding InputValues}" />
                <DataGridTextColumn Header="Output Param" Binding="{Binding OutputNames}"/>
                <DataGridTextColumn Header="Measure value" Binding="{Binding OutputValues}"/>
                <DataGridTextColumn Header="Error Messages" Binding="{Binding ErrorMessages}"/>
                <DataGridTextColumn Header="Warning Messages" Binding="{Binding WarningMessages}" />
            </DataGrid.Columns>
        </DataGrid>

this is my relevant code in the viewModel:
public RelayCommand<object> CellChangedCommand
{
    get;
    set;
}

CellChangedCommand = new RelayCommand<object>(CellChangedEvent);

void CellChangedEvent(object obj)
{

}

i get my Command "CellChangedCommand" with parameter but i need to get the row+column number and the new value.
Thanks

A: I would make the user edit in a separate panel and handler validation there.
That's how this sample works:
https://gallery.technet.microsoft.com/scriptcenter/WPF-Entity-Framework-MVVM-78cdc204
In that you will find some code which works out which binding just transferred data from the view to the viewmodel.
You could still use that even if the user edits in a datagrid.
You'd just need a grid or panel around your datagrid.
It might even work in the datagrid, I'd have to try that to know for sure.
But if you look in the project's resource dictionary you will see:
    <Grid Visibility="{Binding IsInEditMode, Converter={StaticResource BooleanToVisibilityConverter}}"
           Width="{Binding ElementName=dg, Path=ActualWidth}"
           Height="{Binding ElementName=dg, Path=ActualHeight}"
           >
                <i:Interaction.Triggers>
                    <local:RoutedEventTrigger RoutedEvent="{x:Static Validation.ErrorEvent}">
                        <e2c:EventToCommand
                                                Command="{Binding EditVM.TheEntity.ConversionErrorCommand, Mode=OneWay}"
                                                EventArgsConverter="{StaticResource BindingErrorEventArgsConverter}"
                                                PassEventArgsToCommand="True" />
                    </local:RoutedEventTrigger>
                    <local:RoutedEventTrigger RoutedEvent="{x:Static Binding.SourceUpdatedEvent}">
                        <e2c:EventToCommand
                                                Command="{Binding EditVM.TheEntity.SourceUpdatedCommand, Mode=OneWay}"
                                                EventArgsConverter="{StaticResource BindingSourcePropertyConverter}"
                                                PassEventArgsToCommand="True" />
                    </local:RoutedEventTrigger>
                </i:Interaction.Triggers>

Conversion failures or removing them are grabbed by the former and data transfer by the latter.
You need to mark bindings to notifyonsourceupdated - an example binding is:
<TextBox Text="{Binding  EditVM.TheEntity.Address1,
                        UpdateSourceTrigger=PropertyChanged,
                        NotifyOnSourceUpdated=True,
                        NotifyOnValidationError=True,
                        Mode=TwoWay}"  />

Other code is in the sample if I miss something.
Routedeventtrigger
public class RoutedEventTrigger : EventTriggerBase<DependencyObject>
{
    RoutedEvent routedEvent;
    public RoutedEvent RoutedEvent
    {
        get
        {
            return routedEvent;
        }
        set
        {
            routedEvent = value;
        }
    }

    public RoutedEventTrigger()
    {
    }
    protected override void OnAttached()
    {
        Behavior behavior = base.AssociatedObject as Behavior;
        FrameworkElement associatedElement = base.AssociatedObject as FrameworkElement;
        if (behavior != null)
        {
            associatedElement = ((IAttachedObject)behavior).AssociatedObject as FrameworkElement;
        }
        if (associatedElement == null)
        {
            throw new ArgumentException("This only works with framework elements");
        }
        if (RoutedEvent != null)
        {
            associatedElement.AddHandler(RoutedEvent, new RoutedEventHandler(this.OnRoutedEvent));
        }
    }
    void OnRoutedEvent(object sender, RoutedEventArgs args)
    {
         base.OnEvent(args);
    }
    protected override string GetEventName()
    {
        return RoutedEvent.Name;
    }
}

Bindingsourcepropertyconverter
public class BindingSourcePropertyConverter: IEventArgsConverter
{
    public object Convert(object value, object parameter)
    {
        DataTransferEventArgs e = (DataTransferEventArgs)value;
        BindingExpression binding = ((FrameworkElement)e.TargetObject).GetBindingExpression(e.Property);
        return binding.ResolvedSourcePropertyName ?? "";
    }
}


text:
Q: Where does the serveHTTP utility come from on supposedly naked func I have this utility:
type Handler struct{}

func (h Handler) Mount(router *mux.Router, v PeopleInjection) {
    router.HandleFunc("/api/v1/people", h.makeGetMany(v)).Methods("GET")
}

the above calls this:
func (h Handler) makeGetMany(v PeopleInjection) http.HandlerFunc {

    type RespBody struct {}

    type ReqBody struct {
        Handle string
    }

    return tc.ExtractType(
        tc.TypeList{ReqBody{},RespBody{}},
        func(w http.ResponseWriter, r *http.Request) {
         // ...
    })
}

and then tc.ExtractType is like so:
func ExtractType(s TypeList, h http.HandlerFunc) http.HandlerFunc {

    return func(w http.ResponseWriter, r *http.Request) {

        h.ServeHTTP(w, r)  // <<< h is just a func right? so where does ServeHTTP come from?
    }
}

my question is - where does the serveHTTP method/func come from??
isn't the h parameter just a func with this signature:
func(w http.ResponseWriter, r *http.Request) { ... }

so then how does that func have the ServeHTTP func attached to it?
In other words, why I am I calling
h.ServeHTTP(w,r)

instead of
h(w,r)

?

A: The http.HandlerFunc is a type represent func(ResponseWriter, *Request).
The difference between http.HandlerFunc and func(ResponseWriter, *Request) is: http.HandlerFunc type has method called ServeHTTP().
From the source code:
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

The http.HandlerFunc() can be used to wrap handler function.
func Something(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // do something

        next.ServeHTTP(w, r)
    })
}

The wrapped handler will have http.HandlerFunc() type, meaning we'll be able to access it's .ServeHTTP() method.

There is also another type, an interface called http.Handler. It has .ServeHTTP() method signature, and it must be implemented on the struct where the interface is being embedded.
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

As you can see on Something() function above, a return value in http.Handler type is required, but we returned a handler wrapped in http.HandlerFunc(). It's fine, because the http.HandlerFunc has method .ServeHTTP() who fulfil the requirement of http.Handler interface.

In other words, why I am I calling h.ServeHTTP(w,r) instead of h(w,r)?

Because to continue serve the incoming request, you need to call .ServeHTTP().


text:
Q: Why this query and condition return rows I'm working on a large select statement, it was working fine, but with some dates
it gives a strange result, I started reducing it to track the mistake in vain!
until I wrote this code
SELECT DISTINCT
     CURDATE()      AS `Rdat`,
    `p`.`pspsalm1` AS `pspsalm1`,
    `p`.`pspsalm2` AS `pspsalm2`,
    `p`.`pspsalm3` AS `pspsalm3`,
    p.`PSDescription` AS `PSDescription`
FROM
    (`dailyreadings` `d`, `psalms` `p`, `weeks` `w` ,`feasts` `f`)
WHERE      1=2

it gives result as well..!
I think this condition ( 1=2) should give no result
any clarification?

A: It shouldn't give any result
Try:
refreshing your browser
clear broser cache and try again

A: Thanks to you guys
It is a browser issue,
the browser kept the previous criteria and query data using it, even when I changed the condition in the sql statement.
Thanks to you all


text:
Q: Can aggregate filter expressions not use indices? One cool thing about filter expressions is that you can do multiple different filters and aggregates in one query. The "where" part becomes part of the aggregation rather than the whole "where" clause.
For example:
SELECT count('id') FILTER (WHERE account_type=1) as regular,
       count('id') FILTER (WHERE account_type=2) as gold,
       count('id') FILTER (WHERE account_type=3) as platinum
FROM clients;

(from the Django documentation)
Either this is a bug in PostgreSQL 9.5 or I'm not doing it right, or it's simply a limitation of PostgreSQL.
Consider these two queries:
select count(*)
from main_search
where created >= '2017-10-12T00:00:00.081739+00:00'::timestamptz
and created < '2017-10-13T00:00:00.081739+00:00'::timestamptz
and parent_id is null;

select
count('id') filter (
where created >= '2017-10-12T00:00:00.081739+00:00'::timestamptz
and created < '2017-10-13T00:00:00.081739+00:00'::timestamptz
and parent_id is null) as count
from main_search;

(The main_search table has a combined btree index on created and parent_id is null)
Here's the output:
 count
-------
  9682
(1 row)

 count
-------
  9682
(1 row)

If I stick a explain analyze in front of each query, this is the output:
    QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=1174.04..1174.05 rows=1 width=0) (actual time=5.077..5.077 rows=1 loops=1)
   ->  Index Scan using main_search_created_parent_id_null_idx on main_search  (cost=0.43..1152.69 rows=8540 width=0) (actual time=0.026..4.384 rows=9682 loops=1)
         Index Cond: ((created >= '2017-10-11 20:00:00.081739-04'::timestamp with time zone) AND (created < '2017-10-12 20:00:00.081739-04'::timestamp with time zone))
 Planning time: 0.826 ms
 Execution time: 5.227 ms
(5 rows)

                                                          QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=178054.93..178054.94 rows=1 width=12) (actual time=1589.006..1589.007 rows=1 loops=1)
   ->  Seq Scan on main_search  (cost=0.00..146459.39 rows=4212739 width=12) (actual time=0.051..882.099 rows=4212818 loops=1)
 Planning time: 0.051 ms
 Execution time: 1589.070 ms
(4 rows)

NOTE! The filter expression SELECT statement always use a sec scan instead of an index scan :<
I've tried this too with another PostgreSQL 9.5 table in a different database. At first I thought the "Seq Scan" happened because the table had too few rows but both tables are huge enough that an index should kick in.

A: You misunderstud the usage case.
Filter affect only aggregate on PRODUCED ALREADY DATASET.
It do not filter records.
consider modified example:
SELECT count(*) FILTER (WHERE account_type=1) as regular,
       count(*) FILTER (WHERE account_type=2) as gold,
       count(*) FILTER (WHERE account_type=3) as platinum,
       count(*)
FROM clients;

how where clasue should be then?
WHERE
(WHERE account_type=3)
or
(WHERE account_type=2)
or
(WHERE account_type=1)
or 1=1 ???

think about much more complicated FILTER and combination of unfiltered columns. It will be nightmare to the optimizer.
When you think about FILTER consider that this is only shortcut for longer sentence like CASE
SELECT SUM(CASE WHEN account_type=1 THEN 1 ELSE 0 END) as regular,
       SUM(CASE WHEN account_type=2 THEN 1 ELSE 0 END) as gold,
       SUM(CASE WHEN account_type=3 THEN 1 ELSE 0 END) as platinum
FROM clients;


text:
Q: Como buscar a maior data no MongoDB junto com outros parâmetros? Tenho um schema que contem data, status e código:
var entregaSchema = mongoose.Schema({
        codEntrega: String,
        placaPipa: String,
        codRota: String,
        codMA: String,
        dataMA: Date,
        localMA: String,
        codPA: String,
        dataPA: Date,
        localPA: String,
        statusEntrega: String,
        cadEntrega: Date
});

Gostaria de varrer este esquema e trazer a maior data para o codPA passado e com status a 3 que seria finalizado.
Tipo: para o codPA = 34, onde existir maior data e status = 3, isso será executado num for para cada PA, 1,2..34 e ao encontrar vai realizar outra função de inserir uma nova entrega para este PA se caso um calculo de tempo em relação a ultima data trazida com um tempo passado. Tipo, se dataPA >= 7 Inserir entrega para este codPA.

A: Você pode usar o Aggregation framework do mongodb para fazer isso.
Utilizando o mongoose, seria mais ou menos assim:
// Troque essa linha pelo seu mapeamento
var entregaModel = mongoose.model("entrega", entregaSchema);

entregaModel.aggregate([

    // Filtra para apenas os documentos com status = 3
    { $match: { statusEntrega: 3 },

    // Desses documentos, junte todos os que tem codPA iguais
    // E salve a maior dataPA em "maiorData"
    { $group: {
        _id: "$codPa",
        maiorData: { $max: "$dataPA"  }
    }}

], function (err, result) {
    if (err)
        console.log(err);
    else
        // Sai a lista de todos os codPA e a data deles
        // já filtrados pelos com status = 3
        console.log(result);
});

Para saber mais sobre o framework aggregate do mongodb, dá uma lida nesse link: https://docs.mongodb.com/manual/core/aggregation-pipeline/
A api do aggregate no mongoose fica nesse link: http://mongoosejs.com/docs/api.html#aggregate_Aggregate
Espero ter ajudado


text:
Q: how to use filter a list and append to stringbuilder using stream() java8 I have a list which I need to iterate on the basis of certain conditions as below:
StringBuilder sb = new StringBuilder();
list.stream().forEach(l-> {
    if(l.contains("(")){
      sb.append("a");
    } else
      sb.append("b");
    });

How to do the same operation using filter of stream.

A: you can try this,
List<String> val = Arrays.asList("There", "(may)", "(not)", "exist", "brackets");
        StringBuilder sb = val.stream()
           .map(a -> a.contains("(")? "a": "b")
           .collect(StringBuilder::new,StringBuilder::append,StringBuilder::append);
        System.out.println(sb);

Output:
baabb

A: You can use map() and put your condition
StringBuilder sb = new StringBuilder();
list.stream().map(str -> {
  if (str.contains("(")) {
    return "a";
  }
  return "b";
}).forEach(sb::append);

A: It's not exactly what you asked for, but I thought it was worth presenting as an idea to consider.
    List<String> list = List.of("There", "(may)", "(not)", "exist", "brackets");
    String result = list.stream()
            .map(s -> s.contains("(") ? "a" : "b")
            .collect(Collectors.joining());
    System.out.println(result);

Output is:

baabb

Stream operations should generally be free from side effects, and their effect rather come out of their terminal operation. If you do need a StringBuilder, construct one after the end of the stream opeartion:
    StringBuilder sb = new StringBuilder(result);


text:
Q: select the story with its comments and replies and check if current user likes or not in one single query I have four tables

Posts:

post_id     title    Userid    description
1           test     20           TEXT

Comments:

comment_id     post_id    Userid    content
1                1           5        TEXT
2                1           36       TEXT
3                1           6        TEXT

Replies

reply_id     comment_id    Userid    content
1                1           4        TEXT
2                2           5        TEXT
3                2           30       TEXT

likes:

post_id     Userid
1           5

The site starts loading last 20 story in the database.. Now suppose userid (5) is logged in, for example post_id (1) show as liked and all posts show with their comments and replies. I wanna done that in one query instead of nested loops inside loops.

My code:

$sql1 = $conn->prepare("SELECT * FROM posts ORDER BY post_id DESC LIMIT 20");
$sql1->execute();
   while($row1=$sql1->fetch(PDO::FETCH_ASSOC)){
        ....
        // <div class="post" id="<?php echo row1['post_id']; ?>

         .
         .
         ....
         $sql2 = $conn->prepare("SELECT * FROM comments WHERE post_id=:post_id");
         $sql2 ->bindValue(':post_id', $row1['post_id']);
         $sql2 -> execute();
         while($row2=$sql2 -> fetch(PDO::FETCH_ASSOC)){
                ....
                // <div class="comment" id="<?php echo row2['comment_id']; ?>

                .
                .
                ....
                $sql3 = $conn->prepare("SELECT * FROM replies WHERE comment_id=:comment_id");
                $sql3 -> bindValue(':comment_id', $row2['comment_id']);
                $sql3 ->execute();
                  while($row3=$sql3 ->fetch(PDP::FETCH_ASSOC)){ .... }

         }
         $sql_like=$conn->prepare("SELECT * from likes WHERE post_id = $row1['post_id'] AND user_id=$logged_user_id");
          $sql_like->execute();
          $sql_like->rowCount() > 1 ? //userlikes : //user does not like ;
   }

A: Your question is not 100% clear, but you can start from something like this:
$sql1 = $conn->prepare("SELECT p.*,
                 c.comment_id,
                 r.reply_id,
                 COUNT(DISTINCT l.post_id) likes
             FROM (SELECT
                FROM posts
                ORDER BY post_id DESC LIMIT 20
             ) p
             LEFT JOIN comments c
             ON p.post_id = c.post_id
             LEFT JOIN replies r
             ON c.comment_id=r.comment_id
             LEFT JOIN likes l
             ON l.post_id = p.post_id
               AND l.user_id=$logged_user_id");
$sql1->execute();
   $last_post_id = 0;
   $last_comment_id = 0;
   while($row = $sql1->fetch(PDO::FETCH_ASSOC)){
     if ($last_post_id != row['post_id'] ) {
        echo '
'.$row['post_id'].'
';
        echo '
'.$row['likes'].'
';
        ...
        $last_post_id = row['post_id'];
        $last_comment_id = 0;
     }
     ...
     if ($last_comment_id != $row['comment_id']) {
       echo '
'.$row['comment_id'].'
';
       $last_comment_id = $row['comment_id'];
     }
     ...                    .
     echo '
'.$row['reply_id'].'
';

   }

A: You could use a subquery to count the likes from the logged in user in the likes table that match the post id.
SELECT *,
   (SELECT COUNT(*) FROM likes l WHERE l.post_id=p.post_id AND user_id = '$logged_user_id') AS userlikes
   FROM posts p ORDER BY p.post_id DESC LIMIT 20


text:
Q: About django/restframework request This is my APIview:
class Comments(ListCreateAPIView):

   queryset = models.NewsComment.objects
   filter_backends = [CommentsFilterBackend]
   http_method_names = ["get", "post"]

   def get_serializer(self, *args, **kwargs):
      if self.request.method = "get":
          return Myserializer

I want to know why self.request can call the  "method".  Isn't it the encapsulated Request new object? The native request object is encapsulated in Request obj. Why can self.request call the request.method attrs?

A: The answer is in the source code of Request class, more specifically at the the __getattr__ method (line 410):
    def __getattr__(self, attr):
        """
        If an attribute does not exist on this instance, then we also attempt
        to proxy it to the underlying HttpRequest object.
        """
        try:
            return getattr(self._request, attr)
        except AttributeError:
            return self.__getattribute__(attr)

It's one of Python's "magic methods" and you can read more about it here.


text:
Q: How to set css designs using loop in html page Reference image
->once look at my reference image
->In that image, I have taken one  for loop (for creating box design) and made that design above
->But I want to change the background colour and border colour for all the boxes using one HTML class name (like shown in the image)
->Border colour and the background colour should be different for every box.
-> And look at the second box in the image (loans) in that we can see crop loan admin but in other boxes, only members are there how to put condition for this?
->And in all the boxes arrow icon is there in the 1st row only how to put condition for this?
->How to do that? check my code I have used separate div for all the boxes I need to iterate using loop and bind names, border colour, and background colour for all boxes.
Html
<mat-card class="mat mr-4 ml-5 p-3" fxLayout="column" fxFlex>

      <ng-container *ngFor="let item of items">

{{item?.title}}

 Members <mat-icon class="arrow-icon">arrow_right_alt</mat-icon> 1000

 Non-Members 200

 Traders 250

 Employee 40

-

-

    </ng-container>

  </mat-card>

CSS
.overview-cart {

  position: relative;

  width: calc(100% - 80px);

  background-color: #5f7dff;

  overflow: hidden;

  &:after {

    content: "";

    position: absolute;

    right: -175px;

    top: 0;

    border-width: 153px;

    border-style: solid;

    border-color: transparent;

    border-top-color: #fff;

    z-index: 99;

    transform: rotate(19deg);

  }

}

.cart-styling {

  width: 100%;

  justify-content: center;

  height: 30%;

  border: 1px solid #5f7dff;

}

.heading-text {

  font-size: 18px;

  font-weight: normal;

  color: #fff;

}

img {

  width: 90px;

  height: min-content;

}

.mat {

  height: auto;

}

.line {

  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;

  font-size: 14px;

}

.main-line {

  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;

  font-size: 14px;

  color: #0b4983;

}

.arrow-icon {

  line-height: 0.8;

  color: #0b4983;

  margin-right: 75%;

}

.value-color {

  color: #065a3d;

}

.content {

  background-color: #f7f7f9;

}

Ts file
items: any[]= [

    {

      id : 0,

      title: 'Customer',

      submodules: {

        members: 1000,

        non_members: 200,

        traders: 250,

        employees: 40

      }

    },

    {

      id: 1,

      title: 'Loans',

      submodules: {

        Crop_loan_admin: 1000,

        non_members: 200,

        traders: 250,

        employees: 40

      }

    },

    {

      id: 2,

      title: 'Insurance',

      submodules: {

        members: 1000,

        non_members: 200,

        traders: 250,

        employees: 40

      }

    },

  // ]

  // lists: any[]=[

    {

      id: 3,

      title: 'Inventory',

      submodules: {

        members: 1000,

        non_members: 200,

        traders: 250,

        employees: 40

      }

    },

    {

      id: 4,

      title: 'Accounts',

      submodules: {

        members: 1000,

        non_members: 200,

        traders: 250,

        employees: 40

      }

    },

    {

      id: 5,

      title: 'Masters',

      submodules: {

        members: 1000,

        non_members: 200,

        traders: 250,

        employees: 40

      }

    },

  ]

A: store your colors as a property to each item
{

      id : 0,

      title: 'Customer',

      theme : "red", // for example

      submodules: {

        members: 1000,

        non_members: 200,

        traders: 250,

        employees: 40

      }

    },

then use ngStyl in html file (check for the right div to place ngStyle

...

 <ng-container *ngFor="let item of items">

...

A: You can not do that with one css class. but you can do this:
adding theme color to you object:
items: any[]= [
  {
    id: 0,
    theme: '#ff0000',
    title: 'Customer',
    submodules: {
      members: 1000,
      non_members: 200,
      traders: 250,
      employees: 40
    }
  },
  {
    id: 1,
    theme: '#00ff00',
    title: 'Loans',
    submodules: {
      Crop_loan_admin: 1000,
      non_members: 200,
      traders: 250,
      employees: 40
    }
  },
];

bind it to the HTML:
<mat-card class="mat mr-4 ml-5 p-3" fxLayout="column" fxFlex>

      <ng-container *ngFor="let item of items">

    </ng-container>

  </mat-card>

this will apply specified theme to each card.
Here is a stackblitz example.


text:
Q: Allow debugger; statements in certain files, using ESLint Say I want to use this rule:
https://eslint.org/docs/rules/no-debugger
however, I have about 15 files where I want to keep debugger; statements.
Is there something I can add at the top of the .ts/.js files, that can tell ESLint to ignore the no-debugger rule for this particular file?

A: Probably your IDE can help. If you are using VS Code, you can mouse over debugger, click Quick Fix..., and select Disable no-debugger for the entire file, as shown as below:

Then the IDE will add the following comment at the top of the file to disable the rule for you:
/* eslint-disable no-debugger */

See more on the eslint no-debugger rule.

A: You can also disable ESLint in the same line:
debugger; // eslint-disable-line no-debugger

A: You can do that like this:
/* eslint-disable no-debugger */
... code that violates rule ...
/* eslint-enable no-debugger */

A: OR, add:
"no-debugger": false

to the bottom of tslint.json, to disable this warning for all files.

A: Update your eslint configuration file (.eslintrc etc) with such rule:
"rules": {
    "no-debugger":"off"
}

A: I think debugger need to removed, and briefly used in a development environment.
So you're better off ignoring it where you use.
For example:
disable no-debugger for this line
    // eslint-disable-next-line no-debugger
    debugger

or disable no-debugger for the entire file
/* eslint-disable no-debugger */


text:
Q: replace or push object in array using underscore I have one object with new data coming in and one array  with data that has been saved. If cnName from newData already exists in savedData in the cnData array then that object in savedData should be replaced with newData.cnData[0] object. If it does not exists then the data should to pushed to the cnData array in savedData
newData = {
  "cnGroupName": "cnGroupName1",
  "cnData": [{
    "cnName": "cn3",
    "data": {
       "color": "blue",
       "size": "42",
       "position": "right"
    }
  }]
}

savedData = [{
  "cnGroupName": "cnGroupName1",
  "cnData": [{
    "cnName": "cn1",
    "data": {
      "color": "red",
      "size": "42",
      "position": "right"
    }
  }, {
    "cnName": "cn2",
    "data": {
      "color": "blue",
      "size": "11",
      "position": "top"
    }
  }]
}]

I am using underscore
if(savedData.length){
    _.each(savedData, function(num, i){

        if(savedData[i].cnGroupName == newData.cnGroupName ){

            _.each(savedData[i].cnData, function(num, x){

               if(savedData[i].cnData[x].cnName == newData.cnData[0].cnName){

                    // the cnName already exists in savedData so replace
                    savedData[i].cnData[x] = newData.cnData[0]

               }else{
                    // the cnName  does NOT exist in savedData so push the new object to savedData
                   savedData[i].cnData.push(newData.cnData[0])
                }
            })
        }else{
            // the cnGroupName from newData is not in saveData so push newData
            savedData.push(newData)
        }
    })
}

the reason this does not work is because in the second _.each() statment. If the cnName does NOT exist in savedData it will push newData once for every object that is already in savedData. So if there are already 2 saved objects in savedData then the newData will be pushed 2 times
you can see the console logs in this plunker that the newData is being pushed twice
http://plnkr.co/edit/GkBoe0F65BCEYiFuig57?p=preview
My 2 questions are

*

*is there a cleaner way of doing this in underscore?

*is there a way to stop _.each() from continuing the loop ?

A: You can use findIndex to find the first matching index and update if not found.
if(savedData.length){
    var cnindex,
    index = _.findIndex(savedData, function (item) { return item.cnGroupName == newData.cnGroupName });
    if (index === -1)) {
        savedData.push(newData);
    } else {
        cnindex = _.findIndex(savedData[index].cnData, function (item) {return item.cnName == newData.cnData[0].cnName});
        if (cnindex === -1) {
            savedData[index].cnData.push(newData.cnData[0]);
        } else {
            savedData[index].cnData[cnindex] = newData.cnData[0];
        }
    }
}

Note: To stop a each iteration wrap in a try catch block and throw a custom error in the desired break point

A: Have you considered looping through newData.cnData on the second _.each?
if(savedData.length > 0){

    _.each(savedData, function(num, i){

        if(savedData[i].cnGroupName == newData.cnGroupName ){

            _.each(newData.cnData, function(num, x){
           // ^ change the subject here

               if(savedData[i].cnData[x].cnName == newData.cnData[0].cnName){

                    // the cnName already exists in savedData so replace
                    console.log("cn names are the same")
                    savedData[i].cnData[x] = newData.cnData[0]

               }else{
                    // the cnName  does NOT exist in savedData so push
                    console.log("cn names are diffrent")
                   savedData[i].cnData.push(newData.cnData[0])
                }
            })
        }else{
            // the cnGroupName from newData is not in saveData so push newData
            savedData.push(newData)
        }
    })
}


text:
Q: How to get Caller Name using twilio SMS Reply? When I buy the number I use
 var purchaseOptions = new PhoneNumberOptions();
    purchaseOptions.PhoneNumber = commandArgument;
    purchaseOptions.VoiceUrl = LeadsModuleDomainNamePublic.Trim() + "/ProcessCallTwilio.aspx";
    purchaseOptions.StatusCallback = LeadsModuleDomainNamePublic.Trim() + "/ProcessCall.aspx";
    purchaseOptions.SmsUrl = LeadsModuleDomainNamePublic.Trim() + "/TwilioReply.aspx";
    purchaseOptions.VoiceCallerIdLookup = true;

When I get number then use this code.
     foreach (string var in Request.Form)
    {
        if (var == "CallerName") { CallerName = Request[var]; }
    }

but its not give me caller name.

A: Twilio developer evangelist here.
By looking at your code I'm making the assumption you are using the C# Library correct?
And I'm thinking you're trying to get the caller name from a call you're receiving? If that's the case, when you receive a call, Twilio will pass a number of variables back to you which are related to that call. CallerName is not one of them.
An incoming call is modelled like this, and these are all the variables Twilio will pass when it makes a request to your server.
I think what you may be looking at is the CNAM Lookup on the Lookup API. With that, you can get the caller name information when it is available.
Hope this helps you

A: // This code work for me
// Download the twilio-csharp library from twilio.com/docs/libraries/csharp
    using System;
    using System.Collections.Generic;
    using Twilio;
    using Twilio.Rest.Lookups.V1;
    using Twilio.Types;

    public class Example
    {
        public static void Main(string[] args)
        {
            // Find your Account SID and Auth Token at twilio.com/console
            const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
            const string authToken = "your_auth_token";

            TwilioClient.Init(accountSid, authToken);

            var phoneNumber = PhoneNumberResource.Fetch(
                new PhoneNumber("+15108675309"),
                type: new List<string> { "caller-name" });

            Console.WriteLine(phoneNumber.CallerName["caller_name"]);
        }
    }


text:
Q: Oracle APEX - get workspace for current app I need workspace name of the current app to access RESTful API.
Is there any substitution string for this? Or what is easiest way to get workspace name of the current app?

A: You can use one of those for the ID:
Bind variable -> :WORKSPACE_ID
PL/SQL -> V('WORKSPACE_ID')
Substitution string -> &WORKSPACE_ID.
SYS_CONTEXT variable - > SELECT ... WHERE workspace_id = SYS_CONTEXT('APEX$SESSION', 'WORKSPACE_ID')

And to get the name:
select workspace from apex_workspaces where workspace_id = :WORKSPACE_ID

or
select workspace from apex_workspaces where workspace_id = SYS_CONTEXT('APEX$SESSION', 'WORKSPACE_ID')

A: select * from apex_applications

You need apex_administrator_role to obtain not only current schema applications.
...And if you are new you need to be aware of administration role implications.

A: select workspace
from apex_applications
where 1=1
  and application_id = :app_id

You don't need to apex_administrator_role as another answer suggests unless the parsing schema is not assigned to the current workspace.

A: We didn't find solution what is wrong with apex_applications, so we used workaround with apex_040200.wwv_flow_authorized which is working correctly for us.