text:
Q: StandardSetController and Too many Locator Rows I'm creating a Search page so user can search all of the objects by Super Customers and I have ran into a snag.  Originally I set up my search like this .
Edit -- I Don't want to Pagination that many records, It looks like on load the entire Oppty Object is getting queried THEN once the Search is done it filters it.
    public List<Case> setOppCon (Set<Id> accountIds){
        return[
        SELECT Name,OwnerId,StageName,RecordTypeId,Design_Region__c,Design_Territory__c,Potential_Value1__c,
                            LastModifiedDate,Probability
                         FROM Opportunity WHERE Account__c IN: accountIds];
    }

I was not thinking of pagination when I built it , so in order to allow pagination I switched it so I can now use StandSetControllers as such
public ApexPages.StandardSetController setOppCon {
    get {
        if(setOppCon == null) {
            setOppCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                [SELECT Name,OwnerId,StageName,RecordTypeId,Design_Region__c,Design_Territory__c,Potential_Value1__c,
                            LastModifiedDate,Probability
                         FROM Opportunity]));
        }
        return setOppCon;
    }
    set;
}
     public List<Opportunity> getOpps(Set<Id> accountIds) {
             setOppCon.setPageSize(5);
            return (List<Opportunity>) setOppCon.getRecords();
     }

But now the issue that I am having is that I am getting an error Too many query locator rows: 10001, and I believe that is happening because  now I am querying every single record at load and filtering rather than querying with the filter in place.
Pagination I thought was suppose to fix that, but I am having no luck.  I'm somewhat confident I did the class correct, I am unsure about the VF Page.
</apex:pageBlock>
    <apex:pageBlock title="Opportunities">
    <apex:pageblockTable value="{!optyList}" var="opty">
    <apex:column headerValue="Opportunity Name"><apex:outputLink value="/{!opty.Id}">{!opty.Name}</apex:outputLink></apex:column>
    <apex:column value="{!opty.OwnerId}"/>
    <apex:column value="{!opty.StageName}"/>
    <apex:column value="{!opty.RecordTypeId}"/>
    <apex:column value="{!opty.Design_Region__c}"/>
    <apex:column value="{!opty.Design_Territory__c}"/>
    <apex:column value="{!opty.Potential_Value1__c}"/>
    <apex:column value="{!opty.LastModifiedDate}"/>
    <apex:column value="{!opty.Probability}"/>
    <apex:column value="{!opty.StageName}"/>
    </apex:pageblockTable>
         <apex:commandButton rendered="{!setOppCon.hasPrevious}" value="First" action="{!setOppCon.first}"/>
          <apex:commandButton rendered="{!setOppCon.hasPrevious}" value="Previous" action="{!setOppCon.previous}"/>
          <apex:outputText rendered="{!(setOppCon.pageNumber * setOppCon.pageSize) < setOppCon.ResultSize}" value="{!setOppCon.pageNumber * setOppCon.pageSize} Of {!setOppCon.ResultSize}"></apex:outputText>
          <apex:outputText rendered="{!(setOppCon.pageNumber * setOppCon.pageSize) >= setOppCon.ResultSize}" value="{!setOppCon.ResultSize} Of {!setOppCon.ResultSize}"></apex:outputText>
          <apex:commandButton rendered="{!setOppCon.hasNext}" value="Next" action="{!setOppCon.next}"/>
          <apex:commandButton rendered="{!setOppCon.hasNext}" value="Last" action="{!setOppCon.last}"/>
  </apex:pageBlock>


text:
Q: wechat platform can't load vue-resource or axios code I developed a website for the WeChat Platform . The fronted website runs well on my own iphone. But these website won't work on others' phone, or the WeChat Windows version. I found if I comment out the code which related with the vue-resource or axios, the whole page worked fine. If not, the whole js file will not work.
The html code as below:
<!DOCTYPE html>

<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,user-    scalable=no" />
<title>Kindle Binding</title>

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">

                Kindle
                    Pocket

register

login

            <form class="col s12">

                        account_circle <input
                            id="icon_prefix" type="text" class="validate"
                            v-model="newUserInfo.userName" /> Username

                        phone <input
                            id="icon_telephone" type="tel" class="validate"
                            v-model="newUserInfo.phone"> Phone

                        email <input id="icon_email"
                            type="email" class="validate" v-model="newUserInfo.email">
                        Personal Email

                        lock <input
                            id="icon_password" type="password" class="validate"
                            v-model="newUserInfo.emailPwd"> Personal Email Passcode

                        email <input
                            id="icon_kindle_email" type="email" class="validate"
                            v-model="newUserInfo.kindleEmail"> Kindle Email

                <button type="button" style="float: right; margin-right: 20px"
                    class="btn waves-effect waves-light black" @click="register">
                    register
                </button>
                <button type="button" style="float: right; margin-right: 20px"
                    class="btn waves-effect waves-light black" @click="test">
                    test
                </button>
            </form>

The js file as below:
/**
 *
 */
var app = new Vue({

el: "#register",

data: {
    registerUrl: "/KindlePocket/bindingData",
    registerFlag: false,
    newUserInfo: {
        userName:'',
        phone:'',
        email:'',
        emailPwd:'',
        kindleEmail:''
    }
},

methods: {
    register: function() {
         alert("entered the register function!")
         if(this.newUserInfo.userName.trim() == ''
             || this.newUserInfo.phone.trim() == ''
             || this.newUserInfo.email.trim() == ''
             || this.newUserInfo.emailPwd.trim() == ''
             || this.newUserInfo.kindleEmail.trim() == '') {

             alert("information uncompleted!");
             return ;

         } else {
             alert("ready to register");
             axios.post(this.registerUrl, this.newUserInfo,{
                 transformRequest: [function (data) {
                        // Do whatever you want to transform the data
                        let ret = ''
                        for (let it in data) {
                          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                        }
                        return ret
                      }],
                      headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                      }
              })
              .then(function (response) {
                alert("register success");
              })
              .catch(function (error) {
                alert("register failed");
              });

         }

        // vue-resource
         /*this.$http.post(this.registerUrl, this.newUserInfo, { emulateJSON: true })
         .then((response) => {
         console.log(response.data);
         if(response.data.isBinded == 1) {
         this.registerFlag = true;
         alert("register success!");
         }
         })*/
    },
    test: function() {
        alert('test function invoked!');
    }
},
created: function() {
    alert('created function invoked!');
}
})

On my own iphone, when I click the test or register button , the js code runs well and the request send to the backend successfully, But on other phone , even the test button won't work. If I comment out the else block in the register function , all the devices runs well. When I replace axios with vue-resource, the same situation appeared. I don't know why.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Limits by Products and Equalizers The category $Cat$ of small categories is complete. Could you spell out with details the construction of the limit of a functor $F : J \to Cat$  by products and equalizers? (Mac Lane, Categories for the Working Mathematician, Chapter V, Section 2, Theorem 2)

A: The limit of a functor $F :B \to C$ can be constructed as the equalizer of
$$s,t :\prod_A FA \longrightarrow \prod_{f : A \to B}FB$$
where $s$ and $t$ are the unique morphisms defined by
$$
\pi_{(f : A \to B)}s =\pi_B\\
\pi_{(f : A \to B)}t = (Ff)\pi_A
$$
and the universal cone is given by composing with the projections of $\displaystyle\prod\limits_A FA$.
In case $C = Cat$, note that $FA$ is a category for all $A \in B$, and $s$, $t$, and $Ff$ are functors. The functor $s$ is defined on an object $(X_A)_A \in \displaystyle\prod\limits_A FA$ as
$$s((X_A)_A) = (X_B)_{f : A \to B}$$
that is, the $(f : A \to B)$-component of $s((X_A)_A)$ is $X_B$. The functor $t$ is defined on $(X_A)_A$ as
$$t((X_A)_A) = ((Ff)(X_A))_{f : A \to B}$$
On the morphisms of the product category $\displaystyle\prod\limits_A FA$ (these are families of morphisms $g_A : X_A \to Y_A$ in $FA$ for each $A \in B$), the functors $s$ and $t$ are defined by the same formulas:
$$s((g_A)_A) = (g_B)_{f:A\to B}$$
and
$$t((g_A)_A) = ((Ff)(g_A))_{f:A\to B}$$
Finally, note that the limit appears as the subcategory of $\displaystyle\prod\limits_A FA$ consisting of objects and morphisms equalized by $s$ and $t$. Explicitly, an object of the limit $L$ is $(X_A)_A \in \displaystyle\prod\limits_A FA$ such that for all $f : A \to B$ we have $X_B = (Ff)(X_A)$, and a morphism between objects $(X_A)_A$ and $(Y_A)_A$ in $L$ is a family of morphisms $(g_A : X_A \to Y_A)_A$ in $\displaystyle\prod\limits_A FA$ such that $g_B = (Ff)(g_A)$ for all $f : A \to B$.

A: Limits of categories are given by limits of their underlying graphs (forget the composition operation,) which are easy to compute when you observe that a graph is just a set-valued functor from the category $\bullet\stackrel{\to}{\to}\bullet$. Sorry for ugly typesetting.
That is, the limit of a diagram of small categories $(C_i,i\in I)$ is just the corresponding limit of the sets of morphisms $(C_i^1)$ and the sets of objects $(C_i^0)$, with source and target operations induced from those of the $C_i$. The identities are composition are naturally determined by those in the $C_i$, so if you can compute limits of sets, you can compute limits of categories. N.B. This doesn't work at all for colimits-many colimits of categories are heinous! Categories are monadic over graphs, but monadic functors don't generally preserve colimits.
To hew closer to MacLane's plan and to illustrate this, let's compute products and equalizers. Products are very straightforward: objects of $\prod C_i$ are tuples $(c_i)_{i\in I}$ and morphisms tuples $(f_i)_{i\in I}$ with $c_i$ and objects and $f_i:c_i\to c'_i$ a morphism of $C_i$. The composition is componentwise and the identity of $(c_i)$ is $(\text{id}_{c_i})$ the family of identities of the objects $c_i$. Similarly, equalizers: the equalizer of $F,G:C\to D$ has objects $c$ of $C$ such that $F(c)=G(c)$ and morphisms $f:c\to c'$ such that $F(f)=G(f)$, with identities and composition inherited from $C$. As advertised, in both cases we just take the limit of morphism sets and the limit of object sets, and connect them in the natural way. And this explicit description allows you to use the general theorem to give an explicit description of arbitrary limits of categories-which we've seen will reduce to just using the explicit description of arbitrary limits of sets, twice.


text:
Q: R-Tidying multiple columns containing data in lists I have a dataset arranged such that the data is stored as a list of multiple observations within each 'cell'. See below:
partID | Var 1 | Var 2
1      | 1,2,3 | 4,5,6
2      | 7,8,9 | 1,2,3

I would like to get the data in a format more like this:
partID | Var 1 | Var 2
1      | 1     | 4
1      | 2     | 5
1      | 3     | 6

I've been trying various combinations of melt, unlist, and data.table but I haven't had much luck applying the various ways to expand the lists while simultaneously preserving multiple columns and their names. Am I reduced to looping through the dataset and binding the columns together?

A: If for each row, the cells have the same number of entries and they are strings, then this is what you can do, using data.table.
require(data.table)
DT<-data.table(partID=c(1,2),Var1=c("1,2,3","7,8,9"),Var2=c("4,5,6","1,2,3"))

DT2<-DT[,list(Var1=unlist(strsplit(Var1,",")),Var2=unlist(strsplit(Var2,","))),by=partID]

