text:
Q: WSO2 CEP Extension ML with Collaborative Filtering It's possibile to integrate a Collaborative Filtering Explicit Data model generated with WSO2 Machine Learner module? I want to query model with Siddhi, but in WSO2 docs i not found any way to do.

A: Yes it is possible to integrate machine learning models with WSO2 CEP and use Siddhi to get the predictions. Please use this guide.
Tishan

A: Not only collaborative filtering algorithm, any machine learning model you developed using WSO2 Machine Learning Server can be easily integrated with other products in the WSO2 echo system. For instance, you can integrate WSO2 ML models easily with WSO2 ESB using a special mediator called predict mediator [1]. Also, we have written an extension for the WSO2 CEP Server [2] as well. In addition to that, we are planning to add few more extensions in upcoming releases.
Sometimes, you might want to install machine learning models built using WSO2 ML Server outside of  the WSO2 echo system. For this purpose, we have provided two options namely Predictive Model Markup Language (PMML) and pure Java serialized object support.
[1]. https://docs.wso2.com/display/ML110/Predict+Mediator+for+WSO2+ESB
[2]. https://docs.wso2.com/display/ML110/WSO2+CEP+Extension+for+ML+Predictions

A: No. The current released versions of WSO2 Machine Learner (1.0.0 and 1.1.0) do not provide support for collaborative filtering as a CEP extension, therefore you cannot use collaborative filtering models created with Machine Learner with a Siddhi query.
At the moment, only models created for numerical prediction, classification, anomaly detection and deep learning can be used with a Siddhi query.


text:
Q: Does this solve 3SUM in O(N log(N)) time? Does this algorithm work as a solution for 3SUM in O(N log(N)) where the problem is defined by Wikipedia as

In computational complexity theory, the 3SUM problem asks if a given set of n real numbers contains three elements that sum to zero.

//Given an array of integers called list
//return true if 3 integers in list sum to 0, false otherwise

//quicksort the provided list
quickSort(list)

//add all elements of the list to a hashmap where the key is a number and the value is the number of times it occurs
hs = new hashMap<Integer, Integer>()
for(Integer i:list)
   if(hs.get(i)==null)
        hs.add(i, 1)
    else
        hs.add(i, hs.get(i)+1)

//create a pair of pointers pointing to the left of right of the center of array
startIndex=0
while (list[startIndex]<0 and startIndex<list.length-1)
startIndex++

left=startIndex
right=startIndex+1