You use strsplit() to split the strings by the commas.  You use unlist() to make the entries into a vector, not a list.
If, on the other hand, each cell is already a list, then all you need to do is unlist().
require(data.table)
DT3<-data.table(partID=c(1,2),Var1=list(c(1,2,3),c(7,8,9)),Var2=list(c(4,5,6),c(1,2,3)))

DT4<-DT3[,list(Var1=unlist(Var1),Var2=unlist(Var2)),by=partID]

Either way, you get this:
   partID Var1 Var2
      1    1    4
      1    2    5
      1    3    6
      2    7    1
      2    8    2
      2    9    3

A: We can do this easily with cSplit
library(splitstackshape)
cSplit(DT, c("Var1", "Var2"), ",", "long")
#    partID Var1 Var2
#1:      1    1    4
#2:      1    2    5
#3:      1    3    6
#4:      2    7    1
#5:      2    8    2
#6:      2    9    3

data
DT<-data.frame(partID=c(1,2),Var1=c("1,2,3","7,8,9"),Var2=c("4,5,6","1,2,3"))

A: The separate_rows() function in tidyr is the boss for observations with multiple delimited values...
# create data
library(tidyverse)
d <- data_frame(
  partID = c(1, 2),
  Var1 = c("1,2,3", "7,8,9"),
  Var2 = c("4,5,6","1,2,3")
)
d
# # A tibble: 2 x 3
#   partID  Var1  Var2
#    <dbl> <chr> <chr>
# 1      1 1,2,3 4,5,6
# 2      2 7,8,9 1,2,3

# tidy data
separate_rows(d, Var1, Var2, convert = TRUE)
# # A tibble: 6 x 3
#   partID  Var1  Var2
#    <dbl> <int> <int>
# 1      1     1     4
# 2      1     2     5
# 3      1     3     6
# 4      2     7     1
# 5      2     8     2
# 6      2     9     3

A: You can also use dplyr and tidyr which provides the unnest function to expand the columns:
library(dplyr); library(tidyr);
df %>% mutate(Var.1 = strsplit(Var.1, ","), Var.2 = strsplit(Var.2, ",")) %>% unnest()

Source: local data frame [6 x 3]

  partID Var.1 Var.2
   (dbl) (chr) (chr)
1      1     1     4
2      1     2     5
3      1     3     6
4      2     7     1
5      2     8     2
6      2     9     3


text:
Q: How to pass value during button selection in collection view? Here I am having four collection views for my home screen in which for the one of the collection view I need to pass data from one view controller to another depending on buy now button action for a particular indexpath and for clicking on cell i had given different method by using segues can anyone help me how to get indexpath for the particular cell selected button ?
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "newCell",for:indexPath) as! NewCollectionViewCell
let arr = newCategoryImageArray[indexPath.row]
let itemlist = newModel[indexPath.row]
let urls = NSURL(string: arr)
cell.imageView.hnk_setImageFromURL(urls! as URL)
cell.nameLabel.text = itemlist.name
cell.priceLabel.text = String(describing: "$ \(itemlist.price).00")
cell.buyNowButton.tag = indexPath.row
cell.buyNowButton.addTarget(self, action: #selector(<#T##@objc method#>), for: .touchUpInside)
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.layer.borderWidth = 0.7
return cell

func buyNowActionForNewCollection(button: UIButton){
let buttonPosition = button.convert(CGPoint(), to: newCollection)
let indexPath = newCollection.indexPathForItem(at: buttonPosition)

}

A: func buyNowActionForNewCollection(button: UIButton){
 let buttonPosition = button.convert(CGPoint(), to: newCollection)
 let indexPath = newCollection.indexPathForItem(at: buttonPosition)
 let yourVC = segue.destinationViewController as YourViewController;
 yourVC.passedArrayIndex = newCategoryImageArray[indexPath.row] // passedArrayIndex make the property in YourViewController
 }


text:
Q: PHP OOP Class Help I'm am unsure on how to move part of my code into a class.
 <?php
 class InfoTest {

      private $info_results;

      public function __construct() {
           $dbc = get_dbc();
           $info = $dbc->query ("SELECT info_id, info_title FROM text");
           if ($dbc->error) {
                printf("Error: %s\n", $dbc->error);
           }
           while ($info_row = $info->fetch_array())
           {
                $info_results[]= $info_row;
           }
           $info->free();
           $this->info_results = $info_results;
      }

      public function setInfo() {
           $this->info_results = $info_results;
      }

      public function getInfo() {
           return $this->info_results;
      }

      public function __destruct() {
      }

 }

  ?>
 <?php
 $display = new InfoTest();
 foreach ($display->getInfo() as $info_row) {
 ?>

 <?php echo $info_row['info_title']."
"; ?>

 Sub-Info:
 <?php
 $dbc = get_dbc();
 $si_title = $dbc->query ("SELECT info_title FROM text WHERE info_id = ".$info_row['info_id']."");
 if ($dbc->error) {
      printf("Error: %s\n", $dbc->error);
 }
 $num =$si_title->num_rows;
 $count = 0;
 while ($sub_info = $si_title->fetch_array())
 {
      $sub_info_title = $sub_info['info_title'];
      if ($count!=$num-1)
      {
           echo $sub_info_title." , ";
           $count++;
      }
      else echo $sub_info_title;
  }
 ?>

 <?php } ?>

I'm unsure how to move the Sub-Info(code after Sub-Info:) into a class. Does it go in the same class as InfoTest, a class of its own, or doesn't go into a class at all?
Sub-Info Code:
 <?php
 $dbc = get_dbc();
 $si_title = $dbc->query ("SELECT info_title FROM text WHERE info_id = ".$info_row['info_id']."");
 if ($dbc->error) {
      printf("Error: %s\n", $dbc->error);
 }
 $num =$si_title->num_rows;
 $count = 0;
 while ($sub_info = $si_title->fetch_array())
 {
      $sub_info_title = $sub_info['info_title'];
      if ($count!=$num-1)
      {
           echo $sub_info_title." , ";
           $count++;
      }
      else echo $sub_info_title;
 }
 ?>

A: In your class you have already all information. So an alternative to a sql-query could be an additional method, which searches all titles with a special id in the private field info_results. E.g.:
public function getInfoTitles($info_id) {
    $titles = array();
    foreach ($this->info_results as $info_row) {
        if ($info_row['info_id'] == $info_id)
            $titles[] = $info_row['info_title'];
        }
    }
    return $titles;
}

Your Sub-Info Code is then:
echo implode(', ', $display->getInfoTitles($info_row['info_id']));

A: The general idea of OOP is to couple data with methods that process that data. So, if you feel that some piece of your data are processed in the same way multiple times, it's a good idea to introduce a class that will incapsulate that data and logic.
Of course it emerges a lot of other questions: how many classes should one have, how should they interact with each other, which part of business logic should go in which class etc. There is no universal, always-true answer to that questions, but some general approaches to address that questions were developed: the design patterns. There are some books on the topic, one of the most known is Gang-of-Four (GoF) Design Patterns.
That's general thoughts on the topic. In your particular case, I would suggest you creating new class ItemInfo, so InfoTest class is responsible only for quering the DB and creating Instances of this new class.
 class InfoTest {

  private $items;

  public function __construct() {
      $this->items = new Array();
  }

  private function queryItems($itemId){
       $dbc = get_dbc();
       $info = $dbc->query("SELECT info_id, info_title FROM text");
       if ($dbc->error) {
            printf("Error: %s\n", $dbc->error);
       }
       while ($info_row = $info->fetch_array())
       {
            $item = new ItemInfo($info_row);
            $this->items[] = $item;
       }
       $info->free();
  }

  public function getItems($itemId){
    if (empty($this->items)){
        $this->queryItems($itemId);
    }
    return $this->items;
  }

  /* Other functions. */
  public function __destruct() {
  }
 }

Class ItemInfo{
    private $id, $title;
    function __construct(Array $params){
        $this->id = $params['item_id'];
        $this->title = $params['item_title'];
    }

    function getTitle(){
        return $this->title;
    }

    function toString(){
        retirn "I'm item {$this->id}, my title is {$this->title}";
    }
}

And your code will be as simple as
$item_test = new ItemTest();
$items = $item_test->getItems($item_id);
$titles = array();
foreach ($items as $item){
    //you may process your items in any way you need
    $titles[] = $item->getTitle();
}
echo implode(',', $titles);


text:
Q: Which force component is $F_{N3}$ on figure (2)? Here's a diagram of a man standing on a ladder that's currently fixed in position.

Forces are in equilibrium, and the ladder is static. There are two figures illustrating the forces acting on the ladder:

Fm and Fg are downward forces created due to the weight of the man and the ladder, respectively. FN1 and FN2 are the normal forces acting on the ladder from the wall and the ground. Ff is the frictional force acting on the ladder from the ground. On figure (2), there is another force, FN3, vertically acting from the wall to the ladder. Can this be considered as the frictional force acting on the ladder from the wall? Apparently the force is marked as another normal force, not frictional.

A: Imagine that the floor was frictionless. That is, $F_f=0$. If there was also no frictional force between the wall and ladder, the ladder and man would fall to the ground.
This means that $F_{N3}$ is a frictional force. The ladder is pushing against the wall at the top point, so there is a normal force perpendicular to the wall called $F_{N1}$. Since there is friction  between the wall and ladder, $F_{N3}$ acts to stop the ladder from slipping and falling (as does the other frictional force $F_{f}$ which acts horizontally). This is why $F_{N3}$ points vertically upward.
Remember that in such situations, normal forces and frictional forces are always perpendicular to each other. In the diagram you have the normal force $F_{N1}$ which is at $90^\circ$ to the wall, and so $F_{N3}$ which is perpendicular to that, should be a frictional force.


text:
Q: Python Megawidgets tab widths How to I change the default width of the tabs on a notebook page?
import tkinter  #widget library ships with Python
import Pmw      #allows access to update tkinter widgets

class TextBookGUI:
    # class constructor
    # populates each note book page
    def __init__(self, master):

        #place hash tables here

        """
         Create 5 pages on using Pmw notebook widget.
         Documenation for notebook:
         http://pmw.sourceforge.net/doc/NoteBook.html
        """

        self.nb = Pmw.NoteBook(master)
        Pmw.Color.changecolor(self.nb.component('hull'), background='blue')

        self.HomeTab = self.nb.add("Welcome")
        self.nb.tab('Welcome').focus_set()

        self.StudentTab = self.nb.add("Students")
        self.BookTab = self.nb.add("Books")
        self.LoanTab = self.nb.add("Loans")
        self.HelpTab = self.nb.add("Help")
        self.nb.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        self.nb.setnaturalsize()

        #format the house style of tabs: yellow bg and blue text
        self.nb.component('Welcome-tab').configure(font= ('Helvetica', 7 ,'bold', 'italic'), width= 30,fg= "yellow", bg="blue")

I need to set the default tab width to be wider to accomodate the tab names. I cannot access the tab width property. The last line I tried using .configure(width=30), this had no effect on the tab!

A: OK , I have got the solution , although ugly. It does manipulate tab widths.
class TextBookGUI:

# class constructor
# populates each note book page
def __init__(self, master):

    #place hash tables here

    """
     Create 5 pages on using Pmw notebook widget.
     Documenation for notebook:
     http://pmw.sourceforge.net/doc/NoteBook.html
    """
    Pmw.initialise(master)
    self.nb = Pmw.NoteBook(master,borderwidth=2,arrownavigation=True,tabpos='n')

    self.HomeTab = self.nb.add("Welcome")
    self.nb.tab('Welcome').focus_set()
    self.StudentTab = self.nb.add("Students")
    self.BookTab = self.nb.add("Books")
    self.LoanTab = self.nb.add("Loans")
    self.HelpTab = self.nb.add("Help")

    *self.nb._pageAttrs['Welcome']['tabreqwidth'] = 200
    self.nb._pageAttrs["Welcome"]['tabreqheight'] = 100
    self.nb._pageAttrs["Students"]['tabreqwidth'] = 200
    self.nb._pageAttrs["Students"]['tabreqheight'] = 100

    self.nb._pageAttrs["Books"]['tabreqwidth'] = 200
    self.nb._pageAttrs["Books"]['tabreqheight'] = 100

    self.nb._pageAttrs['Loans']['tabreqwidth'] = 200
    self.nb._pageAttrs["Loans"]['tabreqheight'] = 100

    self.nb._pageAttrs['Help']['tabreqwidth'] = 200
    self.nb._pageAttrs["Help"]['tabreqheight'] = 100*

    #format the house style of tabs: yellow bg and blue text
    self.nb.component('Welcome-tab').configure(font= ('Helviticva',20 ,'bold italic'),
                        fg= "yellow",bg="blue",wraplength=150)

    self.nb.component('Students-tab').configure(font= ('Helviticva',20 ,'bold italic'),
                        fg= "yellow",bg="blue",wraplength=150)

    self.nb.component('Books-tab').configure(font= ('Helviticva',20 ,'bold italic'),
                        fg= "yellow",bg="blue",wraplength=150)
    self.nb.component('Loans-tab').configure(font= ('Helviticva',20 ,'bold italic'),
                        fg= "yellow",bg="blue",wraplength=150)

    self.nb.component('Help-tab').configure(font= ('Helviticva',20,'bold italic'),
                        fg= "yellow",bg="blue",wraplength=150)

    self.nb.pack(fill = 'both', expand = 1, padx = 10, pady = 10)

    self.nb.setnaturalsize()

Having searched the net ,someone suggested iterating the page attribute dictionary with iterrkeys(). This  did not work so I took the code out of  the  loop and used  the attributes from the pageAttrs dictionary, which were were [reqtabwidth], [reqtabheight]. It worked!The code has stars around it and was added to the code above.You can see the text size is now 20 and it displays in a nice large tab.That is two evenings wasted for such a simple task.

A: Annoyingly, while you've correctly set the tab width within the widget (I can see it using cget('width'), the megawidget doesn't appear to honor the width setting.
However, it does resize each tab to ensure that it's wide enough to correctly display the text.  If you're not seeing the full text of each tab, it may be because the root window isn't sized wide enough to allow the full width to be displayed.  Try adding a forced size (e.g., root.geometry('500x200')) and see if that helps.
I'd love to have a better answer for you, but that's the best I can do.  Good luck!


text:
Q: Iterating over variable with jQuery not working I set this variable at the top of my page setVars = {"n":"2","m":"1","degree":"3","p":"2"}
I want to iterate over each of the elements in setVars but jquery's each() function isn't working.
Here's what I have -
$(setVars).each(function(key, value) {
  elementId = '#' + key+ '-wrapper';
}

But key is set to 0 here on the first iteration and value is set to the full setVars object here for some reason. It doesn't make it to a second iteration, it breaks when I step through it and try to go to the second iteration.

A: It should be like that I belive according to this http://api.jquery.com/jQuery.each/
$.each(setVars, function(key, value) {
  elementId = '#' + key+ '-wrapper';
});

setVars is not a collection of DOM elements, it is an object

A: You are using .each() that's meant for iterating through jQuery objects instead of $.each() that's meant for iterating through objects and arrays. Try this:
$.each( setVars, function(key, value) {
  elementId = '#' + key+ '-wrapper';
});

A: you don't need JQuery for this.  Also I could be wrong but you don't want the quotes around the name of the object properties you never see that:
setVars = {n:"2",m:"1",degree:"3",p:"2"}

And
for(i in setVars){
   console.log("key: ",i," value: ", setVars[i]); // demonstration of how to access key and value
   elementId = '#' + i + '-wrapper';
}


text:
Q: How to compare each element of multiple lists and return name of lists which are different I am having multiple lists and I need to compare each list with one another and return the name of lists which are different. We need to consider value of elements in list irrespective of their position while comparing lists.
For example:-
Lis1=['1','2','3']

Lis2=['1','2']

Lis3=['0','1','3']

Lis4=[]

Lis5=['1','2']

Output:-
['Lis1','Lis2','Lis3','Lis4']

Thanks in advance.

A: Try this:
input_lists = {"Lis1": ['1', '2', '3'], "Lis2": ['1', '2'],
               "Lis3": ['0', '1', '3'], "Lis4": [], "Lis5": ['1', '2']}

output_lists = {}

for k, v in input_lists.items():
    if sorted(v) not in output_lists.values():
        output_lists[k] = sorted(v)

unique_keys = list(output_lists.keys())
print(unique_keys)  # ['Lis1', 'Lis2', 'Lis3', 'Lis4']

A: import itertools

Lis1=['1','2','3']

Lis2=['1','2']

Lis3=['0','1','3']

Lis4=[]

Lis5=['1','2']

k=[Lis1,Lis2,Lis3,Lis4,Lis5]

k.sort()
list(k for k,_ in itertools.groupby(k))

output
[[], ['0', '1', '3'], ['1', '2'], ['1', '2', '3']]

A: a simple way to implement
Lis1=['1','2','3']
Lis2=['1','2']
Lis3=['0','1','3']
Lis4=[]
Lis5=['1','2']

lis=[Lis1,Lis2,Lis3,Lis4,Lis5]
final=[]
for ele in lis:
    if(ele not in final):
        final.append(ele)
print(final)

A: with  your given data you can use:
Lis1=['1','2','3']

Lis2=['1','2']

Lis3=['0','1','3']

Lis4=[]

Lis5=['1','2']

name_lis = {'Lis1': Lis1, 'Lis2': Lis2, 'Lis3': Lis3, 'Lis4': Lis4, 'Lis5': Lis5}
tmp = set()
response = []

for k, v in  name_lis.items():
    s = ''.join(sorted(v))
    if s not in tmp:
        tmp.add(s)
        response.append(k)

print(response)

output:
['Lis1', 'Lis2', 'Lis3', 'Lis4']

name_lis dictionary contains the name of your list and the actual list,  you are iterating over each list, and for each list, you are sorting the elements and then converting in a string, if the string was encountered before you  know that the list is a duplicate if not you are adding the list to the response


text:
Q: Custom Loop in Page Admin Causing Other Fields to Fail I created a custom loop in the page admin section to manage a custom post type called "widgets" for that page.
$ps_widget_list = get_post_meta( $post_id, 'ps_widget_list', true ); //first get the list of current widgets

$active_widget_array = explode( ', ', $ps_widget_list ); //then separate those widgets into an array of active widgets

// this array is for the UI. It will build a list of all the widgets
// then based on the array of active widgets, will separate them into
// two different arrays to be used later
$widgets_array = array(

    'active' => array(),
    'inactive' => array()

);

//get all the widgets
$args = array(

    'post_type' => 'ps_widgets',
    'posts_per_page' => '-1'

);

$the_query = new WP_Query( $args );

while ( $the_query->have_posts() ) : $the_query->the_post(); // loop through the widgets

    $widget_id = get_the_ID();

    // if the widget's id is in the array of active widgets
    // mark it as active, if not mark as inactive and store to the array
    $key = ( in_array( $widget_id, $active_widget_array) ) ? 'active' : 'inactive';

    $widgets_array[ $key ][ $widget_id ] = array(

        'id' => $widget_id,
        'title' => get_the_title( $widget_id )

    );

endwhile;
wp_reset_postdata();

The issue arises when I try to add an SEO title, description, or keywords in an an SEO plugin. I tried this on both Yoast and All in One. After disabling different sections of code, I narrowed the issue to this loop. I also tried namespacing the variables too, but no luck. I assume its an issue with the loop being called, any suggestions?

A: Switched the loop from using to WP_Query to get_posts.

A: I also encountered side effects with using WP_Query in wordpress admin.
I used two Wp_Query in a custom metabox, which worked well but i later discovered two strange problems:

*

*the slug of the post was automatically set even for the new post

*featured image was automatically set like the slug and new set featured image wasn't saved

After several hours of debugging, I came up with a solution using wp_reset_query();
However this didn't completely solved the problem.Still, the featured image wasn't saving.
What the ** was wrong?
Then I came up with this solution. Use native PHP code and Don't mess with WP template tags  ie,
$your_loop= new WP_Query($args);

Instead of
 if( $your_loop->have_posts()){
     while ($your_loop->have_posts()) {

        //the_title();
        ...
        //WP loop template tags
     }
 }

use  following:
 if( count($your_loop->posts) > 0) {
     foreach( $your_loop->posts as $item_post) {

        //$item_post->post_title
        // see other available using print_r($item_post)
        //
     }
 }


text:
Q: Data save coding problems this is spider
#-*-coding:utf-8-*-
import scrapy
from scrapy_test.items import ScrapyTestItem
class QiushiSpider(scrapy.Spider):
    name = "qiushibaike"
    start_urls = {
         "http://www.qiushibaike.com",
    }
    def parse(self, response):
        item = ScrapyTestItem()
        for temp in response.xpath(".//div[@id='content']//div[@id='content-left']/div"):
            # a = str(map(str, ''.join(temp.xpath(".//div[@class='content']/span/text()").extract())))
            item['text'] = temp.xpath(".//div[@class='content']/span/text()").extract()
            item['number'] = temp.xpath(".//div[@class='stats']/span[@class='stats-vote']/i/text()").extract()
            yield item

This is the pipeline that holds the data
import json
from scrapy.exceptions import DropItem
class ScrapyTestPipeline(object):
    def __init__(self):
        self.ids_seen = set()
        self.file = open("aaa.jl", "w",encoding='utf8' )
    def process_item(self, item, spider):
        item['id'] = hash(''.join(item['text']))
        if item['id'] in self.ids_seen:
            raise DropItem("Duplicate item found: %s " % item)
        else:
            line = json.dumps(dict(item)) + "\n"
            self.file.write(line)
            return item

I tried to save the data, but the data encoding went wrong.I tried to do it in other ways, but I failed. What should I do?
this is error data
"text": ["\n\n\nlz\u7537\uff0c\u4eca\u5929\u8ddf\u670b\u53cb\u53bbktv\u5531\u6b4c\uff01]

A: How did you run your scraper? you are saving data into JSON/CSV by using scrapy's default exporters?
Do this in settings.py
FEED_EXPORT_ENCODING = 'utf-8'

A: #-*-coding:utf-8-*-
import scrapy
from scrapy_test.items import ScrapyTestItem
import re
class QiushiSpider(scrapy.Spider):
    name = "qiushibaike"
    start_urls = {
         "http://www.qiushibaike.com",
    }
    def parse(self, response):
        item = ScrapyTestItem()
        for temp in response.xpath(".//div[@id='content']//div[@id='content-left']/div"):
            a = temp.xpath(".//div[@class='content']/span")
            id = temp.xpath('.//@id').extract_first('')
            item['id'] = re.search('[0-9]*$', id).group(0)
            item['text'] = (''.join(a.xpath("string(.)").extract())).strip().encode('utf-8')
            item['number'] = temp.xpath(".//div[@class='stats']/span[@class='stats-vote']/i/text()").extract_first('')
            yield item

this is pipeline
# -*- coding: utf-8 -*-
from scrapy.exceptions import DropItem
class ScrapyTestPipeline(object):
    def __init__(self):
        self.ids_seen = set()
        self.file = "liu.jl"
    def process_item(self, item, spider):
        if item['id'] in self.ids_seen:
            raise DropItem("Duplicate item found: %s " % item)
        else:
            self.ids_seen.add(item['id'])
            with open(self.file, 'a',encoding='utf-8') as f:
                f.write('text: '+item['text'].decode() + '\n')
                f.write('number '+item['number'] + '\n')
                f.write('id '+item['id'] + '\n\n')
            return item


text:
Q: Unplugging disk during error checking I'm currently running a check disk on my external hard drive, and it's in phase 4 with no visible progress on the progress bar. Unfortunately, I have to turn off the computer that's running the test. Will shutting off/unplugging the hard drive prematurely cause the drive any harm?

A: Put your ear on the drive case and listen for a minute, if you hear no sounds of the read/write heads moving, unplug it, modern drives are very tolerant of unexpected shut downs regardless of when it happens, the only side effect could be corrupt data or an unbootable system drive.
If you hear a repetitious clicking at regular intervals, the drive may have suffered the click of death. Unplug it.

On a hard disk drive, the click of death refers to a similar phenomenon; the head actuator may click as the drive repetitively tries to recover from one or more errors. The clicking sounds can be the heads repetitively loading or unloading, or they can be the sounds of the actuator striking a stop, or both


text:
Q: How to retrieve an attribute value after closing a window in PyQt? I am creating a window inside a MainWindow in PYQT5. Once I close the new created window , how to retrieve the attributes of it in main window ? I am new to PYQT. Please suggest me if I am wrong with the approach of creating a window inside a window
MainWindow File
class AssignmentSectionWindow (object):

    courseID = ''
    semester = ''

    def __init__(self, courseID, semester):
        self.courseID = courseID
        self.semester = semester

    def setupUi(self, assignmentSection):
        assignmentSection.setObjectName("assignmentSection")
        assignmentSection.resize(665, 506)
        self.centralwidget = QtWidgets.QWidget(assignmentSection)
        self.centralwidget.setObjectName("centralwidget")
        self.assignmentLabel = QtWidgets.QLabel(self.centralwidget)
        self.assignmentLabel.setGeometry(QtCore.QRect(30, 20, 231, 31))
        self.assignmentLabel.setObjectName("assignmentLabel")
        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(20, 60, 591, 321))
        self.widget.setObjectName("widget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.listWidget = QtWidgets.QListWidget(self.widget)
        self.listWidget.setObjectName("listWidget")
        self.horizontalLayout.addWidget(self.listWidget)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
        self.verticalLayout.setContentsMargins(-1, 0, 0, 200)
        self.verticalLayout.setObjectName("verticalLayout")
        self.addAssignmentButton = QtWidgets.QPushButton(self.widget)
        self.addAssignmentButton.setObjectName("addAssignmentButton")
        self.verticalLayout.addWidget(self.addAssignmentButton)
        self.editAssignmentButton = QtWidgets.QPushButton(self.widget)
        self.editAssignmentButton.setObjectName("editAssignmentButton")
        self.verticalLayout.addWidget(self.editAssignmentButton)
        self.deleteAssignmentButton = QtWidgets.QPushButton(self.widget)
        self.deleteAssignmentButton.setObjectName("deleteAssignmentButton")
        self.verticalLayout.addWidget(self.deleteAssignmentButton)
        self.horizontalLayout.addLayout(self.verticalLayout)
        assignmentSection.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(assignmentSection)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 665, 22))
        self.menubar.setObjectName("menubar")
        assignmentSection.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(assignmentSection)
        self.statusbar.setObjectName("statusbar")
        assignmentSection.setStatusBar(self.statusbar)

        self.retranslateUi(assignmentSection)
        QtCore.QMetaObject.connectSlotsByName(assignmentSection)

        self.addAssignmentButton.clicked.connect(lambda: (self.addAssignment()))

    def addAssignment(self):

        self.window = QtWidgets.QMainWindow()
        self.ui = AddAssignmentWindow(self.courseID,self.semester)
        self.ui.setupUi(self.window)
        self.window
        ```
        print(self.ui.fileName)

    def editAssignment(self):
        pass

    def deleteAssignment(self):
        pass

    def retranslateUi(self, assignmentSection):
        _translate = QtCore.QCoreApplication.translate
        assignmentSection.setWindowTitle(_translate("assignmentSection", "Assignment Section"))
        self.assignmentLabel.setText(_translate("assignmentSection", "Assignments of " + CommonUtils.getCourseNameFromCourseID(self.courseID)))
        self.addAssignmentButton.setText(_translate("assignmentSection", "Add Assignment"))
        self.editAssignmentButton.setText(_translate("assignmentSection", "Edit Assignment"))
        self.deleteAssignmentButton.setText(_translate("assignmentSection", "Delete Assignment"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    assignmentSection = QtWidgets.QMainWindow()
    ui = AssignmentSectionWindow("101","Fall2019")
    ui.setupUi(assignmentSection)
    assignmentSection.show()
    sys.exit(app.exec_())

Created this window inside the main window
class AddAssignmentWindow(object):

    filePath = ''
    fileName = ''
    couresID = ''
    semester = ''

    def __init__(self, courseID, semester):
        self.courseID = courseID
        self.semester = semester

    def setupUi(self, AddAssignment):
        AddAssignment.setObjectName("AddAssignment")
        AddAssignment.resize(644, 518)
        self.centralwidget = QtWidgets.QWidget(AddAssignment)
        self.centralwidget.setObjectName("centralwidget")

        self.submitButton = QtWidgets.QPushButton(self.centralwidget)
        self.submitButton.setGeometry(QtCore.QRect(280, 400, 113, 32))
        self.submitButton.setObjectName("submitButton")

        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(30, 40, 113, 191))
        self.widget.setObjectName("widget")

        self.verticalLayout = QtWidgets.QVBoxLayout(self.widget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")

        self.assignmentNameLabel = QtWidgets.QLabel(self.widget)
        self.assignmentNameLabel.setObjectName("assignmentNameLabel")

        self.verticalLayout.addWidget(self.assignmentNameLabel)

        self.dueLabel = QtWidgets.QLabel(self.widget)
        self.dueLabel.setObjectName("dueLabel")
        self.verticalLayout.addWidget(self.dueLabel)

        self.uploadFileLabel = QtWidgets.QLabel(self.widget)
        self.uploadFileLabel.setObjectName("uploadFileLabel")
        self.verticalLayout.addWidget(self.uploadFileLabel)
        self.descriptionLabel = QtWidgets.QLabel(self.widget)
        self.descriptionLabel.setObjectName("descriptionLabel")
        self.verticalLayout.addWidget(self.descriptionLabel)
        self.widget1 = QtWidgets.QWidget(self.centralwidget)
        self.widget1.setGeometry(QtCore.QRect(160, 50, 231, 351))
        self.widget1.setObjectName("widget1")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget1)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.assignmentNameLine = QtWidgets.QLineEdit(self.widget1)
        self.assignmentNameLine.setObjectName("assignmentNameLine")
        self.verticalLayout_2.addWidget(self.assignmentNameLine)
        spacerItem = QtWidgets.QSpacerItem(20, 28, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem)
        self.dueLine = QtWidgets.QDateTimeEdit(self.widget1)
        self.dueLine.setCalendarPopup(True)
        # TODO: self.dueLine.setDate(QtCore.QDateTime.currentDateTime())
        self.dueLine.setObjectName("dueLine")
        self.verticalLayout_2.addWidget(self.dueLine)
        spacerItem1 = QtWidgets.QSpacerItem(20, 18, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem1)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.uploadFileNameLine = QtWidgets.QLineEdit(self.widget1)
        self.uploadFileNameLine.setObjectName("uploadFileNameLine")
        self.horizontalLayout.addWidget(self.uploadFileNameLine)
        self.browseButton = QtWidgets.QPushButton(self.widget1)
        self.browseButton.setObjectName("browseButton")
        self.horizontalLayout.addWidget(self.browseButton)
        self.verticalLayout_2.addLayout(self.horizontalLayout)
        self.desciptionText = QtWidgets.QTextEdit(self.widget1)
        self.desciptionText.setObjectName("desciptionText")
        self.verticalLayout_2.addWidget(self.desciptionText)
        spacerItem2 = QtWidgets.QSpacerItem(20, 28, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem2)
        AddAssignment.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(AddAssignment)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 644, 22))
        self.menubar.setObjectName("menubar")
        AddAssignment.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(AddAssignment)
        self.statusbar.setObjectName("statusbar")
        AddAssignment.setStatusBar(self.statusbar)

        self.retranslateUi(AddAssignment)
        QtCore.QMetaObject.connectSlotsByName(AddAssignment)

        self.browseButton.clicked.connect(lambda: (self.browserFile()))

        self.submitButton.clicked.connect(lambda: (self.submitButtonFunction()))

    def browserFile(self):
        options = QFileDialog.Options()
        self.filePath, _ = QFileDialog.getOpenFileName(None, "Open file", "~/Desktop", '', '', options=options)
        if (len(self.filePath) != 0):
            print("File Path is", self.filePath)
            self.fileName = QFileInfo(self.filePath).fileName()
            self.uploadFileNameLine.setText(self.fileName)

    def submitButtonFunction(self):
        assignmentName =self.assignmentNameLine.text()
        assignmentDue = self.dueLine.text()
        description = self.desciptionText.toPlainText()
        isSucess = AssignmentDB.postAssignmentToDB(self.courseID, assignmentName, self.filePath, self.fileName, assignmentDue, description, self.semester)
        if (isSucess):
            CommonUIUtils.showSuccessMessage("Successfully added Assignment")

    def retranslateUi(self, AddAssignment):
        _translate = QtCore.QCoreApplication.translate
        AddAssignment.setWindowTitle(_translate("AddAssignment", "Add Assignment"))
        self.submitButton.setText(_translate("AddAssignment", "Submit"))
        self.assignmentNameLabel.setText(_translate("AddAssignment", "Assignment Name"))
        self.dueLabel.setText(_translate("AddAssignment", "Assignment Due"))
        self.uploadFileLabel.setText(_translate("AddAssignment", "Upload File"))
        self.descriptionLabel.setText(_translate("AddAssignment", "Description"))
        self.browseButton.setText(_translate("AddAssignment", "Browse"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    AddAssignment = QtWidgets.QMainWindow()
    ui = AddAssignmentWindow()
    ui.setupUi(AddAssignment)
    AddAssignment.show()
    sys.exit(app.exec_()))

I need to access AddAssignmentWindow's attribute FileName inside AssignmentSectionWindow

A: You must take into account the following good practices in Qt/PyQt:

*

*Do not modify the code generated by Qt Designer as indicated by the message: # WARNING! All changes made in this file will be lost! When you generate the .py using pyuic because if you modify the design all the written code will be erased. Also another reason is that the class generated by Qt Designer is not a widget, but an interface class that serves to fill a widget. More information here.

*If you want to make a widget that serves to make a form use a QDialog since it allows to know when the application is closed, and the choice of the user through the method exec_().

*Use the layouts to set the elements.

*Do not use the lambda method if they are not necessary.

*Use the decoration @QtCore.pyqtSlot() in the functions that connect to the signals since it has several advantages indicated in the docs.
Considering the above, your project should be of the following structure:
.
├── AddAssignmentDialog.py
├── AssignmentSectionWindow.py
└── uis
    ├── AddAssignmentDialog.ui
    └── AssignmentSectionWindow.ui

AddAssignmentDialog.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>AddAssignmentDialog</class>
 <widget class="QDialog" name="AddAssignmentDialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <layout class="QFormLayout" name="formLayout_4">
   <item row="0" column="0">
    <widget class="QLabel" name="assignmentNameLabel">
     <property name="text">
      <string>Assignment Name</string>
     </property>
    </widget>
   </item>
   <item row="0" column="1">
    <widget class="QLineEdit" name="assignmentNameLine"/>
   </item>
   <item row="1" column="0">
    <widget class="QLabel" name="dueLabel">
     <property name="text">
      <string>Assignment Due</string>
     </property>
    </widget>
   </item>
   <item row="1" column="1">
    <widget class="QLineEdit" name="dueLine"/>
   </item>
   <item row="2" column="0">
    <widget class="QLabel" name="uploadFileLabel">
     <property name="text">
      <string>Upload File</string>
     </property>
    </widget>
   </item>
   <item row="2" column="1">
    <layout class="QHBoxLayout" name="horizontalLayout">
     <item>
      <widget class="QLineEdit" name="uploadFileNameLine"/>
     </item>
     <item>
      <widget class="QPushButton" name="browseButton">
       <property name="text">
        <string>Browse</string>
       </property>
      </widget>
     </item>
    </layout>
   </item>
   <item row="3" column="0">
    <widget class="QLabel" name="descriptionLabel">
     <property name="text">
      <string>Description</string>
     </property>
    </widget>
   </item>
   <item row="3" column="1">
    <widget class="QTextEdit" name="descriptionText"/>
   </item>
   <item row="4" column="1">
    <layout class="QHBoxLayout" name="horizontalLayout_2">
     <item>
      <spacer name="horizontalSpacer">
       <property name="orientation">
        <enum>Qt::Horizontal</enum>
       </property>
       <property name="sizeHint" stdset="0">
        <size>
         <width>40</width>
         <height>20</height>
        </size>
       </property>
      </spacer>
     </item>
     <item>
      <widget class="QPushButton" name="submitButton">
       <property name="sizePolicy">
        <sizepolicy hsizetype="Maximum" vsizetype="Fixed">
         <horstretch>0</horstretch>
         <verstretch>0</verstretch>
        </sizepolicy>
       </property>
       <property name="text">
        <string>Submit</string>
       </property>
      </widget>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>

AssignmentSectionWindow.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>AssignmentSectionWindow</class>
 <widget class="QMainWindow" name="AssignmentSectionWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Assignment Section</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QGridLayout" name="gridLayout">
    <item row="0" column="0">
     <widget class="QLabel" name="assignmentLabel">
      <property name="text">
       <string>Assignments of %n </string>
      </property>
     </widget>
    </item>
    <item row="1" column="0">
     <widget class="QListWidget" name="listWidget"/>
    </item>
    <item row="1" column="1">
     <layout class="QVBoxLayout" name="verticalLayout">
      <item>
       <widget class="QPushButton" name="addAssignmentButton">
        <property name="text">
         <string>Add Assignment</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QPushButton" name="editAssignmentButton">
        <property name="text">
         <string>Edit Assignment</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QPushButton" name="deleteAssignmentButton">
        <property name="text">
         <string>Delete Assignment</string>
        </property>
       </widget>
      </item>
      <item>
       <spacer name="verticalSpacer">
        <property name="orientation">
         <enum>Qt::Vertical</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>20</width>
          <height>40</height>
         </size>
        </property>
       </spacer>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>23</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

Then you convert the .ui to .py:
pyuic5 uis/AddAssignmentDialog.ui -o AddAssignmentDialog_ui.py
pyuic5 uis/AssignmentSectionWindow.ui -o AssignmentSectionWindow_ui.py

Obtaining the following structure:
.
├── AddAssignmentDialog.py
├── AddAssignmentDialog_ui.py
├── AssignmentSectionWindow.py
├── AssignmentSectionWindow_ui.py
└── uis
    ├── AddAssignmentDialog.ui
    └── AssignmentSectionWindow.u

AddAssignmentDialog.py
from PyQt5 import QtCore, QtGui, QtWidgets

from AddAssignmentDialog_ui import Ui_AddAssignmentDialog

class AddAssignmentDialog(QtWidgets.QDialog, Ui_AddAssignmentDialog):
    def __init__(self, parent=None):
        super(AddAssignmentDialog, self).__init__(parent)
        self.setupUi(self)
        self.filename = ""

        self.browseButton.clicked.connect(self.browserFile)
        self.submitButton.clicked.connect(self.accept)

    @QtCore.pyqtSlot()
    def browserFile(self):
        self.filename, _ = QtWidgets.QFileDialog.getOpenFileName(
            None,
            "Open file",
            QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.DesktopLocation),
            "",
            "",
        )
        if self.filename:
            finfo = QtCore.QFileInfo(self.filename)
            self.uploadFileNameLine.setText(finfo.fileName())

    def get_assignment(self):
        assignmentName = self.assignmentNameLine.text()
        assignmentDue = self.dueLine.text()
        description = self.descriptionText.toPlainText()
        return {"name": assignmentName, "due": assignmentDue, "description": description}

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = AddAssignmentDialog()
    w.show()
    sys.exit(app.exec_())

AssignmentSectionWindow.py
from PyQt5 import QtCore, QtGui, QtWidgets

from AssignmentSectionWindow_ui import Ui_AssignmentSectionWindow
from AddAssignmentDialog import AddAssignmentDialog

class AssignmentSectionWindow(QtWidgets.QMainWindow, Ui_AssignmentSectionWindow):
    def __init__(self, parent=None):
        super(AssignmentSectionWindow, self).__init__(parent)
        self.setupUi(self)
        self.addAssignmentButton.clicked.connect(self.addAssignment)
        self.assignmentLabel.setText("Assignments of xxx")

    @QtCore.pyqtSlot()
    def addAssignment(self):
        w = AddAssignmentDialog()
        if w.exec_() == QtWidgets.QDialog.Accepted:
            data = w.get_assignment()
            print(data)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = AssignmentSectionWindow()
    w.show()
    sys.exit(app.exec_())

The complete example can be found here


text:
Q: How to click a non ID java button in my c# browser? I have a c# program which has a web browser my program deals with java pages i want it to click a button in a page but the button has no ID or value  all i got about it is  this code :
  td class="submit">

   <button class="fixedSizeBigButton" type="submit">

please is there any way to click that button
and for  http://watin.sourceforge.net/   i need a code
thanks a lot

A: Your button has a class name,you can find your button using class name,see this example:
private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.DocumentText = "
<button   class=\"fixedSizeBigButton\" type=\"submit\">	";
        webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
    }

    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        foreach (HtmlElement btn in webBrowser1.Document.GetElementsByTagName("button"))
        {
            if (btn.GetAttribute("ClassName") == "fixedSizeBigButton")
            {
                btn.InvokeMember("Click");
            }
        }
    }

A: I found this link when I went looking around.
More looking around leads me to believe you need to look more into the entire Find class itself.  I know there are other ways to locate elements.
I'm trying to locate the documentation that will let me construct some code, since I've never actually used this before :-)  I'll update if/when I get something more.
Update
Looks like you aren't the only one having similar issues.  You can apparently Chain find methods.  WatiN - Find HTML Table  Which seems rather useful, if you know more about the button's exact location.  Using Find.ByClass along with something else, to try to define the button uniquely.


text:
Q: I don't know how to change a color in a d3.js US map when hovered over I have this map of the USA. I know how to bind other data, change colors of states but the only thing I don't know how to change the default orangish color when a state is hovered over.
You can find it here as well: http://blockbuilder.org/malcolm-decuire/34d2ce39d3b8c2f8a577
<!DOCTYPE html>
<meta charset="utf-8">

 American Lynches | 1830-1970

A: According to the documentation, it's controlled by the highlightFillColor config option:
geographyConfig:{
  highlightFillColor: '#FC8D59'
}


text:
Q: Displaying JSON array data as a listview I have a JSON array that I am trying to display. I was able to succesfully display it as a textview, however not all of the data is listed. only the last. Which is "Remember tomorrow we will be giving out popcorn and some more water bottles at our office! Tuesday, we will give you free breakfast! Please sign up to be a CSA volunteer when coming to get some free food!". I believe that it would be more efficient to list it as a listview however, I everything that I am reading from online websites isn't working.
DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://ec2-54-213-155-95.us-west-2.compute.amazonaws.com/notices.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");

InputStream inputStream = null;
String result = null;
try {
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    inputStream = entity.getContent();
    // json is UTF-8 by default
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }
    result = sb.toString();
} catch (Exception e) {
    // Oops
}
finally {
    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}

try {
    JSONObject jObject = new JSONObject(result);
    JSONArray jsonArray = jObject.getJSONArray("notices");
    for(int i = 0; i < jsonArray.length(); i++) {
        String arrayString = jsonArray.getString(i);
        Log.d("notices", arrayString);
        ListView listView1 = (ListView) findViewById(R.id.listView1);

} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Basicly I want to display this as a listview !

A: First you should think about doing this in an async task.
Second to display it in a lsitview is relatively easy. You can do something like this:
public class YourActivity extends Activiy{
   public void getJson(String selection, String url) {
           new LoadJsonTask().execute( selection, url);

   }
   private class LoadJsonTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>> > {
       ProgressDialog dialog ;
       protected void onPreExecute (){
            dialog = ProgressDialog.show(YourActivity.this ,"title","message");

       }
       protected ArrayList<HashMap<String, String>> doInBackground (String... params){
           return doGetJson(params[0],params[1]);
       }
       protected void onPostExecute(ArrayList<HashMap<String, String>> mylist){

            ListAdapter adapter = new JsonAdapter(YourActivity.this, mylist, R.layout.list,
              new String[] { "name", "text", "ts"}, new int[] { R.id.item_title,
                R.id.item_subtitle, R.id.timestamp});
            setListAdapter(adapter);
            dialog.dismiss();
       }
    }

 public ArrayList<HashMap<String, String>> doGetJson(String selection, String url) {
     JSONObject json = null;
     String formatedcat = selection.toLowerCase();
     ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     json = JSONfunctions
        .getJSONfromURL(url);
     try {
    //the array title that you parse
    JSONArray category = json.getJSONArray(formatedcat);
    for (int i = 0; i < category.length(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        JSONObject c = category.getJSONObject(i);
        map.put("id", String.valueOf(i));
        map.put("name",
                c.getString("title"));
        //map.put("text",c.getString("title"));
        map.put("ts",c.getString("run_date") );
        map.put("image","http:"+c.getString("url"));
        mylist.add(map);
    }
} catch (JSONException e) {

}
   return mylist;
  ....
}

The important part of the code is:
 ListAdapter adapter = new JsonAdapter(YourActivity.this, mylist, R.layout.list,
              new String[] { "name", "text", "ts"}, new int[] { R.id.item_title,
                R.id.item_subtitle, R.id.timestamp});
            setListAdapter(adapter);

This is where you are setting the string array to the hashmap you created from the json object and setting the list adapter with it so the listview will display all the relevant data. See more with this question.


text:
Q: How can I have two different "processes" for the same entity accessing the same outputs in VHDL? I have an entity which looks at five pairs of switches and sets letters on a 7-segment display based on the state of those switches (H for 00, E for 01, L for 10 and, O for 11).
I have a process in the architecture of this file which has a case statement that looks at the values of the switches and writes the proper letter to the corresponding display.
Now, I also have three switches that will, depending on their states, move the letters to adjacent 7-segment displays (like a rotation). I originally had this in another process within the same architecture, but I get compilation errors because I'm using the outputs (the 7-segment displays) in two different places.
I'm completely new to VHDL so this may seem simple, but how do I separate these two functions? Do they need to be in different files? How to have them both run "concurrently"?

A: Something like this  (Warning it hasn't been debugged, it analyzes and elaborates).
What this shows is that there are registers for the display digits and that rotation function  operates between the output of those registers and the driven display digit ports.
The rot_select could of course be separated from the write pointer.
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;   -- TO_INTEGER

entity rot_digits is
    port (
    -- the 8 7-segment display with defaults for simulation visibility.
        dp0:    out std_logic_vector (6 downto 0) := "0000001"; -- 0
        dp1:    out std_logic_vector (6 downto 0) := "1001111"; -- 1
        dp2:    out std_logic_vector (6 downto 0) := "0010010"; -- 2
        dp3:    out std_logic_vector (6 downto 0) := "0000110"; -- 3
        dp4:    out std_logic_vector (6 downto 0) := "1001100"; -- 4
        dp5:    out std_logic_vector (6 downto 0) := "0100100"; -- 5
        dp6:    out std_logic_vector (6 downto 0) := "0100000"; -- 6
        dp7:    out std_logic_vector (6 downto 0) := "0001111"; -- 7
  -- rotation select, also used for write pointer
        rot_select: in  std_logic_vector(2 downto 0);
        wr_enab:    in  std_logic;
        reset:      in  std_logic;
        switch:     in  std_logic_vector(1 downto 0)
    );
    type display8 is array (integer range 0 to 7) of
            std_logic_vector(6 downto 0);

    constant H:         std_logic_vector (6 downto 0) := "1001000"; -- H
    constant E:         std_logic_vector (6 downto 0) := "0110000"; -- E
    constant L:         std_logic_vector (6 downto 0) := "1110001"; -- L
    constant O:         std_logic_vector (6 downto 0) := "0000001"; -- O (0)
    constant ERR:       std_logic_vector (6 downto 0) := "0110110"; -- error
    constant BLANK:     std_logic_vector (6 downto 0) := "1111111";

end entity;

architecture foo of rot_digits is

    -- digit is (a,b,c,d,e,f,g)  6 downto 0, '0' for ON (sink)
    --    a
    --   f  b
    --    g
    --   e  c
    --    d

    -- (d0,d1,d2,d3,d4,d5,d6,d7) are register values for stored digits
    signal d0:          std_logic_vector (6 downto 0);
    signal d1:          std_logic_vector (6 downto 0);
    signal d2:          std_logic_vector (6 downto 0);
    signal d3:          std_logic_vector (6 downto 0);
    signal d4:          std_logic_vector (6 downto 0);
    signal d5:          std_logic_vector (6 downto 0);
    signal d6:          std_logic_vector (6 downto 0);
    signal d7:          std_logic_vector (6 downto 0);

    function "ror" (l: display8; r: std_logic_vector(2 downto 0))
        return display8 is
        variable rot: integer range 0 to 7;
    begin
        if IS_X(TO_X01(r)) then   -- unknown defaults to 0 rotation
            rot := 0;
        else
            rot := to_integer(unsigned(r));
        end if;

        case rot is
            when 0 => return l;
            when 1 => return
                display8'(l(0),l(7),l(6),l(5),L(4),l(3),l(2),l(1));
            when 2 => return
                display8'(l(1),l(0),l(7),l(6),l(5),L(4),l(3),l(2));
            when 3 => return
                display8'(l(2),l(1),l(0),l(7),l(6),l(5),L(4),l(3));
            when 4 => return
                display8'(l(3),l(2),l(1),l(0),l(7),l(6),l(5),L(4));
            when 5 => return
                display8'(l(4),l(3),l(2),l(1),l(0),l(7),l(6),l(5));
            when 6 => return
                display8'(l(5),l(4),l(3),l(2),l(1),l(0),l(7),l(6));
            when 7 => return
                display8'(l(6),l(5),l(4),l(3),l(2),l(1),l(0),l(7));
        end case;
    end function;

    signal selected:   std_logic_vector (6 downto 0);

begin

SEL:
    selected <= H    when switch = "00" else
                E    when switch = "01" else
                L    when switch = "10" else
                O    when switch = "11" else
                ERR;

ROTATE:
    (dp0,dp1,dp2,dp3,dp4,dp5,dp6,dp7)
            <= display8'(d0,d1,d2,d3,d4,d5,d6,d7) ror rot_select;

Display_Registers:
    process (wr_enab,reset, switch)
    begin
        if (reset = '1') then
            (d0,d1,d2,d3,d4,d5,d6,d7) <= display8'(others => BLANK);
        elsif (wr_enab = '1') then
            case rot_select  is
                when "000" => d0 <= selected;
                when "001" => d1 <= selected;
                when "010" => d2 <= selected;
                when "011" => d3 <= selected;
                when "100" => d4 <= selected;
                when "101" => d5 <= selected;
                when "110" => d6 <= selected;
                when "111" => d7 <= selected;
                when others =>
                    (d0,d1,d2,d3,d4,d5,d6,d7) <= display8'(others => ERR);
             end case;

        end if;
    end process;

end architecture;

The ERR assignments are to show there's an other than '0' or '1' either in the rot_select or switch vectors.  Should be three horizontal bars.
By definition there's an equivalent process for the concurrent signal assignment to the display digit output ports.  You could likewise have that process perform the rotations without a newly declared "ror" shift operator.

A: If you drive a signal from two different processes, the two drivers will "compete".
For bit and std_ulogic types, the compiler will complain that you are not allowed to have two drivers on a signal.  If you are using std_logic types, then there is a "resolution function" which decides what the resulting value is when you drive two different values onto a signal.  For example, if you drive a 0 and a 1, you'll get  the defined-unknown result X.
It is possible to drive Z (high-impedance) onto a signal to allow another signal to override it, however, if you want to synthesise it you need to check what your tools will do with it as very few chips these days can actually have real high-impedance modes on their internal signals.
A portable, tidy, synthesisable way to achieve what you want is to treat a logic 1 as less-strong than a logic-0.  Then you can combine two separate signals with an AND gate:
process1: process
begin
   sig1 <= '1'; -- not driving
   -- some statemachine eventually does
     sig1 <= '0';
   -- and then
     sig1 <= '1'; -- when it's finished
end process;

process2: process
begin
    sig2 <= '1'; -- not driving
       --- similarly...
       sig2 <= '0'; -- at some point
end process;

actual_sig <= sig1 and sig2;

If it makes more sense for your purposes for a 0 to be the 'idle' state, then use an 'or' instead to merge the signals together.

A: I'll try to focus more on solving your problem than answering your original question. For a good answer to your question, see Martin's (@martin-thompson) post.
The key to the presented solution is to generate an intermediary signal, which will hold the 'rotated' letters. In short:

*

*signal #1 <= an array of letters, without rotation, selected directly form your pairs of switches

*signal #2 <= an array of rotated letters; the amount of rotation comes from you 'rotation' switches

This way, we can have one process that generates signal #1, and another taht generates signal #2. It is usually better to structure your solution so that each signal is assigned from within a single process.
The code below should solve your problem:
entity switches_to_7seg is
    port (
        -- each switch pair selects one letter from 'H', 'E', 'L', 'O'
        switch_pair_0: in bit_vector(1 downto 0);
        switch_pair_1: in bit_vector(1 downto 0);
        switch_pair_2: in bit_vector(1 downto 0);
        switch_pair_3: in bit_vector(1 downto 0);
        switch_pair_4: in bit_vector(1 downto 0);
        -- the rotation switches select the amount of rotation from 0 to 4
        rotate_switches: in bit_vector(2 downto 0);
        -- the outputs are five 7-segment displays
        lcd_display_0: out bit_vector(6 downto 0);
        lcd_display_1: out bit_vector(6 downto 0);
        lcd_display_2: out bit_vector(6 downto 0);
        lcd_display_3: out bit_vector(6 downto 0);
        lcd_display_4: out bit_vector(6 downto 0)
    );
end;

architecture dataflow of switches_to_7seg is

    -- declare an enumerated type to make it easier working with the output letters
    type output_letter_type is ('H', 'E', 'L', 'O');
    type output_letter_vector_type is array (natural range <>) of output_letter_type;

    -- this comes directly from the switches
    signal switch_selected_letters: output_letter_vector_type(0 to 4);
    -- this is an intermediary signal, with the letters rotated
    signal rotated_letters: output_letter_vector_type(0 to 4);

    -- return a letter corresponding to the state of a pair of switches
    function output_letter_from_bit_vector(bits: bit_vector) return output_letter_type is
    begin
        case bits is
        when "00" => return 'H';
        when "01" => return 'E';
        when "10" => return 'L';
        when "11" => return 'O';
        end case;
    end;

    -- return a value for driving a 7-segment display to show the corresponding letter
    function seven_seg_from_output_letter(letter: output_letter_type) return bit_vector is
    begin
        case letter is
        when 'H' => return "0110111";
        when 'E' => return "1001111";
        when 'L' => return "0001110";
        when 'O' => return "1111110";
        end case;
    end;

begin

    -- this first part reads the input switches and convert them to letters
    switch_selected_letters(0) <= output_letter_from_bit_vector(switch_pair_0);
    switch_selected_letters(1) <= output_letter_from_bit_vector(switch_pair_1);
    switch_selected_letters(2) <= output_letter_from_bit_vector(switch_pair_2);
    switch_selected_letters(3) <= output_letter_from_bit_vector(switch_pair_3);
    switch_selected_letters(4) <= output_letter_from_bit_vector(switch_pair_4);

    -- this first process generates the intermediary signal 'rotated_letters'
    rotate_letters: process (all) begin
        case rotate_switches is
        when "000" =>
            rotated_letters <= switch_selected_letters;
        when "001" =>
            rotated_letters <= switch_selected_letters(1 to 4) & switch_selected_letters(0);
        when "010" =>
            rotated_letters <= switch_selected_letters(2 to 4) & switch_selected_letters(0 to 1);
        when "011" =>
            rotated_letters <= switch_selected_letters(3 to 4) & switch_selected_letters(0 to 2);
        when "100" =>
            rotated_letters <= switch_selected_letters(4) & switch_selected_letters(0 to 3);
        when others =>
            rotated_letters <= switch_selected_letters;
        end case;
    end process;

    -- this second process outputs the rotated letters to the displays
    output_letters: process (all) begin
        lcd_display_0 <= seven_seg_from_output_letter( rotated_letters(0) );
        lcd_display_1 <= seven_seg_from_output_letter( rotated_letters(1) );
        lcd_display_2 <= seven_seg_from_output_letter( rotated_letters(2) );
        lcd_display_3 <= seven_seg_from_output_letter( rotated_letters(3) );
        lcd_display_4 <= seven_seg_from_output_letter( rotated_letters(4) );
    end process;

end;


text:
Q: Array vs If, which one is better in performance/best practice sight? For same result I can use (I prefer this simple one, personally):
$idx = 2;
$arr = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
echo $arr[$idx];

or:
$idx = 2;
if ($idx == 0)
    echo "Sun";
elseif ($idx == 1)
    echo "Mon";
elseif ($idx == 2)
    echo "Tue";
elseif ($idx == 3)
    echo "Wed";
elseif ($idx == 4)
    echo "Thu";
elseif ($idx == 5)
    echo "Fri";
else
    echo "Sat";

Which one is better in performance or best practice perspective?

A: I think array is faster. Array are reference object, so when you use array[index], it will get the value without loop from 0 to index.
When you use if else like  that, it just like the loop:

$idx = 5;
for($i =0;i<$array.length;i++)
{
    if(i==idx){
      echo ($array[i]);
break;
    }
}


text:
Q: how to specify height of row? I want to implement a tableview which shows an expandable cell for a specific row, so I create my custom table cell which will be expanded if setting its expandContent as following:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSString *shouldExpand = [self.datasource objectAtIndex:indexPath.row];
    if([shouldExpand isEqualToString:@"expand"]){
        [cell setExpandContent:@"Expand"];
    }
    else{
        [cell setTitle:@"a line"];
    }
    return cell;
}

however, in order to tell tableview the row height, I need to implement the following code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return [cell cellHeight];
}

The problem is heightForRowAtIndexPath method will call 1000 times of tableView:cellForRowAtIndexPath: if my datasource contains 1000 data, and it cost too much time.
how to fix the problem?

A: no u should find the size of cell first then send the hight calculated, dont call  tableView:cellForRowAtIndexPath: it will results in recursion instead, first calculate and send the height . for example

         //say suppose you are placing the string inside tableview cell then u need to   calculate cell for example

    NSString *string = @"hello world happy coding";
    CGSize maxSize = CGSizeMake(280, MAXFLOAT);//set max height
     CGSize cellSize = [self.str sizeWithFont:[UIFont systemFontOfSize:17]
                   constrainedToSize:maxSize
                   lineBreakMode:NSLineBreakByWordWrapping];//this will return correct height for text
    return cellSize.height +10; //finally u return your height

A:
how to fix the problem?

If you really have 1000 rows, you should consider not using dynamic row heights because even if you come up with a fast way to determine the row height the table will still need to ask about the height of each row separately. (In fact, if you really have 1000 rows, you should reconsider your whole design -- that's just too much data to look through with a linear interface.)
If you must use dynamic row heights for a large number of rows, you'll need to at least find a quick way to determine the height without creating the whole cell. Perhaps you can determine the factors that affect row height and come up with a very simplified method for calculating the height. If you can't do that, the it might make sense to calculate the height for each row once and then save the result with the row data so that you don't have to calculate it again until the data changes.

A: This is the code i used to set the UITableViewCell height dynamically:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary* dict = [branchesArray objectAtIndex:indexPath.row];
    NSString* address = [NSString stringWithFormat:@"%@,%@\n%@\n%@\n%@",[dict objectForKey:@"locality"],[dict objectForKey:@"city"],[dict objectForKey:@"address"],[dict objectForKey:@"contactNumber"], [dict objectForKey:@"contactEmail"]];

    CGSize constraint = CGSizeMake(220, MAXFLOAT);

   CGSize size = [address sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14.0f] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

   CGFloat height1 = MAX(size.height, 110.0f);
   return height1+20;
}

as well as set the frame in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath also


text:
Q: Longest consecutive date streak in Excel Suppose I have the spreadsheet:
+-------+----------+
| Date  | Duration |
+-------+----------+
| 06/30 | 12:00    |
| 07/01 | 44:30    |
| 07/03 | 12:00    |
| 07/04 | 18:00    |
| 07/05 | 10:00    |
| 07/07 | 08:00    |
| 07/09 | 99:00    |
| 07/10 | 99:00    |
+-------+----------+

How could I find the length of the longest consecutive streak of dates via Excel? (in this example, it would be 3: 07/03, 07/04, 07/05).
I'd like to do this with an array formula, but I don't know how to compute consecutive differences in a column with an array formula. I would prefer to avoid a helper column, but it's not a deal-breaker.

A: Using one helper column this will be pretty simple.

Formulas:
C3 downwards:
=IF(A3-A2=1,C2+1,0)

E2:
=MAX(C:C)+1

Found an array formula which works without helper column:
{=MAX(FREQUENCY(IF($A$3:$A$10001-$A$2:$A$10000=1,ROW($A$2:$A$10000)),IF($A$3:$A$10001-$A$2:$A$10000<>1,ROW($A$2:$A$10000))))+1}

Will work for dates in column A from A2 up to A10000.
But I'm pretty sure that the solution with helper column is better in terms of performance and readability.


text:
Q: How to update in database after select change in html select in zend I have a html select dropdown list in my view

    <?php $level = $this->escapeHtml($user->level); ?>

    <?php if ($level == 1): ?>
         <option value="1" selected ="selected">Administrator</option>
         <option value="2" <?php IsSelected($level,2); ?>> Manager</option>
         <option value="3" <?php IsSelected($level,3); ?>>HR Staff</option>
     <?php elseif ($level == 2): ?>
         <option value="1" <?php IsSelected($level,1); ?>>Administrator</option>
         <option value="2" selected ="selected">Manager</option>
         <option value="3" <?php IsSelected($level,3); ?>>HR Staff</option>
       <?php elseif ($level == 3): ?>
         <option value="1" <?php IsSelected($level,1); ?>>Administrator</option>
         <option value="2" <?php IsSelected($level,2); ?>>Manager</option>
         <option value="3" selected ="selected">HR Staff</option>
        <?php endif; ?>
    </select>

What I want is that everytime I select on my dropdown, it must update the level column in my user table in database.
I have tried using onchange event of javascript

but it fails on calling the parent url.
this outputs http://localhost/ijm/public/%7B%7BURL()%7D%7D/editLevel/2
instead of http://localhost/ijm/public/user/editLevel/2
aside from that, how can I update my user table from that javascript function?
this is my function in userController
public function editLevelAction()
    {
        //return $this->$view;
        $id = (int) $this->params()->fromRoute('id', 0);
        $data = array(
                'level' => $level
        );
        $this->update('user', $data, 'id = ' .'39');

         //return $this->redirect()->toRoute('user');

    }

what should i need to do for this to work? Thanks in advance.
Here now is the whole code.
<?php
$title = "Manage Users ";
$this->headtitle($title);

$identity = $this->identity()->level;
?>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />

<?php echo $this->escapeHtml($title); ?>User list

<a href="<?php echo $this->url('user/add'); ?>"> Add new user

<?php if (count($users)): ?>

        Name
        E-mail
        Level

    <?php foreach ($users as $user): ?>

        <a href="<?php echo $this->url('user/edit', array('id' => $user->id)); ?>"><?php echo $this->escapeHtml($user->first_name . ' ' . $user->last_name); ?>
        <?php echo $this->escapeHtml($user->email); ?>

            <?php $level = $this->escapeHtml($user->level); ?>
            <select name="level" id= "level" onchange="changeLevel(this)">
                 <option value="1" <?php IsSelected($level,1); ?>>Administrator</option>
                 <option value="2" <?php IsSelected($level,2); ?>> Manager</option>
                 <option value="3" <?php IsSelected($level,3); ?>>HR Staff</option>
            </select>

            <a href="<?php echo $this->url('user/delete', array('id' => $user->id)); ?>" class="btn btn-mini btn-danger" rel="tooltip" title="Delete this user">

    <?php endforeach; ?>

<?php else: ?>

There are no registered users available.

<?php endif; ?>

A: Try using AJAX (here is jQuery). This is just a quick example based on yours:
jQuery Hosted Libraries

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />

Form: Select

<form>
    <?php
        // Here is just a quick function to help fix your redundant
        // select check. This could probably be done better, but you
        // don't need to echo out all 3 sets of options 3 times
        function IsSelected($value = 1,$level = 1) {
                echo ($value == $level)? 'selected="selected"':"";
            }

        $level = $this->escapeHtml($user->level); ?>

    <select name="level" id= "level" onchange="changeLevel(this)">
         <option value="1"<?php IsSelected($level,1); ?>>Administrator</option>
         <option value="2"<?php IsSelected($level,2); ?>>Manager</option>
         <option value="3"<?php IsSelected($level,3); ?>>HR Staff</option>
    </select>
</form>

jQuery AJAX


text:
Q: Change color for specific data in ggplot2 I have 15 measurement points and i defined "renkler" color palette for them. I want to change the color of 2 (red: DEF-2 and DEF-13 points in the ps_no column) in these 15.
My codes are
library(ggplot2)
library(reshape)
dat <- read.delim("a.txt")
dat$Date <- as.Date(dat$Date,"%d/%m/%Y")

# order
dat$parameter <- factor(dat$parameter, levels = c("DEF-2", "DEF-13"))
dat$ps_no <- factor(dat$ps_no, levels = c("DEF-2", "PS.584", "PS.585", "PS.586", "PS.603", "PS.630", "DEF-13", "PS.600", "PS.667", "PS.690", "PS.714", "PS.734", "PS.754", "PS.811", "PS.813"))

# create own color palette
library(RColorBrewer)
renkler = c(brewer.pal(name="Set2", n = 7), brewer.pal(name="Set2", n = 8))

# Setup plot without facets
p <- ggplot(data = dat, aes(x = Date, y = value)) +
  geom_line(aes(color = ps_no)) +
  geom_point(aes(color = ps_no)) +
  scale_color_manual(values = renkler) + # oluşturduğumuz paleti yüklemek için
  scale_x_date(date_breaks = "1 months",date_labels = "%Y-%m",
               limits = as.Date.character(c("01/12/2017","31/12/2018"),
                                          format = "%d/%m/%Y")) +
  ylab("[mm/year]") +
  xlab("") +
  facet_grid(parameter ~ .) +
  theme_bw()

p + theme(
  axis.text.x = element_text(angle = 45, hjust = 1),
  panel.grid.major.x = element_blank(),
  panel.grid.minor.x = element_blank(),
)

and the data output with dput(dat):
structure(list(parameter = structure(c(2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("DEF-13",
"DEF-2"), class = "factor"), ps_no = structure(c(3L, 3L, 3L,
3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 7L, 7L, 7L, 8L, 8L, 8L, 2L,
2L, 2L, 6L, 6L, 6L, 9L, 9L, 9L, 10L, 10L, 10L, 11L, 11L, 11L,
12L, 12L, 12L, 13L, 13L, 13L, 14L, 14L, 14L, 15L, 15L, 15L, 1L,
1L, 1L), .Label = c("DEF-13", "DEF-2", "PS.584", "PS.585", "PS.586",
"PS.600", "PS.603", "PS.630", "PS.667", "PS.690", "PS.714", "PS.734",
"PS.754", "PS.811", "PS.813"), class = "factor"), Date = structure(c(17534,
17546, 17870, 17882, 17534, 17546, 17870, 17882, 17534, 17546,
17870, 17882, 17534, 17546, 17882, 17534, 17546, 17882, 17536,
17557, 17879, 17534, 17546, 17882, 17534, 17546, 17882, 17534,
17546, 17882, 17534, 17546, 17882, 17534, 17546, 17882, 17534,
17546, 17882, 17534, 17546, 17882, 17534, 17546, 17882, 17536,
17549, 17886), class = "Date"), value = c(0, 1.23684, -12.15729097,
-11.4102363, 0, 2.45200798, 1.12950398, -2.76779102, 0, 0.924571,
-7.1917482, -6.2764626, 0, -4.0725265, 0.4847485, 0, 0.290382,
-6.098794, 0, 0.813289109, -0.426076522, 0, 1.7502, -5.139665,
0, -29.67012, -14.956098, 0, 12.8852143, 7.4377433, 0, 1.404183,
-12.426633, 0, -24.09551, -7.619493, 0, -4.194441, -16.258703,
0, -0.835691, -10.504454, 0, 1.311699, 6.30102, 0, -1.49366556,
-1.835284539)), row.names = c(NA, -48L), class = "data.frame")

And also I need to change legend tittle (ps_no) and the texts on the right side of plots (DEF-2 and DEF-13).
Thank you.
Edit:
I filter the data which I want to show different color with using filter command. After filter command, I add a command line for geom_line and another command line for geom_point. It is working in the plot. But this is not the answer literally because the colors in the legend do not change.
So this the the new version of codes:
library(ggplot2)
library(reshape)
dat <- read.delim("aroundDEF.txt")
dat$Date <- as.Date(dat$Date,"%d/%m/%Y")

# order
dat$parameter <- factor(dat$parameter, levels = c("DEF-2", "DEF-13"))
dat$ps_no <- factor(dat$ps_no, levels = c("DEF-2", "PS.584", "PS.585", "PS.586", "PS.603", "PS.630", "DEF-13", "PS.600", "PS.667", "PS.690", "PS.714", "PS.734", "PS.754", "PS.811", "PS.813"))

# create own color palette
library(RColorBrewer)
renkler = c(brewer.pal(name="Set2", n = 7), brewer.pal(name="Set2", n = 8))
  geom_line(aes(color = ps_no)) +
  geom_line(data=highlight_df, aes(color = ps_no), color='#da0018') +
  geom_point(aes(color = ps_no)) +
  geom_point(data=highlight_df, aes(color = ps_no), color='#da0018') +

# filter dataframe to get data to be highligheted
highlight_df <- dat %>%
  filter(ps_no=="DEF-2" | ps_no=="DEF-13")

# Setup plot without facets
p <- ggplot(data = dat, aes(x = Date, y = value)) +

  scale_color_manual(values = renkler) +
  scale_x_date(date_breaks = "1 months",date_labels = "%Y-%m",
               limits = as.Date.character(c("01/12/2017","31/12/2018"),
                                          format = "%d/%m/%Y")) +
  ylab("[mm/year]") +
  xlab("") +
  facet_grid(parameter ~ .
             , labeller = as_labeller( c("DEF-2" = "DEF-2 and around", "DEF-13" = "DEF-13 and around"))) +
  theme_bw()

p + theme(
  axis.text.x = element_text(angle = 45, hjust = 1),
  panel.grid.major.x = element_blank(),
  panel.grid.minor.x = element_blank(),
)

In short, still I need an answer...

A: After renkler variable:
renkler[1]= "#DA0018"
renkler[7]= "#DA0018"

For the legend title:
scale_color_manual(values = renkler, name="new name")


text:
Q: Starting PowerMTA: [FAILED] Centos6 Have recently installed PowerMTA server on CentOS 6,  but unable to start pmta service and getting this error in logs.
service pmta restart

Stopping PowerMTA:                                         [  OK  ]
  Starting PowerMTA:                                         [FAILED]

/usr/sbin/pmtad --debug

2018-05-26 20:41:27 WARNING (line 15 of /etc/pmta/config): deprecated syntax for max-message-size; use file size syntax (such as in "100K") or "unlimited" instead.
2018-05-26 20:41:27 WARNING (line 82 of /etc/pmta/virtualhost.txt): "auto-cold-virtual-mta" deprecated; use explicitly defined cold Virtual MTAs instead.
2018-05-26 20:41:27 Startup error: Error in line 51 of /etc/pmta/config: Error in line 82 of /etc/pmta/virtualhost.txt: not a valid local IP address

I installed PMTA 4.5 on 5 different VPS and only this one not starting dunno what is wrong.
pmta/virtualhost.txt checked and ip is right.I know thease questions are stupid but i`m new with linux, thanks for help!