//run this loop while pointers are in boundaries of array
while(! (left<0 or right>=list.length)
{
    //see if a 3rd number that can be added to the numbers at left
    //and right to make 0 can be found
    sum=list[left] + list[right]
    negsum= -(sum)
    //if it's found enter these if statements
    if(hs.get(negsum)!=null)
    {
        //check for the possibility that the 3rd number is one of the 1st 2, if not return true
       if(negsum==list[left] or negsum== list[right])
       {
        //if the 3rd number is one of the 1st 2 make sure that a duplicate of it exists, or if all 3 are 0, that 3 zeros exist
        //if we have enough duplicates, return true
            if(list[left]==list[right] )
                if(list.hasMoreThanTwo(negsum))
                    return true
            else if(list.hasMoreThanOne(negsum))
                return true
       }
       else
           return true
    }

    //if a trio cannot be formed with the numbers at left and right, adjust the pointers so that we will get closer to 0 and try again.
    if (sum<0)
        right++
    else
        left--
}

//if pointers go out of bounds 3 numbers that sum to 0 don't exist
return false

A: Your code doesn't handle this case:
[-10, -7, 0, 0, 4, 6].
In this case, the right pointer would go out of bounds because the left pointer would be at -10, which is too big.
So if something is really negative, your algorithm will try to look for a positive solution, and ultimately fail.

A: If I understand the algorithm -- which you didn't explain at a high level -- it won't work.  It appears that the approach is to work from the least-magnitude positive (right) and negative (left) numbers.  For each pair, you look for a third number to make 0.  Then you move one boundary to the next larger number, keeping the 2-number sum close to 0.
The problem is that you're not at all guaranteed of the triple containing one number relatively near to 0.  For instance, something like
[-5100, -1700, -1600, -1000, , 2500, 2600, 5000]
Will see you skip left past -1600 to -1700 before you get right to 2600 to find the solution.

A: As has been stated, your code doesn't involve all the possible combinations. Here, I will go over a test case in which your code fails to consider all possibilities.
We have the following array:
[101, 100, 100, 0, -50, -199, -200]

For ease of use, it has already been sorted. This is converted to:
{101: (1, 0), 100:(2, 1), 0:(1, 2), -50:(1, 3), -199:(1, 4), -200:(1, 5)}
[101, 100, 0, -50, -199, -200]

We start off at the center of the value, in this case 0 and -50.
On the first iteration, we can see that nothing matches, and so we move the left since that would result in a closer approximation. (0 + -199 vs 100 + -50)
The next iteration, we move to the right. (100 + -199 vs 101 + -50)
The iteration after, we move to the right again, since this is closer to 0. (101 + -199 vs 100 + -200)
As you may have noticed, we've just skipped past the pairing of 100 and -200, which is the relevant pair in the triplet (100, 100, -200) in this case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reading and Writing to documents or other files in Google Drive using gnome account So I added my Google Drive using gnome-online accounts in ubuntu 20.04.2 LTS Now if I make changes to the directory (e.g add a new file or remove it etc.) it syncs fine.
But whenever, I try to open a document(eg.a pdf file), the default Document Viewer tries to download it first and then let me read/edit it. When done, I have to upload it again to get it synced!  I tried using Okular but it simply can't open it.
Is there any way to seamlessly open and edit files (for my case I need to edit some pdf files and docs) in Google Drive as can be done in Windows (using it just as a regular folder)?
Thanks.


text:
Q: REPLACE INTO table in mysql query optimization I have below query which is taking nearly 70min for the completion.
The record counts of tables:

*

*demo.HIST_MARKETING_COMM_DISCREPANCIES -- ~400K  Records

*demo.VW_2AND3_LETTER_COUNTRY_DETAILS  -- 260  Records

*DG_ORG_DETAILS_DIM -- 20  Records
My MySQL server config:  2 vCPUs, 6GB RAM, 300GB Disk size
replace into demo.mt_mkt_comm_base_tbl
SELECT c.org_id
     , c.org_name
     , IFNULL(GETINITCAP(hcd.cntry_name), a.prmry_reside_country_code) country_name
     , a.*
  FROM demo.hist_marketing_comm_discrepancies a
  LEFT
  JOIN demo.vw_2and3_letter_country_details hcd
    ON hcd.cntry_code2 = a.prmry_reside_country_code
  LEFT
  JOIN demo.dg_org_details_dim c
    ON a.org_id = c.org_id
 WHERE a.active_flag = 'y'
   AND a.breach_indicator IS NOT NULL

Explain plan for the above:

Seeking some help to improve the performance of query, i'm even fine to scale my server configuration also.
I have used index as below

*

*A composite Index on ( ACTIVE_FLAG, BREACH_INDICATOR, MAIL_DATE) in hist_marketing_comm_discrepancies, Even MAIL_DATE is removed also same composite index is being used, so kept it.
KEY idx_composite_key (ACTIVE_FLAG,BREACH_INDICATOR,MAIL_DATE)

*Index on CNTRY_CODE2

*Index on ORG_ID
Now the explain plan is as below

And query is giving the result ~20min, is there anyway query execution time further can be reduced.
I have resized innodb_buffer_pool_size,
Before modification it was 108M, I have modified that to 3000M, Now the entire replace query completes in ~2min.
To change the setting is done in the [mysqld] section of the my.cnf file. And you must restart mysqld to get it to take effect. (in ubuntu you can locate my.cnf file in /etc folder)

A: make sure all these fields are indexed:
cntry_code2
prmry_reside_country_code
org_id
breach_indicator
active_flag
it will reduce the cardinality of your problem.
remove the IFNULL and filter your query afterward.
for sure scaling your server would help but your config and amount of data you have shouldn't be this slow.

A: Let's back up a step.  What is the purpose of this REPLACE?  How much of the table is being replaced?
If it is practical to build a fresh copy of the table, then 'swap' it into place, that is likely to be much faster.  (Cf RENAME TABLE; I can discuss further if needed.)
If it is practical to do the "replacing" piecemeal, then that could be much less invasive.  (See techniques in http://mysql.rjweb.org/doc.php/deletebig#deleting_in_chunks )
Please note that REPLACE is implemented as DELETE + INSERT.  As such, you destroy auto_inc values, and work harder than with IODKU, so...
If you stick with REPLACE .. SELECT .., then consider changing to INSERT INTO t .. ON DUPLICATE KEY UPDATE ...  It is likely to be faster.
http://mysql.rjweb.org/doc.php/deletebig#optimal_reload_of_a_table discusses both the full table replacement and the use of RENAME TABLE.
Indexes
These may help some:
a:  (active_flag, breach_indicator, org_id, prmry_reside_country_code)
c:  (org_id, org_name)
hcd:  (cntry_code2, cntry_name)


text:
Q: Python Tkinter IntVar Not Updating I have two functions that are part of a Python 3.4.1 Tkinter GUI.
def jumpto():
    global jump
    jump = Tk()
    jump.wm_title("Jump")
    jump.focus_force()
    label = Label(jump, text = "Enter digit to jump:").pack()
    global jumptext
    jumptext = IntVar()
    jumpentry = Entry(jump, textvariable = jumptext)
    jumpentry.pack()
    jump.bind("<Return>", close)

def close(self):
    global jumptext
    global jump
    print(jumptext.get())
    while digit < jumptext.get(): #digit is an integer that increases in the unrelated area below
        #Do something completely unrelated
    jump.destroy()

jButton = Button(master, text = "JUMP", command = jumpto).pack() #master is the main Tk window

However, when I run the code, jumptext.get() within close remains 0, despite something being typed in to the entry box created with jumpentry. Any way to make it so that the information entered actually updates to jumptext.get()?
Also, if anyone could explain to me why self must be entered within close, that would be a bonus.
Thanks in advance!

A: The thing is that you're making two instances of Tk(), which leads to strange behavior. The jump window should be a Toplevel window, which is the window to use if you want another window next to your Tk() window.
close needs to accept an argument because it is called by a bind which always passes an event object which contains all kinds of information about the event that triggered the close function (things like mouse position and the key that was used to trigger the event). So calling it event instead of self would actually be more correct. self is a variable used in classes which contains class attributes.


text:
Q: Finding the values of $Q$ from $180^{\circ}$ to $360^{\circ}$ I have $\cos{Q}=-0.5$, required to find $180^{\circ}\leq Q\leq 360^{\circ}$.
What I tried: The acute angle is $60^{\circ}$, then, since cosine is negative on third quadrant, I suppose the value is $180^{\circ}+60^{\circ}=240^{\circ}$. Am I right?

A: You are correct.  There are two values within a circle that have a given cosine (except -1,0,1).  For $\cos Q=0.5$, these are $150^\circ$ and $240^\circ$ and you have found the right one.


text:
Q: Java servlet - export to an excell using string buffer I am new to JAVA. I am trying to export Excel through servlet from resultset.
When i am trying to store data in String buffer the it is not actually saving it.
Testfirst.java
String assingee_name = req.getParameter("firstName");
String track_name = req.getParameter("track");
String sla_id = req.getParameter("sla");
StringBuffer sb = new StringBuffer();

try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con = DriverManager.getConnection("jdbc:odbc:Databasethree");
    stmt = con.createStatement();

    //pw.println("'" +assingee_name + "'");
    length = track_name.length();

    if (length > 0) {
        rs = stmt.executeQuery("SELECT* FROM casedetails where track =" + "'" + track_name + "'");
    }

    length = sla_id.length();
    if (length > 0) {
        //rs = stmt.executeQuery("SELECT* FROM casedetails where case_age >"+"'" +sla_id + "'");
        rs = stmt.executeQuery("SELECT* FROM cdoscase where Incident_Submit_Fiscal_Year=" + "'" + sla_id + "'");
    }

    length = assingee_name.length();
    if (length > 0) {
        rs = stmt.executeQuery("SELECT* FROM casedetails where Assingee_name =" + "'" + assingee_name + "'");
    }
    pw.println("");

    pw.println("
 CDOS Case Management Version 1.1
");

    pw.println("");
    pw.println("
");

    ResultSetMetaData rm = rs.getMetaData();
    int clm = rm.getColumnCount();
    StringBuffer sb1 = new StringBuffer();
    String sb2 = new String();

    for (int j = 1; j <= clm; j++) {
        sb2 = rm.getColumnName(j);
        pw.println("");
        pw.println(sb2);
        pw.println("	");
    }

    ArrayList Rows = new ArrayList();
    ArrayList row = new ArrayList();
    Object a = new Object();
    int jj = 0;  // to find out the number rows

    while (rs.next()) {
        jj = jj + 1;

        pw.println("
");

        for (int i = 1; i <= clm; i++) {
            //data1[i]=rs.getString(i);
            pw.println("");
            //pw.println(rs.getObject(i).toString());
            pw.println(rs.getString(i));
            pw.println("	");
            sb2.append(rs.getString(i);
            //row.add(rs.getString(i));
            //sb2=sb2+rs.getObject(i).toString();
        }

        pw.println("
");

    } sb1.append("fd");
    //Rows.add(row);
    pw.println("Total Records found" + sb1);
    pw.println("
");

    //sb2=sb2+rs.getObject(clm).toString();
    //sb1.append(sb2);
    //sb1.append(sb2);
    a = rs.getString(4).toString();
    pw.println("this is data " + a);
    pw.println("
");
    pw.println("Do you want to download report 	");
    req.setAttribute("data", Rows);
    pw.println("<input type=\"submit\" name =\"submit1\" value=\"Export To Excel\">");
    pw.println("</form>");
} catch (SQLException e) {
    pw.println(e.getNextException());
} catch (ClassNotFoundException e) {
    pw.println(e.getException());
} finally {
    try {
        if (rs != null) {
            rs.close();

            rs = null;
        }
        if (stmt != null) {

            stmt.close();
            stmt = null;
        }
        if (con != null) {

            con.close();
            con = null;
        }
    } catch (Exception e) {
        pw.close();
    }
}

}
Any help on this is highly appreciated.
Thanks,
SR


text:
Q: Cannot Initialise Variable for type Unsafepointer Swift 3.0 conversion Hi I am converting existing swift 2.0 code to swift 3.0 but came across an error  while conversion:

Cannot invoke initializer for type 'UnsafePointer' with an argument list of type '(UnsafeRawPointer)'

Here is my code:
extension Data {

  var hexString : String {
    let buf = UnsafePointer<UInt8>(bytes) // here is the error
    let charA = UInt8(UnicodeScalar("a").value)
    let char0 = UInt8(UnicodeScalar("0").value)

    func itoh(_ i: UInt8) -> UInt8 {
        return (i > 9) ? (charA + i - 10) : (char0 + i)
    }

    let p = UnsafeMutablePointer<UInt8>.allocate(capacity: count * 2)

    for i in 0..<count {
        p[i*2] = itoh((buf[i] >> 4) & 0xF)
        p[i*2+1] = itoh(buf[i] & 0xF)
    }

    return NSString(bytesNoCopy: p, length: count*2, encoding: String.Encoding.utf8.rawValue, freeWhenDone: true)! as String
 }
}

A: In Swift 3 you have to use withUnsafeBytes() to access the raw bytes of a Data value. In your case:
withUnsafeBytes { (buf: UnsafePointer<UInt8>) in
    for i in 0..<count {
        p[i*2] = itoh((buf[i] >> 4) & 0xF)
        p[i*2+1] = itoh(buf[i] & 0xF)
    }
}

Alternatively, use the fact that Data is a collection of bytes:
for (i, byte) in self.enumerated() {
    p[i*2] = itoh((byte >> 4) & 0xF)
    p[i*2+1] = itoh(byte & 0xF)
}

Note that there is another problem in your code:
NSString(..., freeWhenDone: true)

uses free() to release the memory, which means that it must be
allocated with malloc().
Other (shorter, but potentially less efficient) methods to create
a hex representation of a Data value can be found at
How to convert Data to hex string in swift.


text:
Q: How do I prove this $I_x$ is an interval?
Every non-empty open set of the real line is the union of a countable
  disjoint class of open intervals.

Proof. Let $G$ be a non-empty open set of the real line. Let $x\in G$ which implies there is an open interval centred at x which completely sit inside $G$. Let $I_x=\bigcup_{x\in C\subset G \\\text{$C$ is an open interval}}C.$ We know that the arbitrary union of open subset is open. Hence, we have $I_x$ is open.

How do I prove this $I_x$ is an interval?

In order to prove $I_x$ is an interval, we need to show any $a,b\in I_x$, the closed interval $[a,b]\subset I_x.$ Any $a,b\in I_x \implies a \in$ some open interval centered $x$ and contained in $G$($G_a$(say)), also $b\in$ some other open interval centered at $x$ and contained in $G$($G_b$(say)). How do I prove $[a,b]\subset I_x$ with the help of elementary real analysis with out using the aid of topology? Please help me.

A: What you want to prove is that if $x\in\mathbb R$ and if you have a family $\mathscr F$ of intervals such that $x$ belongs to each element of $\mathscr F$, then the union $U$ of all elements of $\mathscr F$ is also an interval. Take $a,b\in U$ with $a\leqslant b$ and take $y\in\mathbb R$ such that $a\leqslant y\leqslant b$; you want to prove that $y\in U$ too. There are $3$ possibilites:

*

*$a\leqslant b\leqslant x$: then some element $I\in\mathscr F$ is such that $a\in I$. But $I$ is an interval and $x\in I$. So, $y\in I$.

*$a\leqslant x\leqslant b$: then there are elements $I,J\in\mathscr F$ such that $a\in I$ and $b\in J$. Since $I\cup J$ is an interval (because $x$ belongs to both of them), $y\in I\cup J$.

*$x\leqslant \leqslant b$: it's like the first case.

It follows that $y\in U$.

A: Let $u,z \in I_x$. Then there exist open intervals $C,D$ such that $C,D \subset G$, $u\in C$ and $z \in D$. The union $C \cup D$ is an open interval because $x$ belongs to both $C$ and $D$. Also, $C \cup D \subset G$. If $u<y<z$ then $y \in C \cup D$ and it follows from definition that $y \in I_x$. Hence $I_x$ is an interval.


text:
Q: Unreal conditional inversion with "Should" Unreal conditional sentences with Past Perfect, Were and Should may suffer inversion to show more formality. "Past Perfect" and "Were" exist in the original regular Unreal Conditional but how does "Should" work? Where does it come from? From another S.Past verb different from "were"?
Is it correct, for ex? "If he knew it, he would tell me".
       INVERSION.....Should he know it, he would tell me.

A: Should you like the movie, we can go to another one.
Should here means: in the event you like the movie. It is semantically equal to: if you like the movie. It is just a bit more formal.  Should they come by, we'll tell them the story. Should the trade partners agree to the treaty, their respective legislatures will sign it. It is used in written form most often than in speech.

A: Subject-auxiliary inversion to express a conditional works exactly the same way as subject-auxiliary inversion to express a question: you simply move the auxiliary in front of the subject and drop the if:

If he should come tomorrow, we will of course welcome him.
  ↓
  Should he come tomorrow, we will of course welcome him.
If he were coming he would surely inform us.
  ↓
  Were he coming he would surely inform us.
If I had known you were coming I would have rearranged my schedule.
  ↓
  Had I known you were coming I would have rearranged my schedule.

In Present-day English, however, this sort of conditional construction is restricted to a handful of past-form auxiliaries—were (uninflected for person or number), had and should—and even these constructions have a very formal, old-fashioned ring today.
Note that these inverted constructions do not necessarily express "unreality":

*

*Should and were conditionals may express unreality but more often express non-reaiity: a hypothetical condition or an 'open' condition, a contingency which has not yet been realized but may be in the future.

*

*Should conditionals are usually open, and the verb heading the following  consequence clause will usually have future reference: either a will future, as in the example above or a modal in either non-past or past form understood in a non-past sense:

Should he come tomorrow we can let him use John's office.
  Should he come tomorrow we could let him use John's office.

Would in the consequence clause is possible, but unlikely.

*

*The verb heading a consequence clause introduced by were conditionals may express counterfactuality but more often express an open condition regarded as possible but unlikely; in either case a past form is required in the consequence clause:

Were he to come tomorrow we would let him use John's office.

*Had conditionals, however, usually do express counterfactuality. The perfect construction in the condition clause indicates a past contingency, and the "conditionality" of the construction implies that the contingency was not in fact realized, since if it were realized there would be no "if" involved.


text:
Q: There is an image embedded on my page that I can't locate in order to delete. Please help me! This is what the page looks like on the site (once published):

This is what it looks like when I go to edit the page. The image isn't there (it's positioned above the text you'll see here) and can't be selected or deleted, and I can't find it through any other means:

A: That's the featured image for that page.  If you look at your page editor, to the right you have Permalink, Featured Image, Discussion, Page Attributes, and Hide Title?
You want to expand the 'Featured Image' one and click 'Remove'.
What you've done is assign what I assume is your logo as the featured image to your page and the theme then places it immediately at the top of the entry content.


text:
Q: Is there a way to remove or replace njada's hide helmet in Skyrim without mods? I want her to wear a circlet or some headset that doesn't hide her hair. Is there a way to do this though the console without installing a mod? I tried to remove the helmet through the console, but it only works temporarily as the hide helmet gets respawn after you leave her.

A: I tried this myself and it worked for me:

*

*Open the console, click on the NPC

*type 'openactorcontainer 1' and put the cloth you want to equip from your inventory in there

*type 'showinventory', there should be a list of items the npc has. Try to find the ID of the item you want to remove,
a line could look like this:
Boots (001b1be) (100,100.00%) - Worn - Outfit
in this case, '001b1be' is the id of the item

*type 'removeitem [ITEM ID] 1, in this case: removeitem 001b1be 1

*now search for the item id of the item you want to equip and type:
'equipitem [ITEM ID] #', e.g.: equipitem 001b1be 1
the 1 behind the ID means that the outfit cannot be removed
If the default outfit should be reequiped for whatever reason and its not permanently, you could create a textfile inside your skyrim installation folder and write in it:
prid [follow id]
equipitem [item id] 1

save it and type ingame: 'bat [name of the txt file]' whenever you want to overwrite the npcs default outfit. As far as i know, thats all you can do without using mods, but i hope this helps.


text:
Q: $asyncValidators Angular I am using Angular 1.3.* and I try to validate my form. It is within a ng-repeat. So I may obtain several input fields. I do not only require the field to be not empty, but also require the search to be successful when retrieving information from the backend.
I have this input field
                               <input type="text"
                               ng-model="user"
                               placeholder="username"
                               name="user{{$index}}"
                               typeahead="data as data.name for data in getUser($viewValue)"
                               typeahead-editable="false"
                               class="form-control"
                               autocomplete="off"
                               userValidator
                               required>

You need to type something

 It seems that the entered user is           not a valid input

here is my try for the backendCall
  .directive('userValidator',function($http,$q){
    return{
      require:'ngModel',
      link:function($scope,element,attrs,ngModel){
        ngModel.$asyncValidators.userAvailable=function(userInput){
          return $http.post('/user'+userInput)
            .then(function)????

        }
      }
    }
  });

Note, that I WANT the user to exist. I guess I'll have to make a backend call with asyncValidators. However, I do not seem to get it. A way for me to circumvent this would be to say that on ALL other $errors than "required", show the message "It seems that the entered user is not a valid input". How could I do a successful backend call and use it or alternatively, how can I make sure to show the other error message on all other occasions?

A: If the username exists then simply return true, if it does not exists simply reject with the message
.directive('userValidator',function($http,$q){
return{
  require:'ngModel',
  link:function($scope,element,attrs,ngModel){
    ngModel.$asyncValidators.userAvailable = function(modelValue , viewValue) {

     var userInput= modelValue || viewValue;
      return $http.post('/user'+userInput)
         .then(function() {
           //username exists, this means validation success
           return true;
         }, function() {
           //username does not exist, therefore this validation fails
           return $q.reject('selected username does not exists');
         });

      }
    }
  }
});

A: A Firebase example:
.directive('isAccountNameAvailable',[ 'FireRef', '$q', function( FireRef, $q){

return {
  require:'ngModel',
  scope:{
    profile:'=profile'
  },
  link:function($scope, element, attrs, ngModel){
    ngModel.$asyncValidators.isAccountNameAvailable = function(modelValue , viewValue) {
      var deferred  = $q.defer();

      var userInput = modelValue || viewValue;

      $q.all([
          FireRef.child('accountNames').child(userInput).once('value'),
          FireRef.child('users').child($scope.profile.$id).child('accountName').once('value')
        ])
        .then(function(snapshots){

          /*
           snapshots[0].val() is userID in accountNames path e.g accountNames/londonServicesLTD/userID
           snapshots[0].key() is accountName key in accountNames e.g accountNames/londonServicesLTD

           snapshots[1].val() is the current accountName value in user/userID/accountName e.g londonServicesLTD
           snapshots[1].key() is 'accountName' key in user/userID/
          */

          if(!snapshots[0].exists()){
            deferred.resolve(true);
          }else if(snapshots[0].val() === $scope.profile.$id){
            deferred.resolve(true);
          }else{
            deferred.reject(false);
          }

        },function(){
          deferred.reject(false);
        });

      return deferred.promise;
    }
  }
}

}])

html:

    Account Name
    <input type="text" name="accountName" ng-model="model.accountName" required ng-trim no-special-chars camel-case is-account-name-available profile="profile" class="form-control" placeholder="E.g. londonServicesLTD">

        - The account name is required.

        - Not allowed to use special characters.

        - The account name is not available.


text:
Q: Which type of relay is best to switch a signal to a voltmeter? In my system I want to measure multiple DC voltages with a single multimeter. I'm thinking of using relays to switch between the different signals.
But relays specifications tend to indicate, that I actually can't use them for this purpose.
One of my signals is from a high precision current shunt (Vishay  HZ series) with an expected signal range of 550 mV to around 4.3 V. The others are in the range of 0 to 10 V.
I'm not too concerned with the switching capacity of the relays. It's used in a production equipment and can be replaced on a regular basis; I expect around 20000 switch overs per year.
My research:
Solid State Relay
Solid state relays usually have a minimal output voltage specification, which is higher than 550 mV. So it can't be used for the current shunt and for the 0 to 3 V range of the signals.
Furthermore, they typically have leakage current specification which would defeat the whole purpose of the high precision current shunt (leakage > 1 µA).

Standard electromechanical relay
The problem with standard electromechanical relays is the requirement of minimal load current. To get anywhere near the load of a voltmeter (1 µA at 10 V, or even less if switched to >10 M\$\Omega\$) I need gold-plated contacts.
But even gold-plated contacts are rated for a minimal load current in the order of 1 mA at 24 V.

Reed relay
In most of the datasheets I haven't found a mention of a minimal required load current or voltage specification.
I'm not sure if that means that it doesn't matter (because of the sealed enclosure there is no oxide build up?), or that the manufacturers don't care.

Currently I'm leaning towards reed relays, but I'm not sure if I'm missing something.

A: At least some conventional relays seem to have very low contact currents.  For example, I see that Kemet EA2/EB2 series has a contact current of 10 uA.  Any good?
Datasheet

A: Put a capacitor and a small series resistor in parallel with the meter's inputs. Then when you switch, the capacitor will draw a small surge current and keep the contact clean.
0.1 uF and 10-100 Ω should work depending on your operating range.
Be careful that when switching from a high input V back to a sensitive circuit that the now-charged capcitor doesn't overdrive the sensitive circuit.
Also ensure that you have a delay between opening one pair of switches and closing the next - some relays may take longer to open than close, so you might briefly short two signals together

A: After the helpful recommendation from @jonathanjo I did some further research concerning electromechanical relays.
From my findings I'd conclude the following for switching low current signals:

*

*Use a relay with gold plating, sometimes also called gold clad. Be sure that it is a thick gold layer. Gold layers of 0.2 µm are only to prevent the contacts from corroding during storage. A thin layer will wear off or easily evaporate if an arc occurs. I found relays with up to 10 µm gold, which shouldn't wear off as fast.

*Look for bifurcated contacts. Basically, this means that for each contactor there are two contact points, which make for a more reliable connection.

*Use more than one contact in parallel. According to Finder this will decrease the minimum switching load and increase the reliability. Sadly, I haven't found a second source for this claim and I'm not sure if this scales downward into µA range.
I have found one relay for rail applications, which is specified down to 1 µV and 1 µA (Mors Smitt D-E).
For my application it makes life much easier as it is mountable on a DIN rail.
I have asked one of the biggest companies for reed relays, but there are none which could be mounted on a DIN rail directly or with a socket. Otherwise, they would be a very good fit for this application.

A: For measuring voltage, something like the Toshiba TLP3317 solid state relay is a good choice for voltage measurement.

*

*It has an on resistance of 7~12 ohms.  If the meter has high input resistance (like > 10M ohms) then it shouldn't be adding more than 1 ppm error.

*It's recommended for use up to 64V.

*It has a leakage current rating of only 20pA at 80V.  Proportionally lower leakage at lower voltages.

*Solid state, so no minimum switching current or cycle limit.

*No minimum switching voltage.

*Both AC and DC voltages can be measured.

Omron also makes similar relays.
Also, if you are only measuring up to 10V, manufacturers like Analog Devices make analog MUX chips that could be used.


text:
Q: How to know collection view's `referenceSizeForHeaderInSection` method call has finished? I have a viewController with a UICollectionView, to which I'm setting headers I need their height to be calculated dynamically. My implementation of the collectionView(_:layout:referenceSizeForHeaderInSection:) is similar to this:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    let width = collectionView.frame.size.width
    customHeader.layoutIfNeeded()
    let height = customHeader.container.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height

    return CGSize(width: width, height: height)
}

I'd need to know when this call has been completed and the size of the headers have been set, in order to trigger some other actions I need to perform.
I've seen that both viewDidLoad() and viewDidLayoutSubviews() methods of the viewController are called before this other one. Is there any way to achieve what I need?


text:
Q: EXCEL - Nested Ranges for references thanks for reading my question.
I'm trying to find price points for various sizes of product packages. I have a data range on Sheet1, A1:Z102, with the top row as mass of the packages (B1:Z1), and the first column (A2:A102) as the selling price. In the array I've calculated the profit margins (B2:Z102)
I'm trying to set up "what-if" automatically on a sheet that allows me to enter various weights "Sheet2!B1:B10" -- that will select the corresponding column of package weights from "Sheet1!A2:Z2", then have the function MATCH the closest row of that column to my "what-if" profit margin "Sheet2!A1", and finally return on Sheet2, C1:C10, the selling price that is closest to that profit margin.
SHEET1
       1lbs    2lbs    3lbs    4lbs
$1     $0.10  -$0.80  -$1.80% -$2.80
$2     $1.74   $0.74  -$0.26  -$1.26
$3     $2.61   $1.61   $0.61  -$0.39
$4     ...     ...     ...     $0.47
...

SHEET2
$0.20  2lbs    X
       4lbs    X

[Edit1] So the function would return C1=$2, and C2=$4 in three iterative steps (I think).

*

*Cell.Sheet2!B1.Value matched to identical column in Sheet1 Row1: Returns Column Y

*For Column Y in Sheet1, find value closest positive value to Cell.Sheet2A1: Returns Column Y, Row Z

*For Sheet1 Column Y, Row Z return value in Sheet1 Column 1 Row Z. repeat that value in C1 Sheet2

*Repeat 1-3 for B2...Bn

I'm having a hard time solving each step:

*

*MATCH can identify correct column

*Can't figure out how to nest MATCH in "OFFSET" to search only Column Y. I've tried INDEX MATCH, INDEX MATCH MATCH, LOOKUPs(V&H).

*Return Column1 value in RowZ.

I'm realizing this might be a Macro solution, but I just don't know how to VBA it:
Dim profit, lbs, cost, reflbs, refprofit As Range

Set cost = Worksheets("Sheet1").Range("$A$2", "$A$5")
Set profit = Worksheets("Sheet1").Range("$B$2", "$E$5")
Set lbs = Worksheets("Sheet1").Range("$B$1", "$E$1")
Set reflbs = Worksheets("Sheet2").Range("$B1")
Set refprofit = Worksheets("zTest").Range("$H$39")

For Each profitCell In profit
    For Each costCell In cost
        For Each lbsCell In lbs
            If lbsCell.Value = reflbsCell.Value Then

Then I'm not sure how to direct a search in the column whose header lbs matches "reflbs", and then I'd put in a:
If profitCell.Value = refprofitCell.Value Then

Then return the Row Z for the match, then ultimately return Row Z, Column A Sheet1! in Sheet2!C1.
Thanks a bunch!

A: Assuming your source data is laid out like your example as follows:

Then on sheet2 if your data is laid out as follows:

Then you can use the following formula to to get the numbers in red:
=INDEX(Sheet1!$B$2:$E$5,IFERROR(MATCH(Sheet2!$A$1,Sheet1!$A$2:$A$5,1),1),MATCH(Sheet2!$B1,Sheet1!$B$1:$E$1,0))

When the dollar value you are looking for is less than the first value in your column, you were probably getting an error.  The way vlookup and match work is that they do not look for the nearest number value.  They look for the the last number that was less then what they were looking for.  That is the reason why your column needs to be sorted in ascending order.  In order to deal with a legitimate value that is less than the first value in the list, the match function that will throw the error is wrapped in an iferror function that returns 1 to represent the first row.  Note that if an invalid entry for price is entered in sheet2!A1, it will still return 1 for the first row.
For your weights, they are actually string values most likely and not numbers.  Its quite common to have your units listed in a separate cell and then just the value in a cell of its own to make working with the values easier.  In this case I assumed your weight would always be an exact match for one of your column headers.  a weight of 2.5lbs would throw an error as it is not found in your header list.


text:
Q: Flask-Login:Where user_loader callback should be defined? I am new to python coding but straightaway started experimenting with flask. I am having trouble with flask-login extension
Here I am making a simple application which is a blog. This blog is going to be used by one person only.
I cannot understand why the user_loader decorator not working which is defined in models.py. I get exception the application NoneType object is not callable.
My app structure is like this
.
|-- app
|   |-- admin
|   |   |-- __init__.py
|   |   |-- static
|   |   |-- templates
|   |   `-- views.py
|   |-- config.py
|   |-- __init__.py
|   |-- main
|   |   |-- __init__.py
|   |   |-- static
|   |   |-- templates
|   |   `-- views.py
|   `-- models.py
`-- launch.py

app.init
from flask import Flask
from main import main
from admin import admin
from flask.ext.script import Manager
from .config import config
from flask_debugtoolbar import DebugToolbarExtension
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import Column
from flask_bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.login import LoginManager

app_myblog=Flask(__name__)
app_myblog.debug=True
app_myblog.config.from_object(config)
app_myblog.register_blueprint(main)
app_myblog.register_blueprint(admin,url_prefix="/admin"
toolbar=DebugToolbarExtension(app_myblog)
manager=Manager(app_myblog)
db=SQLAlchemy(app_myblog)
Bootstrap(app_myblog)
moment=Moment(app_myblog)

login_manager=LoginManager()
login_manager.init_app(app_myblog)
login_manager.session_protection='strong'
login_manager.login_view='admin.login'

In app.models I have defined User class which does not load users from database. In fact it simply loads user from configuration. In same file I have also defined user_loader callback
class User(UserMixin):
    def __init__(self):
        self.id='1'
        self.name=app_myblog.config['USERNAME']
        self.password=app_myblog.config['PASSWORD']

    def get_id(self):
        return unicode(id)

@login_manager.user_loader
def load_user(userid):
    u=User()
    if u.get_id()==userid:
        return u
    else:
        return None

admin.init
from flask import Blueprint

admin=Blueprint('admin',__name__,template_folder='templates',static_folder='static')
from . import views

admin.views
from flask import render_template,request,redirect,url_for
from . import admin
from flask.ext.login import login_required,login_user
from flask_wtf.form import Form
from wtforms import StringField,PasswordField,SubmitField
from ..models import User

class LoginForm(Form):
    username=StringField('Username')
    password=PasswordField('Password')
    submit=SubmitField('Login')

@admin.route('/')
@login_required
def index():
    return render_template('admin_home.html')

@admin.route('/login',methods=['GET','POST'])
def login():
    form=LoginForm()
    if form.validate_on_submit():
        login_user(User())
        nextx = request.args.get('next')
        return redirect(nextx or url_for('admin.index'))
    return render_template('admin_login.html',form=form)

Whenever i run the routes which have login_required i get the error
TypeError: 'NoneType' object is not callable. Here is the traceback.
Traceback (most recent call last):
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request
    return view_func(**req.view_args)
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_login.py", line 756, in decorated_view
    elif not current_user.is_authenticated():
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
    return self.__local()
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_login.py", line 46, in <lambda>
    current_user = LocalProxy(lambda: _get_user())
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_login.py", line 794, in _get_user
    current_app.login_manager._load_user()
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_login.py", line 363, in _load_user
    return self.reload_user()
  File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_login.py", line 325, in reload_user
    user = self.user_callback(user_id)
TypeError: 'NoneType' object is not callable

A: Edit:
I created a minimal example of your code and the the difference was that I removed the get_id(self) function (+ some extra libraries that isn't needed), beacuse it's part of the UserMixin class that you inherit.
Are you sure your form is getting validated? Can you describe how you test this step by step? I mean, "go to login.html" -> "enter credentials" -> etc
Make sure which call is causing the crash, is it the redirect inside your login function?

A: You should define the method in the same place you instantiate the login manager.
ala
login = LoginManager
@login.user_loader
def load_user(id/email):
    #your logic here

Or import your loginmanager instance from your module and define in your views.


text:
Q: Sendgrid unhandled error which is persisting in newly created accounts I have made a contact form where the user can send a message to the admin.
Use has to provide a message for which I have a text are and then he has to provide his email id and his name.
After clicking on sending the admin should receive a message.
I used SendGrid recent API and it does require some changes but I don't want to give a single sender manually.
I want anyone who comes to my site should be able to communicate with me via the contact form.
Probably, the normal contact form which we all know.
I checked in console log and it gives an error like
{
    errors: [{
        message: 'The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity
        requirements ',
        field: 'from',
        help: null
    }]
}

This tells that the user input value is not a verified address, I can use a single sender and make it work but I don't want such manual workings.
Instead, everybody should be able to contact me and I don't need to add them manually on my SendGrid.


text: Q: I deleted my Google App script by accident, can I restore it? I deleted all project in Google App script, I don't know how to restore, it took me more than a month to write it. Is there any way to restore it?


text:
Q: Redis - keys disappear Is it possible to disappear keys in Redis without reason? I'm adding keys to redis:
Transaction transaction = jedis.multi();
transaction.incrBy(positionsQuantityKey, positionQuantity);
transaction.expire(positionsQuantityKey, 24 * 3600);
transaction.exec();

but after few minutes I ran command:
jedis.keys("*");

and the key disappeared. What could delete this key? I'm sure that expire time was succesfully set, because result of this command was 1.
I'm using redis 2.6

A: If you're not doing anything else with Redis during that time, open a MONITOR session with redis-cli and look what goes on - another process could be deleting your key.
Alternatively, perhaps you're running low on RAM and Redis' eviction policy is configured to evict volatile keys.


text:
Q: Error: signal SIGABRT only occurs in Release Mode Xcode React Native My app works fine in debug mode but after submitting to TestFlight and trying to launch the app it crashes with no explanation whatsoever.
Someone suggested that I build my app in Release mode to see where the error comes from and I'm now getting the following error:

->  0x10f2cbd42 <+10>: jae    0x10f2cbd4c               ; <+20>
signal SIGABRT

How can I solve this?

A: There's a lot that can be wrong in this case.
Try to get a stack trace to see whats wrong.
You can do that by:

*

*running your app in the release build configuration from Xcode.

*adding the Crashlytics SDK to your app and run your app from TestFlight.
The stack trace will appear inside the Fabric console.


text:
Q: Periodic Stream in BLoC Pattern Flutter I am developing a simple chat application, and I had to check-end API with specific time intervals.
but in my BLOC logic I used Observable
So how can I change codes to make this stream periodic?
final bloc = ConversationBloc();

class ConversationBloc {
  final repository = Repository();
  final conversationFetcher = PublishSubject<ConversationModel>();
  final conversationFetcherStatus = PublishSubject<MessageModel>();

  Observable<ConversationModel> get userConversation =>
      conversationFetcher.stream;

  dispose() async {
    await conversationFetcher.drain();
    conversationFetcher.close();
    conversationFetcherStatus.close();
  }

  fetchUserConversation(toUsernameController) async {
    ConversationModel conversationModel =
        await repository.fetchUserConversation(toUsernameController);
    conversationFetcher.sink.add(conversationModel);
  }

  saveConversation(Data conversation) async {
    try {
      MessageModel conversationModel =
          await repository.saveConversation(conversation);
      conversationFetcherStatus.sink.add(conversationModel);
    } catch (e) {
      conversationFetcherStatus.sink.addError(e);
    }
  }

   fetchUserConversationList(int toUsernameController) async {
    ConversationModel conversationModel =
        await repository.fetchUserConversationList(toUsernameController);
    conversationFetcher.sink.add(conversationModel);
  }
}


text:
Q: BERT error while calling a custom function with Application.Run VBA "The macro may not be available in this workbook or all macros may be disabled." I'm actually using VSTO c# to build an Addin that uses BERT has a bridge to get custom R functions on excel. But Im getting some errors trying to call custom functions on Bert functions directory using Application.Run in VBA
Actually I have on ThisAddin class:
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
    }

    void InternalStartup()
    {
    }

    public void BertCall(string functionName, String dataRange)
    {
        if(dataRange.Equals("00:00"))
        {
            MessageBox.Show("Blank cells were found, pleace fill it and try again");
        }
        else
        {
            double result = Application.Run("BERT.Call", functionName, getCurrentWorkSheet().Range[dataRange]);
            MessageBox.Show(result.ToString());
        }
    }

    private Worksheet getCurrentWorkSheet()
    {
        Worksheet currentWorksheet = Globals.Factory.GetVstoObject(
        this.Application.ActiveWorkbook.Worksheets[1]);
        return currentWorksheet;
    }

And in another class Called BertCalls I have the following code
    Validations validate = new Validations();

    public void bertCalls(string functionName)
    {
        Globals.ThisAddIn.BertCall(functionName, validate.getRange()); //this method calls ThisAddIn BertCall method, that handles the comunication with Bert
    }

    public void Sumar()

    {
        Excel.Range selectedRange = Globals.ThisAddIn.Application.Selection;
        bertCalls("sum");

    }

As you see Im using some custom validation classes.
Actually it is working fine when I call build-in R functions, like "sum" but when I try to call custom functions I had the compile error while excecuting the method "Can't execute the macro or it is disabled"
I did the following things:

*

*Create the functions on Documents/Bert2/functions

*Tried to call by the name of the custom function using BERT.Call paramether, but does not work.

*Enabling Trust center to VBA applications and macros

*Change the Application.Run param same as in BERT documentation to
Application.Run(functionName, getCurrentWorkSheet().Range[dataRange]); where functionName is the name of the customFunction, and called by R.AddTest, but get a big negative number.

I need to execute custom functions using BERT with VBA, but I'm getting this error, and I did not find nothing to avoid this error.
Thanks for the help

A: Problem Solved!
I was using windows 10, in onedrive/documents carpet route where BERT2 and the custom R functions, I had to copy that carpet in the local document carpet  C:\Users\user\Documents and it works with the exact code above.
Take care of the routes if you need to work with documents route in windows 10. OneDrive/Documents != User/Documents


text:
Q: Google apps script function returns undefined in html I am building an add-on for google docs (Just for practice) that will act like email. I already incorporated sending, receiving, deleting, and viewing messages. I added the code needed for a UI modal dialog, but one of the functions is only returning undfined. I tested this function in the code.gs file, and it worked perfectly. Here is a section of code.gs:
function onInstall() {
  var html = HtmlService.createHtmlOutputFromFile('Startup').setWidth(350).setHeight(170);
  DocumentApp.getUi().showModalDialog(html, 'New account:');
}

function testCheck() {
  var ui = DocumentApp.getUi();
  ui.alert(checkUsername(ui.prompt('').getResponseText(), ui.prompt('').getResponseText()));
}

function checkUsername(un, em) {
  var i; var a; var is;
  var props = PropertiesService.getScriptProperties();
  if (props.getProperty(un) == null) {
    is = true;
  } else {
    return 'This username is taken!';
  }
  if (em.length == 0) {
    return true;
  } else {
    var len = (em.match(/@/g) || []).length;
    if (len == 1) {
      if (props.getProperty(em) != null) {
        return 'Someone has already registered this email address as ' + props.getProperty(em);
      } else {
        return true;
      }
    } else {
      if (em.indexOf(', ') != -1) {
        em = em.split(', ');
      } else if (em.indexOf('; ') != -1) {
        em = em.split('; ');
      } else if (em.indexOf(' + ') != -1) {
        em = em.split(' + ');
      } else if (em.indexOf(';') != -1) {
        em = em.split(';');
      } else if (em.indexOf(',') != -1) {
        em = em.split(',');
      } else if (em.indexOf('+') != -1) {
        em = em.split('+');
      } else if (em.indexOf(' ') != -1) {
        em = em.split(' ');
      } else {
        return 'Please separate your email addresses with a comma, space, or semicolon.';
      }
      for (i = 0; i < em.length; i++) {
        a = em[i];
        if (props.getProperty(a) != null) {
          return 'Someone has already registered ' + a + ' as ' + props.getProperty(a);
        }
      }
      return true;
    }
  }
}

Here is the html file:
<!DOCTYPE html>

    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">

    Username:

    <input type='text' id='user' style='width:350px' maxlength='12'/>

    Other email addresses:

    <textarea id='extras' style='width:350px' rows='2'></textarea>

    <button class='action' onClick='check()'>Next</button>
    <button onclick='group()'>Groups</button>

Update: I completely retyped the functions, but the program continues to return undefined. All inputs are the correct values, and the function returns information correctly in a ui.alert() box.

A: I figured it out after completely reading the Google Apps Script Documentation. The google.script.run.function() API does not return a value. In order to fetch data from a script, you must have the script generate raw HTML, and create a dialog with an HTML string.

A: Due to security considerations, scripts cannot directly return HTML to a browser. Instead, they must sanitize it so that it cannot perform malicious actions. You can return sanitized HTML using the createHtmlOutput API
function doGet() {
  return HtmlService.createHtmlOutput('Hello, world!');
}

The code in the HtmlOutput can include embedded JavaScript and CSS. (This is standard client-side JavaScript that manipulates the DOM, not Apps Script). All of this content is sanitized using Google Caja, which applies some limitations to your client-side code. For more information, see the guide to restrictions in HTML service.
https://developers.google.com/apps-script/reference/html/html-output#


text:
Q: Receive arrays of arrays of ... in D function? Don't know if is possible, I want receive maybe data[n] or data[n][n][n]. In C could be (correct me if wrong):

void save_data(void* arr, int n, int dimensions)
{
    // do ugly things
}

But must exist a more elegant way in D.

A: One alternative besides using C style pointer arithmetics is to template safe_data, i.e. do something like this:
import std.stdio;
import std.traits;

void safe_data(T)(in T arr) {
    static if(isArray!T) {
        writeln("Length ", arr.length); // do some ugly stuff for whole array
        foreach(e; arr) safe_data(e);   // recursively go deeper
    } else {
        writeln("Element ", arr);       // do more ugly stuff on individual elements
    }
}

void main() {
    writeln("A");
    int[3] A = [1,2,3];
    safe_data(A);
    writeln("B");
    int[3][2] B = [[1,2,3],[4,5,6]];
    safe_data(B);
}

Depending on what you want to do with the data, you might want to use ref instead on in. BTW, if you prefer, you can move the static if outside of the function which makes for cleaner code sometimes:
// handle arrays
void safe_data(T)(in T arr) if(isArray!T) {
        writeln("Length ", arr.length); // do some ugly stuff for whole array
        foreach(e; arr) safe_data(e);   // recursively go deeper
}

// handle array elements
void safe_data(T)(in T e) if(!isArray!T) {
        writeln("Element ", e);         // do more ugly stuff on individual elements
}


text:
Q: After converting a data frame to csv file in colab,I cannot save the file to my google drive import pandas as pd

df = pd.read_excel('/content/drive/MyDrive/Colab Notebooks/Files /Copy of weather_data.xlsx')
k2 = df.head(4)
k2.to_csv('/content/drive/MyDrive/Colab Notebooks/Files/new_fileee.csv',index=False)

This generates an error saying there is no such file or directory

A: Normally, everyone puts the error code in the message, rather than a picture. Have you viewed these sites - Pandas Dataframe to CSV File – Export Using .to_csv() https://datagy.io/pandas-dataframe-to-csv/; pandas.read_excel -https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
Looking at your error, I'm presuming you've tested your output...
print(k2)

Maybe try to get the path using the os.path.dirname
import pandas as pd
import os

df = pd.read_excel("/content/drive/MyDrive/Colab Notebooks/Files/Copy of the weather.xlsx")
k2 = df.head()
dirname = os.path.dirname("content/drive/MyDrive/Colab Notebooks/Files/Copy of the weather.xlsx")
newfilename = "new_fileee.csv"
csvfile = dirname + "/" + newfilename
k2.to_csv(csvfile, index = false)


text:
Q: Find number of combinations, nCr in O(1) Is there a way to find the number of combinations (not the actual combinations), in O(1)? I read an answer here -  time and space complexity of finding combination (nCr). The answer says that it takes O(n!) to find the actual combinations but only takes O(1) to find the number of such combinations. I couldn't understand how it can be done. Please explain me how to do that in O(1). Here, O(1) is time complexity.
[edit]:The main problem I'm having is how to implement n! in O(1).

A: Please check the below C program. It takes n and r as input and calculates nCr value:
int main(){
    int n, r;
    scanf("%d", &n);
    scanf("%d", &r);

    /*
    *  nCr = n! / !(n-r) / !(r)
    *      = n * n-1 * n-2 * .... * 1 / (n-r * n-r-1 * .. * 1) /
    *           (r * r-1 * ... * 1)
    *      = n * n-1 * n-2 * n-r+1 / (r * r-1 * ... * 1)
    *
    */

    int result = 1;
    int i;

    for (i=0; i<r; i++){
        result *= (n-i);    // n * n-1 * n-2 * .... * n-(r-1)
        result /= (i+1);    // r * r-1 * ... * 1
    }

    /*  The loop is going to run only r times for any n
     *  Time to calculate nCr : O(r)
     *  Space complexity: O(1)
    */

    printf("Result of C(%d, %d) = %d", n, r, result);

    return 0;
}

To calculate it, the loop runs only for 'r' times.
Hence, time complexity to calculate nCr value is O(r)
But space complexity is O(1)
I guess you must have been confused with these two complexity orders. Hope, it helps you.

A: If you are trying to calculate n! in constant time, why not use Stirling's Approximation?
n! \approx sqrt(2 * pi * n) * (n / e)^n
or in C:
pow( n, n ) * exp( -n ) * sqrt( 2.0 * PI * n );
I think this will get you the closest to constant time, the actual run time of each of those operations is architecture dependent.
Sources:
https://en.wikipedia.org/wiki/Stirling%27s_approximation
https://github.com/ankurp/C-Algorithms/blob/master/factorial/fact.c

A: The run-time complexity of nCr can only be in O(1) if the computing platform you use computes n! in O(1). On a standard computer, this is not the case.
But we can use the fact that exp(n) and log(n) is usually an O(1) operation for IEEE doubles and implement an approximation of log(n!) - based on Stirling's approximation - in O(1):
logf(n) = log(n!) = (n – 0.5) * log(n) – n + 0.5 * log(2 * PI) + 1/(12 * n)

If we combine this with a lookup-table for log(n!) for n ≤ 255 we will still have at least 14 significant figures and we can compute a very good approximation of nCr as follows:
binomial(n, r) = exp(logf(n) - logf(n - r) - logf(r))

A: Ajeet's answer should be accepted, but I think it can be improved to Min(O(r),O(n-r)) which is still O(r) if reduced.
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System. in );
        int n = sc.nextInt();
        int r = sc.nextInt();
        // choose smaller one
        if (n - r < r) {
            r = n - r;
            System.out.printf("Change %d to %d\n", n - r, r);
        }
        /*
         * nCr  = n! / ((n-r)! * (r)! )
         *      = (n * n-1 * n-2 * .... * 1) / ( (n-r * n-r-1 * .. * 1) * (r * r-1 * ... * 1) )
         *      = (n * n-1 * n-2 * n-r+1) / (r * r-1 * ... * 1)
         */

        int result = 1;

        for (int i = 0; i < r; i++) {
            result *= (n - i); // n * n-1 * n-2 * .... * n-(r-1)
            result /= (i + 1); // r * r-1 * ... * 1
        }

        /*
         * The loop is going to run only r times or (n-r) times for any n Time to calculate nCr : Min ( O(r) , O(n-r) )
         * Space complexity: O(1)
         */
        System.out.printf("Result of C(%d, %d) = %d", n, r, result);
    }
}

A: In some of the use cases, it might be best to precompute all the answers in O(n^2) by generating pascal's triangle, so that the queries are O(1).
Other times you just have to calculate n! one by one so the complexity would be O(n).


text:
Q: How to hover all elements but avoid some? I need to be able to hover elements but not all. In this case I tried all but not the table.
$(".modal-content *:not("table")").on("mouseenter", function() {...

UPDATE
I had a typo, accepting the answer.

A: You have a error with quotation mark. Try this.
$(".modal-content *:not(table)").on("mouseenter", function() {...

A: You do not need quotes around the word 'table' at all.... The selector should read:
.modal-content *:not(table)

Just so it's clear, that selector means "all elements that are descendants of an element with a className of '.modal-content' but NOT table elements.
P.S. - if you're just adding visual effects to elements, you should use pure CSS and not jQuery. For example, to turn elements red on hover:
.modal-content *:not(table):hover {
   background-color: red;
}

A: Here ya go (turns red on hover):
$('.modal-content')
  .on('mouseenter', '*:not(table,table *)', function (e) {
    $(this).css({ backgroundColor: 'red' })
  })
  .on('mouseleave', '*:not(table,table *)', function (e) {
    $(this).css({ backgroundColor: 'initial' })
  });

jsFiddle: https://jsfiddle.net/o9nj2saf/1/


text:
Q: How to retrieve Entity Configuration from Fluent Api Using Entity-Framework 6 I'm able to set up the configuration through Fluent Api like this:
public class ApplicationUserConfiguration : EntityTypeConfiguration<ApplicationUser>
{
    public ApplicationUserConfiguration()
    {
        this.HasKey(d => d.Id);
        this.Ignore(d => d.UserId);
    }
}

Source from this question
Using the attribute approach I'm able to know what's the property roles by reflection, but I wonder how can I retrieve these configurations, like Key for example, with Fluent Api approach?
There's no public property from the EntityTypeConfiguration<> class.
Is that possible to get the Key and ForeignKey somehow?

A: There is a MetadataWorkspace class which provides API to retrieve metadata about storage, model, CLR types and mappings for Entity Framework.

Represents the ADO.NET metadata runtime service component that
  provides support for retrieving metadata from various sources.

Having an instance of DbContext, you can find its MetadataWorkspace using following code:
var metadataWorkspace = ((IObjectContextAdapter)dbContext).ObjectContext.MetadataWorkspace;

Then you can get item collections which contain different types of models including object model, the conceptual model, the storage (database) model, and the mapping model between the conceptual and storage models.
The following extension methods returns EntityType for given clr type:
using System;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Linq;

public static class DbContextExtensions
{
    public static EntityType GetEntityMetadata<TEntity>(this DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException(nameof(dbContext));

        var metadataWorkspace = ((IObjectContextAdapter)dbContext)
            .ObjectContext.MetadataWorkspace;
        var itemCollection = ((ObjectItemCollection)metadataWorkspace
            .GetItemCollection(DataSpace.OSpace));
        var entityType = metadataWorkspace.GetItems<EntityType>(DataSpace.OSpace)
            .Where(e => itemCollection.GetClrType(e) == typeof(TEntity)).FirstOrDefault();

        if (entityType == null)
            throw new Exception($"No entity mapped to CLR type '{typeof(TEntity)}'.");

        return entityType;
    }
}

Then you can use EntityType to extract more information about the model, for example you can find a list of key properties:
var keys = dbcontext.GetEntityMetadata<Category>().KeyProperties.Select(x=>x.Name).ToList();


text:
Q: Skipping parameters in callback function The callback function I'm working with has the following signature (from http://api.jquery.com/load/):
complete(responseText, textStatus, XMLHttpRequest)

Now, I only need the third parameter. In Lua there's a convention where an underscore is used to skip unneeded return values from functions (skip because _ will actually hold the value):
var1, _, _, var4 = func()

So I thought of doing a similar thing with JavaScript and set my function signature to this:
function (_, _, XMLHttpRequest)

Is there anything wrong with this approach, perhaps there's a better/cleaner way?

A: You're using two arguments which have the same name. You should write so :
function (_, __, myXhr)

A: The technique is not pretty, but I use it myself on several occasions. I guess it is still quite better to give those unused arguments meaningful names (just to avoid confusion), but you're fine in using underscores.
I often see it used in jQuery related callbacks, where the index is often passed in as first argument, like
$('.foo').each(function(_, node) {
});

because most of the time, you don't care about the index there. So to answer your actual question, there is nothing wrong in using the technique (beside confusion maybe) and there is no better/cleaner way to skip unwanted arguments.

A: I acknowledge that using _ is a common pattern to omit parameters that prepend the one you want. That's cool for one parameter, maybe 2.
somethingWithACallback((_, whatIAmLookingFor) => {
  // ...
})

but I got stuck needing the 5th one. This would mead I'd have to write
somethingWithACallback((_, __, ___, ____, whatIAmLookingFor) => {
  // ...
})

For that case I propose this pattern:
somethingWithACallback((...args) => {
  const whatIAmLookingFor = args[4];
})

With destructuring, you can also do this
somethingWithACallback((...args) => {
  const [,,,,whatIAmLookingFor] = args;
})

and apply that to multiple parameters
somethingWithACallback((...args) => {
  const [,,,,whatIAmLookingFor,,andAnotherThing] = args;
})

and thereby essentially pick what you need.

A: You can combine the variadic definition with array destructuring.
something((...[,,req]) => { /* req.blah */ }

If you are using Typescript, you will need to add type definitions for the arguments, and you can either be generic:
something((...[,,req]: any[]) => { /* req.blah */ })

Or specific:
something((...[,,req]: [ResponseText, TextStatus, XMLHttpRequest]) => { /* req.blah */ })

Or, as you are discarding the non-required parameters, you could use any (or unknown) for those:
something((...[,,req]: [any, any, XMLHttpRequest]) => { /* req.blah */ })

If you find that verbose, then introduce a type:
type Params = [ResponseText, TextStatus, XMLHttpRequest]

something((...[,,req]: Params) => { /* req.blah */ })


text:
Q: How to replace string in the website after PHP have complete the processing For example , the is a word 'cat', and I would like to change to 'dog' in every page,
but in server side:
 str_replace("cat","dog",$doc);

or in cilent side:
 doc.replace("cat", "dog");

I need to provide the doc variable, is it possible to just auto search and find the server processed result and replace the word in every page?
It may also changed the code in javascript and lead to error , but to simplify , just assume the jquery doesn't have function name/ variable using 'cat'
Thanks a lot for helping.
Updated:
Thanks for the answer. Last question, if I use framework such as codeigniter, where should I put the ob buffer code?
e.g.
In controller?
function index() {
    $data['demo_data'] = $demo_data;
    $this->load->view('test',$data);
}

A: One way to do this is tu use output buffering :
http://php.net/manual/en/function.ob-start.php (see Example #1)
You have to be careful  when to replace text in html because str_replace() will also match in html tags and javascript code in your page.

A: The proper solution would be to use a variable:
<?php
$animal = 'cat';

echo "My $animal took a walk in the park.".

The methods you suggest both imply a bad design and will possibly result in undesirable side-effects.

A: You could use output buffering in PHP.
http://php.net/ob_start
<?php
ob_start();

//do some stuff

$buffer = ob_get_flush();
$output = preg_replace(/\bcat\b/, 'dog', $buffer);
echo $out;

A: I think it's all meaningless, but it works
 document.documentElement.innerHTML =
 document.documentElement.innerHTML.replace(/cat/g,'dog')

About codeigniter
function index() {
    $data['demo_data'] = $demo_data;
    //  Add 3rd argument as true to get output muffer
    $text = $this->load->view('test',$data, true);
    // Any manipulations with text
    echo $text;
}


text:
Q: Why am I getting a NameError when I use input() in Python 2? I am getting a classic
NameError : name 'Y' is not defined.
I know this is extreme beginner level and a multitude of similar questions have been answered.
However none of the answers have helped me fix this simple issue. Replies would be greatly appreciated.
def intro ():
#checks if the user already has an account and redirects accordingly

print("ARE YOU A REGISTERED USER? [Y/N]")
redirect = input()
if redirect == "Y" :
    print("OK")
else :
    print("gtfo")

intro()

A: Looks like you're using Python 2. Try using raw_input() instead of input(). input() on Python 2 is equivalent to eval(raw_input(string)).

A: this worked for me using python3, you can add a way to also check lower case inputs.
def intro():
    redirect = input("ARE YOU A REGISTERED USER? [Y/N] ")
    if redirect == "Y" :
        print("OK")
    else :
        print("gtfo")

intro()
exit = input("press any key to exit")


text:
Q: Sqlite3 performance issues with single row UPDATE Background:
So as the title suggests, I am having performance issues with sqlite3 doing a simple update on a single row, and I can't track it down.
I've already disabled synchronous and journal_mode, as suggested in every other performance thread I've read through.

Details:
Kernel: Linux beaglebone 4.4.30-ti-r64
FileSystem: Linux beaglebone 4.4.30-ti-r64
SQLite: 3.8.7.1 2014-10-29 13:59:56
Row Count: 163
Query: (UPDATE tableX SET value='15' WHERE parm='parmY')
Time To Execute: 2730 ms
Schema: TABLE tableX (rowId INTEGER PRIMARY KEY AUTOINCREMENT, parm varchar(32), value varchar(32));

I make the assumption that I'm only updating one row, and there's only 163 to parse through to find the proper one, so where am I going wrong to cause this type of performance hit on such a simply query?
I initially thought it was my code causing the issue somehow, but when I tried it directly through the terminal, the time was very similar.

Edit 1: Copied DB to host PC, and it is performing as expected with very quick return from this query. Now to figure out exactly what's going on with the target system that could be causing this.


text:
Q: slider not working with setInterval( ) function I am loading news and notification in my PhoneGap app with setInterval( ) function. The news come one by one and load until the last news comes. The problem is that scroll bar on this page doesn't work until the news are load completely. What's wrong with it?
My code
function clearPackageTableSuccess(x) {
    if(x=="c") {
        //alert("x="+x);
        clearInterval(myVar);
    } else {
        //alert("hhh");
        myVar = setInterval(function() {
            newsloop()
        }, 100);
    }
}


text:
Q: Python (paramiko) - No such file or directory: u'\u012f\u0161-test.xls' My file name is this file_path=u'įš-test.xls.
When I try this:
from xlrd import open_workbook
wb = open_workbook(file_path)

I get this error:
  File "/usr/local/lib/python2.7/dist-packages/xlrd/__init__.py", line 394, in open_workbook
    f = open(filename, "rb")
IOError: [Errno 2] No such file or directory: u'\u012f\u0161-test.xls'

If I change to:
wb = open_workbook(file_path.encode('utf-8'))

IOError: [Errno 2] No such file or directory: '\xc4\xaf\xc5\xa1-test.xls'

Note
There might be a problem with paramiko, because file is taken from remote directory, using this method (if file with unicode name is taken from local directory, it passes fine too):
from contextlib import closing
import socket, os
from paramiko import SSHConfig, SSHClient, AutoAddPolicy, AuthenticationException

    def check_remote_dir(self, cr, uid, ids, direct, arch_dir, gec_type, fmt, context=None):
        rec = self.browse(cr, uid, ids, context=context)[0]
        with closing(SSHClient()) as ssh:
            ssh.set_missing_host_key_policy(AutoAddPolicy())
            try:
                ssh.connect(rec.host, username=rec.user, password=rec.password)
            except socket.gaierror:
               raise orm.except_orm(_('Error!'),
                    _("Name or service '%s' not known") % (rec.host))
            except AuthenticationException:
               raise orm.except_orm(_('Authentication Fail!'),
                    _("Bad username or password"))
            with closing(ssh.open_sftp()) as sftp:
                try:
                    sftp.chdir(direct)
                except IOError:
                    raise orm.except_orm(_('Error!'),
                        _('Remote directory %s not found') % (direct))
                try:
                    os.chdir(arch_dir)
                except OSError:
                    raise orm.except_orm(_('Error!'),
                        _('Archive directory %s not found') % (arch_dir))
                gec_obj = self.pool.get('card.gec.data')
                for f in sftp.listdir():
                    for fmt in fmt.replace(' ', '').split(','): #removing any whitespace and then splitting in list
                        length = len(fmt) + 1
                        if f[-length:] == ".%s" % (fmt):
                            gec_id = gec_obj.create(cr, uid, {'name': f, 'gec_type': gec_type})
                            self._resolve_parse(cr, uid, gec_id, gec_obj, gec_type, f, context=context)
                            self.archive_file(f, None, add_dt=True, remote=True)
                            sftp.remove(f)
                            break #only need to check till first occurence

P.S. method params like cr, uid, ids are application specific and are not really related with remote file handling, so you can ignore those
Update
I noticed this in a log:
2015-02-03 10:23:48,143 10430 INFO amb_test paramiko.transport.sftp: [chan 1] Opened sftp connection (server version 3)
is-test.xls
2015-02-03 10:23:48,162 10430 INFO amb_test paramiko.transport.sftp: [chan 1] sftp session closed.

This happens and then I get that error. Could it be that session is closed before file is used?
Update2
It seems something is wrong with sftp.listdir(). When I try to use filename from it, like using standard open, it gives error, that there is no such file as I guess it only checks on local directory (I don't get it how it was working before..). If I try to open with sftp.open(), then it works.
How could I use remote path to open it in local server?

A: It seems there was something wrong with remote file paths. When I got a remote path and tried to directly open from it, it would not see it and would throw an error that such file not found.
So I rewritten my methods, to handle remote files a bit differently. Now it just downloads it and opens it locally, instead of remotely (and only after parsing saving it locally).
If there are better approaches, please feel free to post them as answers.
So here my new methods that solved my problem:
def check_remote_dir(self, cr, uid, ids, rem_dir, local_dir, arch_dir, gec_type, fmt, context=None):
    """
    Only used to check remote directories and download files
    locally
    """
    rec = self.browse(cr, uid, ids, context=context)[0]
    with closing(SSHClient()) as ssh:
        ssh.set_missing_host_key_policy(AutoAddPolicy())
        try:
            ssh.connect(rec.host, username=rec.user, password=rec.password)
        except socket.gaierror:
           raise orm.except_orm(_('Error!'),
                _("Name or service '%s' not known") % (rec.host))
        except AuthenticationException:
           raise orm.except_orm(_('Authentication Fail!'),
                _("Bad username or password"))
        with closing(ssh.open_sftp()) as sftp:
            try:
                sftp.chdir(rem_dir)
            except IOError:
                raise orm.except_orm(_('Error!'),
                    _('Remote directory %s not found') % (rem_dir))
            try:
                os.chdir(local_dir)
            except OSError:
                raise orm.except_orm(_('Error!'),
                    _('Archive directory %s not found') % (arch_dir))
            gec_obj = self.pool.get('card.gec.data')
            for f in sftp.listdir():
                sftp.get(f, f)
                sftp.remove(f)
    #handle files locally
    rec.check_dir(local_dir, arch_dir, gec_type, fmt)

def check_dir(self, cr, uid, ids, direct, arch_dir, gec_type, formats, context=None):
    rec = self.browse(cr, uid, ids, context=context)[0]
    try:
        os.chdir(direct)
    except OSError:
        raise orm.except_orm(_('Error!'),
            _('Directory %s not found') % (direct))
    directs = os.listdir(direct)
    gec_obj = self.pool.get('card.gec.data')
    formats = formats.replace(' ', '').split(',') # Removing any whitespace and then splitting in list
    for f in directs:
        for fmt in formats:
            length = len(fmt) + 1
            if f[-length:] == ".%s" % (fmt):
                gec_id = gec_obj.create(cr, uid, {'name': f, 'gec_type': gec_type})
                self._resolve_parse(cr, uid, gec_id, gec_obj, gec_type, f, context=context)
                self.archive_file(f, arch_dir, add_dt=True)
                break #only need to check till first occurence


text:
Q: SUM function sometimes takes more than 30 seconds I'm using POSTGRESQL database and have pretty simple query that calculates total revenue for selected time period (startDate and endDate input parameters).
Here is public.processedorder table definition:
CREATE TABLE public.processedorder (
    "OrderId" int4 NOT NULL,
    "ChannelId" int4 NOT NULL,
    "ShippingId" int4 NOT NULL,
    "CountryId" int4 NOT NULL,
    "LocationId" int4 NOT NULL,
    "PackagingId" int4 NOT NULL,
    "ConvertedTotal" numeric(18,6) NOT NULL,
    "ConvertedSubtotal" numeric(18,6) NOT NULL,
    "ConvertedShippingCost" numeric(18,6) NOT NULL,
    "ConvertedShippingTax" numeric(18,6) NOT NULL,
    "ConvertedTax" numeric(18,6) NOT NULL,
    "ConvertedDiscount" numeric(18,6) NOT NULL,
    "ConversionRate" numeric(18,6) NOT NULL,
    "Currency" varchar(3) NOT NULL,
    "OriginalTotal" numeric(18,6) NOT NULL,
    "OriginalSubtotal" numeric(18,6) NOT NULL,
    "OriginalShippingCost" numeric(18,6) NOT NULL,
    "OrignalShippingTax" numeric(18,6) NOT NULL,
    "OriginalTax" numeric(18,6) NOT NULL,
    "OriginalDiscount" numeric(18,6) NOT NULL,
    "ReceivedDate" timestamp NOT NULL,
    "DispatchByDate" timestamp NOT NULL,
    "ProcessedDate" timestamp NOT NULL,
    "HoldOrCancel" bool NOT NULL,
    "CustomerHash" varchar(100) NOT NULL,
    "EmailHash" varchar(100) NOT NULL,
    "GetPostalCode" varchar(10) NOT NULL,
    "TagId" uuid NOT NULL,
    "timestamp" timestamp NOT NULL,
    "IsRMA" bool NOT NULL DEFAULT false,
    "ConversionType" int4 NOT NULL DEFAULT 0,
    "ItemWeight" numeric(18,6) NULL,
    "TotalWeight" numeric(18,6) NULL,
    "PackageWeight" numeric(18,6) NULL,
    "PackageCount" int4 NULL,
    CONSTRAINT processedorder_pkey PRIMARY KEY ("OrderId"),
    CONSTRAINT processedorder_tagid_unique UNIQUE ("TagId")
)
WITH (
    fillfactor=50,
    autovacuum_enabled=false
);
CREATE INDEX ix_processedorder_receieveddate ON public.processedorder USING btree ("ReceivedDate" DESC NULLS LAST) WITH (fillfactor='50');

Here is a query:
SELECT SUM(o."ConvertedTotal") as "totalRevenue"
FROM public.processedorder o
WHERE o."ReceivedDate" BETWEEN '2020-07-23T00:00:00.000Z' and '2021-06-05T00:00:00.000Z'

Sometimes the query uses ix_processedorder_receieveddate index, sometimes not, I guess it depends on startDate and endDate params.
Here is a query plan of the query above:
Finalize Aggregate  (cost=92468.33..92468.34 rows=1 width=32) (actual time=371.130..371.131 rows=1 loops=1)
  ->  Gather  (cost=92468.11..92468.32 rows=2 width=32) (actual time=371.074..371.105 rows=3 loops=1)
        Workers Planned: 2
        Workers Launched: 2
        ->  Partial Aggregate  (cost=91468.11..91468.12 rows=1 width=32) (actual time=367.789..367.790 rows=1 loops=3)
              ->  Parallel Seq Scan on processedorder o  (cost=0.00..91121.46 rows=138661 width=7) (actual time=0.021..268.513 rows=114050 loops=3)
                    Filter: (("ReceivedDate" >= '2020-07-23 00:00:00'::timestamp without time zone) AND ("ReceivedDate" <= '2021-06-05 00:00:00'::timestamp without time zone))
                    Rows Removed by Filter: 296245

Here is another the same query with different params:
SELECT SUM(o."ConvertedTotal") as "totalRevenue"
    FROM public.processedorder o
    WHERE o."ReceivedDate" BETWEEN '2021-05-01T00:00:00.000Z' and '2021-06-05T00:00:00.000Z'

Here is the query plan of the last query:
Aggregate  (cost=42314.13..42314.14 rows=1 width=32) (actual time=89.767..89.768 rows=1 loops=1)
  ->  Bitmap Heap Scan on processedorder o  (cost=500.94..42272.06 rows=16830 width=7) (actual time=9.696..66.717 rows=26347 loops=1)
        Recheck Cond: (("ReceivedDate" >= '2021-05-01 00:00:00'::timestamp without time zone) AND ("ReceivedDate" <= '2021-06-05 00:00:00'::timestamp without time zone))
        Heap Blocks: exact=2156
        ->  Bitmap Index Scan on ix_processedorder_receieveddate  (cost=0.00..496.73 rows=16830 width=0) (actual time=9.404..9.404 rows=26347 loops=1)
              Index Cond: (("ReceivedDate" >= '2021-05-01 00:00:00'::timestamp without time zone) AND ("ReceivedDate" <= '2021-06-05 00:00:00'::timestamp without time zone))

Basically the summation is over ~200,000 rows
Do you have any ideas guys, could it be because of invalid format of timestamp and it's not uses the index or what?
Thanks.

A: Maybe stats are just out of date try ANALYZE processedorder
Also just for testing purposes you can force the use of the index by "disabling" sequential scans
SET enable_seqscan = OFF;

A: My guess
I would guess that it's PostgreSQL trying to optimize your results.
In this case I have no idea what to do about it.
You could try splitting the request in smaller chunks to verify this. If your time period is only a few days, does it use the index more reliably?
Take into account the number of rows filtered in your two examples. There is a huge difference. This might cause PostgreSQL to just go find the rows in the table without the index, as it's a large chunk of the entire tables content. Retrieving data from an index has it's own costs and the larger your chunk of data the greater this cost and the less your gain.
What to do?
If this is an operation you repeat fairly often you might want to engineer another solution on how to request the data.
E.g. creating another table containing just the needed columns and maybe pre-aggregated day-wise, or whatever fits your needs.

A: if you don't have an index on both "ConvertedTotal and "ReceivedDate" , that definitely improve your performance alot :
create index ix_name on processedorder (ReceivedDate,ConvertedTotal);


text:
Q: RHEL Routing with 3 nics I am trying to get my routing to work on my RHEL 7 with 3 nics and 3 subnets.
I have the followig nics
DEVICE=eth0
BOOTPROTO=sttic
ONBOOT=yes
TYPE=Ethernet
USERCTL=yes
PEERDNS=yes
IPADDR=10.241.78.5
NETMASK=255.255.254.0
IPV6INIT=no

DEVICE=eth1
BOOTPROTO=static
IPADDR=10.241.74.5
NETMASK=255.255.254.0
ONBOOT=yes
TYPE=Ethernet
USERCTL=yes
PEERDNS=yes
IPV6INIT=no

DEVICE=eth2
BOOTPROTO=static
IPADDR=10.241.76.5
NETMASK=255.255.254.0
ONBOOT=yes
TYPE=Ethernet
USERCTL=yes
PEERDNS=yes
IPV6INIT=no

ip route show
10.241.74.0/23 dev eth1  proto kernel  scope link  src 10.241.74.5
10.241.78.0/23 dev eth0  proto kernel  scope link  src 10.241.78.5
10.241.76.0/23 dev eth2  proto kernel  scope link  src 10.241.76.5
default via 10.241.78.1 dev eth0

I have a system 10.241.74.7 behind eth1 and 10.241.76.7 behind eth2
I also have sysctl.conf setup with the following
# Controls the use of TCP syncookies
net.ipv4.tcp_syncookies = 1

# Disable netfilter on bridges.
net.bridge.bridge-nf-call-ip6tables = 0
net.bridge.bridge-nf-call-iptables = 0
net.bridge.bridge-nf-call-arptables = 0

The issue I am having is that system behind eth1 cannot reach eth2 and vice versa.
also when i initiate a ping from the .5 system
ping 10.241.74.7 -I eth2
PING 10.241.74.7 (10.241.74.7) from 10.241.76.5 eth2: 56(84) bytes of data.
From 10.241.76.5 icmp_seq=2 Destination Host Unreachable
From 10.241.76.5 icmp_seq=3 Destination Host Unreachable
From 10.241.76.5 icmp_seq=4 Destination Host Unreachable

ping 10.241.76.7 -I eth1
PING 10.241.76.7 (10.241.76.7) from 10.241.74.5 eth1: 56(84) bytes of data.
From 10.241.74.5 icmp_seq=2 Destination Host Unreachable
From 10.241.74.5 icmp_seq=3 Destination Host Unreachable
From 10.241.74.5 icmp_seq=4 Destination Host Unreachable

However, when I ping both networks from eth0 it works:
ping 10.241.76.7 -I eth0
PING 10.241.76.7 (10.241.76.7) from 10.241.78.5 eth0: 56(84) bytes of data.
64 bytes from 10.241.76.7: icmp_seq=1 ttl=64 time=0.450 ms
64 bytes from 10.241.76.7: icmp_seq=2 ttl=64 time=0.483 ms

ping 10.241.74.7 -I eth0
PING 10.241.74.7 (10.241.74.7) from 10.241.78.5 eth0: 56(84) bytes of data.
64 bytes from 10.241.74.7: icmp_seq=1 ttl=64 time=0.461 ms
64 bytes from 10.241.74.7: icmp_seq=2 ttl=64 time=0.399 ms

iptables has been flushed, so I am not sure why traffic is not passing between both networks ... there may be a routing issue?
netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
10.241.74.0     0.0.0.0         255.255.254.0   U         0 0          0 eth1
10.241.78.0     0.0.0.0         255.255.254.0   U         0 0          0 eth0
10.241.76.0     0.0.0.0         255.255.254.0   U         0 0          0 eth2
0.0.0.0         10.241.78.1     0.0.0.0         UG        0 0          0 eth0

Can anyone help?

A: For Linux to forward packets between interfaces you need to set net.ipv4.ip_forward=1 in /etc/sysctl.conf and either reboot the system for the changes to take effect or run sysctl -p
Regarding your ping results, if I remember correctly, by specifying -I ethX on the ping command, you are forcing the packets to actually leave from the specified interface (regardless of subnet configuration and routing on that interface).
What you need to do is try to ping with the source address you want to check (eg instead of ping -I eth0 10.241.74.7 try ping -I 10.241.78.5 10.241.74.7).
This way the packets will leave with the source address 10.241.78.5 but from the proper interface where 10.241.78.0/23 subnet is actually configured on.


text:
Q: Storing multiple objects in a file I have a collection of objects in form of an ArrayList and I want to keep all of the objects into a file. At present I am storing the complete ArrayList into the file(of size 26,000) and I have experienced a latency of 80ms in reading it. Which way is better? Storing the complete ArrayList or the Array of Objects into the file?
P.S.: No of objects can be above millions in count.

A: I think saving ArrayList<T> to single binary file using Serializable is a best way unless your data file is up to 4 Gb.
In the other way you can do the serialization in multiple threads. If you'll go this way - it is possible to find n - optimal number of threads and array parts.


text:
Q: input value should update on span value changes once file uploads After uploading an image file, I want the <input>'s value to reflect my  value. However, only after I click the  tag does the <input> change its value, not automatically on the 's change as desired.
I want the -change to update the <input>'s value.
<input
  v-model="data.filename"
  class="input"
  type="text"
  placeholder
  readonly
/>

  {{ file.name }}

    Upload

export default {
  data() {
    return {
      file: null,
      data: {
        filename: ''
      },
    }
  },
  methods: {
    valuedata() {
      this.data.filename = this.file.name
    }
  }
}

The screenshot above shows the results after file upload/selection. While the 's value updates correctly, the <input>'s value however remains the same. Its value updates only after clicking the anchor tag.

A: The b-upload component has an input event that is fired when a file is selected:

You could add an input-handler that sets data.filename to the selected file's name:

export default {
  methods: {
    onFileSelected(file) {
      this.data.filename = file.name
    }
  }
}

demo


text:
Q: Conservation of momentum always? Consider two atoms A and B, with A at rest and B in motion towards A.
As soon as B is in the atomic field of A, will it stop with its energy going into B or will it just move up to a postion where there is equillibrum between the forces of both the atoms and then move A with itself, but the whole mass will now move with a lesser velocity, i.e. the momentum just gets rearranged?
When I look at the above scenario, I find it easy to agree with the second option (the rearrangement of momentum), but it looks like the first option of stopping will never happen, because it can repel back only if it goes beyond the point of equilibrium, which doesn't look like it will happen.
Even if it happens, how will A gain all of the force of B, as A will experience a atomic force from B which will balance some amount of the force of A?
please explain

A: Newton's third law says the the force on A due to B is equal and opposite to the force on B due to A.  This in turn means that the changes of momentum of A and B are the same in magnitude but opposite in direction.  This is how the momentum becomes rearranged.  B loses some momentum and A gained an equal amount.
So when two atoms collide you can think of their electrons shells interacting.  This interaction might well form a bond between the atoms but the combined amount of momentum they carried will not change.  You can think of one of the atoms slowing down whilst the other speeds up until they are both travelling at the same velocity.
PS Be careful about using energy, force and momentum as though they are interchangeable words.


text:
Q: List recent operations on mongodb I'm using MongoDB with Node.js framework.
There is a weird behavior that some documents are not getting inserted into db, though from orm's point of view there are no errors: err = null in callback of Collection.create() and fresh document with _id is returned. When I try to search by that _id in db - no document is found.
I tried to manually insert new document to db and it was successfull.
Is there a way I can trace these operations from db's point of view? Some command to list recent requests and their results..?

A: You can enable profiling for all operations:
db.setProfilingLevel(2)

Then, look at system.profile collection to see what's happen.  system.profile is a capped collection that can be searched as any other collection. Profiling can be noisy, and eventually you should have to change the size of the system.profile collection
db.setProfilingLevel(0)

db.system.profile.drop()

db.createCollection( "system.profile", { capped: true, size:4000000 } )

db.setProfilingLevel(2)

A: The most notable way of tracking errors within MongoDB is to use the --diaglog option: http://docs.mongodb.org/manual/reference/program/mongod/#cmdoption--diaglog with maybe a level of 3, however 1 might be enough for you.
As noted by @Neil this has unfortunately become deprecated as of 2.6.
The only way currently is to write out ALL operations MongoDB performs, via @Rauls answer, and then use a query like:
db.system.profile.find({op:{$in:['update', 'insert', 'remove']}});

and possibly resize the capped collection used for profiling: http://docs.mongodb.org/manual/tutorial/manage-the-database-profiler/#profiler-overhead to capture the amount you want.


text: Q: Создать Angular 7 drop-down list? мне нужно сделать что-то вроде drop-down списка, но только элементы должны выпадать по клику и не исчезать, а исчезать только по некст клику мышки. К примеру есть у меня массив картинок, по клику на название drop-down списка все картинки из списка "выпадают" на странице, и если кликнуть еще раз, они исчезают назад в список, т.е. drop-down закрылся, как это лучше всего реализовать в Angular 7, и есть ли уже примеры подобных реализаций?


text:
Q: Add column to pandas without headers How does one append a column of constant values to a pandas dataframe without headers? I want to append the column at the end.
With headers I can do it this way:
df['new'] = pd.Series([0 for x in range(len(df.index))], index=df.index)

A: Each not empty DataFrame has columns, index and some values.
You can add default column value and create new column filled by scalar:
df[len(df.columns)] = 0

Sample:
df = pd.DataFrame({0:[1,2,3],
                   1:[4,5,6]})

print (df)
   0  1
0  1  4
1  2  5
2  3  6

df[len(df.columns)] = 0
print (df)
   0  1  2
0  1  4  0
1  2  5  0
2  3  6  0

Also for creating new column with name the simpliest is:
df['new'] = 1


text:
Q: Como abrir uma página de acordo com o link inserido no input? Quero fazer um formulário que quando eu colocasse o endereço (URL) em um campo e clicar no botão Enviar ir para o site inserido no campo. Como fazer isso?

A: Você pode utiliza javascript com  window.open ou window.location para fazer o que deseja.
Exemplo com window.open():
Ele vai abrir o url numa nova janela.
window.open('http://www.google.com');
Exemplo com window.location.href:
Ele vai abrir na janela atual
window.location.href = 'http://www.google.com';

Exemplo de utilização:
 <form>
    <input name="url" type="text" id="url">
    <input type="button" id="btn" value="Acessar" onClick="javascript: window.open(document.getElementById('url').value);" />
 </form>

O javascript pega o link digitado no campo de texto com ID url, e abre uma nova aba ou janela com window.open.

A: Segue um exemplo

document.getElementById('send').onclick = function(){
  let url = document.getElementById("url").value
  alert(url)
  window.open(url, "_self")
}
<input type="text" id="url">

<button id="send">Enviar</button>


text:
Q: Interpretar  en una celda de gridView Tengo que separar por marcas de \n el contenido de una celda de GridView para conseguir que en una celda aparezcan lineas diferentes.
El código en el que me hallo es el siguiente:
Modificando la DataTable:
cmd = new OracleCommand();
cmd.Connection = cnn;
cmd.CommandText = comando;
da.SelectCommand = cmd;
da.Fill(dt);

for (int i = 0; i < dt.Rows.Count; i++)
{
    string text = dt.Rows[i]["OBSFX"].ToString();
    text = text.Replace("\n", "
 ");
    dt.Rows[i]["OBSFX"] = text;
}

GridView1.DataSource = dt;
GridView1.DataBind();

Ahora modificando el GridView directamente:
cmd = new OracleCommand();
cmd.Connection = cnn;
cmd.CommandText = comando;
da.SelectCommand = cmd;
da.Fill(dt);

GridView1.DataSource = dt;
GridView1.DataBind();

for (int i = 0; i < GridView1.Rows.Count; i++)
{
    string text = GridView1.Rows[i].Cells[16].Text;
    text = text.Replace("\n", "
");
    GridView1.Rows[i].Cells[16].Text = text;
}

GridView1.DataBind();

Ninguna de las dos maneras funciona. ¿Alguna idea?

A: El método Replace sustituye todas las ocurrencias que coincidan con el primer parámetro por el valor del segundo. En tu caso, si quieres cambiar
 por \n la instrucción sería:
text = text.Replace("
", "\n");

Justo al contrario de como lo tienes.
Además, para que la celda muestre más de una línea, es posible que tengas que ajustar un par de propiedades en el GridView, como el alto de fila automático y el ajuste de palabras (wordwrap) en las celdas.

A: Finalmente encontre la respuesta a mi problema. Tenia que generar un evento de RowDataBoundy ahi insertar el siguiente codigo :
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            string encoded = e.Row.Cells[i].Text;  //
            e.Row.Cells[i].Text = encoded.Replace("\n", "
");
        }
    }
}

Este evento se encuentra dentro de la GridViewy solo hay que añadir el evento y el codigo y ya funciona solo.
Muchas gracias a todos por vuestra colavoracion!!! :D
Espero que a alguien le ayude.


text:
Q: (Import Error) cant install packages with pip since trying to install gensim.models Had to install a number of packages and pip install worked perfectly fine but since trying to install gensim.models (which i think was wrong since it should have been gensim) i cant install either gensim or other packages.
The following error always pops up:

edit:
after searching for solutions i found this

my output is Version: 1.12.0
But pip install -U six doesnt work

A: The solution for me was to manually replace the content of the  six file
( in my case under /lib/python3.9/site-packages/six.py )
with the content of
https://raw.githubusercontent.com/benjaminp/six/master/six.py