A: The IP in line 82 is a public IP, try to change it to a private one like 192.168...


text:
Q: How to make warnings explicit when converting from string to logical produces NAs I'm writing a function that catches conversion errors when a value is coerced to NA. It seems like the base conversion functions are inconsistent in returning warnings.
> as.numeric("a")
[1] NA
Warning message:
NAs introduced by coercion

However, the warning is not shown when converting to logical:
> as.logical("a")
[1] NA

My question: Is there a way to make the warning explicit when a string cannot be converted to logical?
I have looked into rlang::as_logical(), but it returns an error instead of a warning, that I'd like to avoid if possible.

A: You can use options(warn =. For example:
options(warn=1, error=NULL)

to get a warning.
I typically handle this by promoting warnings to errors for the relevant part of the code.
For example:
options(warn=2, error=NULL)
as.logical(x)

Error: (list) object cannot be coerced to type 'logical'

You can also easily reset it like this options(warn=0, error=NULL)
Related: Breaking loop when "warnings()" appear in R

A: You can make your own function about this:
as.logical2 <- function(x) {

  if (is.na(x)) return(x)
  out <- as.logical(x)
  #if there is an NA, you can issue a warning
  if (is.na(out)) warning('NAs introduced by coercion')
  out

}

as.logical2('a')
#[1] NA
#Warning message:
#In as.logical2("a") : NAs introduced by coercion


text:
Q: DUDA DE MODULO UPDATE SQL CON PYTHON || INCIDENCIA 1054 Realice mi script para actualizar mi BD, sin embargo, me envía un error 1054 Unknown column 'FGT60ETK19070551' in 'where clause'. ¿Alguno de ustedes saben que estoy realizando mal?
  def actualizar(Serial_Num ,licencia_vencimiento):
     cursor = conexion.cursor()
     sql = '''UPDATE Inventario SET (licencia_vencimiento = '{}')  WHERE Serial_Num =
           {}'''.format(Serial_Num ,licencia_vencimiento)
     cursor.execute(sql)
     col_afectada = cursor.rowcount
     conexion.commit()
     cursor.close()
     retur(col_afectada)

print(actualizar(FGT60ETK19070551,'2022-08-12'))

A: El problema lo tienes en la asignación de parámetros de la consulta sql, estás asignando a licencia_vencimiento el primer valor, es decir, el de Serial_Num  y viceversa.
def actualizar(Serial_Num ,licencia_vencimiento):
     cursor = conexion.cursor()
     sql = '''UPDATE Inventario SET (licencia_vencimiento = {lic})  WHERE Serial_Num =
           {sn}'''.format(sn=Serial_Num , lic=licencia_vencimiento)
     cursor.execute(sql)
     col_afectada = cursor.rowcount
     conexion.commit()
     cursor.close()
     retur(col_afectada)

print(actualizar('FGT60ETK19070551', '2022-08-12'))

Te recomiendo no usar format para evitar posibles vulnerabilidades en las consultas sql, ya que no estás validando la entrada. En su lugar, se recomienda usar el argumento de execute que permite el paso de parámetros.
def actualizar(Serial_Num ,licencia_vencimiento):
     cursor = conexion.cursor()
     sql = "UPDATE Inventario SET licencia_vencimiento = %(lic)s WHERE Serial_Num = %(sn)s"
     cursor.execute(sql, {"lic": licencia_vencimiento, "sn": Serial_Num })
     # estas consultas son equivalentes, pero no hacen el uso de argumentos con nombre
     # sql = "UPDATE Inventario SET licencia_vencimiento = %s WHERE Serial_Num = %s"
     # cursor.execute(sql, (licencia_vencimiento, Serial_Num))
     col_afectada = cursor.rowcount
     conexion.commit()
     cursor.close()
     retur(col_afectada)

print(actualizar('FGT60ETK19070551','2022-08-12'))


text:
Q: Typedef to a double array of ints I am trying to learn about an implementation of some code that uses a typedef to a double array and also uses pointers and I am having some difficulty understanding the code and details on how the code works and what types the variables are and what points to what.
I have tried playing around with different implementations and trying to understand how it works but the results I have gotten have been not what I have expected.
Heres some code I tried to test:
typedef int array[2][6];
array *arr;
arr = (array*)malloc(sizeof(array));
*arr[0][0]=2;
*arr[0][1]=4;

*arr[1][0]=3;
*arr[1][1]=5;
printf("line 1: %d %d\nline 2: %d %d\n",*arr[0][0],*arr[1][0],*arr[0][1],*arr[1][1]);
int *in = (int*) ((*arr)[0]);
printf("in = %d\n",in[1]); // results are unexpected

The code that I am actually looking at is for a ping pong buffer and is  (simplified) as follows:
int buffer_count = 2; // 2 ping pong buffers
int sample_size = 15;
typedef int PingPong_t[buffer_count][sample_size];

PingPong_t *inputstream;

// logic goes here to determine pingpong_idx
int pingpong_idx = 0; // I believe this is to choose the first or second buffer

int *pcmIn = (int*)((*inputstream)[pingpong_idx]);

// do processing

I expect that pcmIn is an integer array of the current ping or pong buffer, but I am having trouble proving that to myself or I am just unsure what the datatypes actually are and what it is actually doing.
A good question I might have is, what is the type of inputstream? Is it correct to say that inputstream is a pointer to a double array of integers? Or is inputstream a double array of integer pointers?
Then what would be the type of pcmIn?

A: Let's break it down.
typedef int PingPong_t[buffer_count][sample_size];
This will make PingPong_t represent a 2D array of integers.
So, you can have
PingPong_t p = {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},{3,4,5,6,7,8,9,10,11,12,13,14,15,16,17}};
Then, we declare a pointer to this type as
PingPong_t *inputstream;
which means that inputstream is a pointer to whatever PingPong_t represents. It is not an array, not an array of pointers, just a pointer.
Since PingPong_t essentially means int x[2][15], inpustream will mean int (*y)[2][15].
Suppose we had something like
inputstream = &p;
Then, inputstream will point to the 2D array that is p. A custom pointer of type 2-dimensional (2 x 15) int array.
So, inputstream is int (*)[2][15] and p is int [2][15].
Now, playing it further, let us suppose we were to increment inputstream.
Incrementing a pointer will add the size of the type it points to.
So, in our case incrementing inpustream adds sizeof(int)*2*15 i.e. 120 (my machine has 4-byte int). Note that it does not add sizeof(int) here as its base type is not int but a 2D array of ints.
Finally, pcmIn is an int pointer (which can be thought of as a 1D array here), we are assigning like this
int *pcmIn = (int*)((*inputstream)[pingpong_idx]);
which fetches the first row (pingpong_idx) of the 2D array that inputstream points to, and assigns it to pcmIn.
Furthermore, you are getting unexpected results in your example above as you are assigning to the array in wrong manner. Since arr is a pointer to 2D array, you assign a value to an element like this
(*arr)[0][1]=4;
and not like this
*arr[0][1]=4;.
The latter will mean that arr is a 2D array of pointers and you are basically setting the value of [0][1]th pointer to 4, which is not what you had planned.
arr is not a 2D array and so arr[0][1] will mean the adding sizeof(int)*15 to the value of arr, and *arr[0][1] is basically getting/setting value at that address. In effect, the [0][1]th value is still uninitialized.
But, then how does *arr[0][0]=2; and printf("in = %d\n",in[0]); work?
Because, doing *arr[0][0]=2; will set the value of [0][0]th element to 2.