text:
Q: Fetch data using React HOC(Higher Order Component), Redux and pass props I want to create a HOC that would allow me to call methods which will fetch data from backend and display a loader mask if they're loading. The trick is that I want to be able to pass different actions for different components.
So I'd like to call it like that:
export default withPage({
  getLoadingStatus: getStatus,
  actionOnLoad: booksActions.getAllBooksRequest
})(ShareABookContainer);

As I'm passing some props there I defined my withPage.js like below:
const withPage = ({
  actionOnLoad,
  getLoadingStatus
}) => WrappedComponent => () => {
  return (
    <PageContainer
      getLoadingStatus={getLoadingStatus}
      wrappedComponent={WrappedComponent}
      actionOnLoad={actionOnLoad}
    />
  );
};

export default withPage;

PageContainer.js is the most common container, so:
const PageContainer = props => <PageComponent {...props} />;

const mapStateToProps = (state, ownProps) => ({
  ...
});

const mapDispatchToProps = (dispatch, ownProps) => {
...
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageContainer);

And PageComponent is a common Component as well:
class PageComponent extends Component {
  componentDidMount() {
   ...
  }

  render() { return <this.props.wrappedComponent />;
  }
}

export default PageComponent;

What happens is that nothing gets rendered and if I console.log wrappedComponent I receive:

WrappedComponent ƒ a(e,t){!function(e,t){if(!(e instanceof t))throw
  new TypeError("Cannot call a class as a function")}(this,a);var
  r=function(e,t){if(!e)throw new ReferenceError("this hasn't been
  initialised - super()…

When I'm passing some div, e.g. test instead of  everything works fine, but what I need is for passed component to be rendered.
I have no idea what I'm doing wrong and examples in the Internet are not helping either. I wasn't able to find an example for a situation like mine (so passing props to HOC and using Redux there, it's either one or the other). I'd be very grateful for any thoughts/suggestions/answers.

A: Try simpler:
return (
  <PageContainer
    getLoadingStatus={getLoadingStatus}
    actionOnLoad={actionOnLoad} >
    <WrappedComponent />
  </PageContainer>
);

BTW, react rather 'doesn't like' <this.props.wrappedComponent /> No errors??
When needed dynamic components I probably used sth like:
const Wrapped = this.props.wrappedComponent;
render () { return <Wrapped /> }

Var name had to be uppercased.


text:
Q: What special feature does this kind of coupling have? This diagram was in the 4th chapter of the book Heat and Thermodynamics, Zemansky and Dittman.

An amount of gas confined to a cylinder of thermally insulator material, here, is undergoing an adiabatic expansion. As the gas expands, the body is lifted.
My question is that why is the mechanism designed like that? I mean that almond shaped thing attached to the small gear. There must be an idea behind it, as the book says:

My own guess is that this kind of hanging the mass, guarantees a quasi-static process.

A: As the piston moves up the pressure inside the cylinder decreases.
Thus the force exerted by the gas in the cylinder on the piston decreases.
What is needed to allow the piston to move up slowly is to apply a decreasing external force on the piston as the piston moves up such that the external force is slightly less than the force exerted by the gas on the piston.
That decreasing force is achieved using the cam, rack and pinion.
There is a lever with axle of the pinion/cam acting as the fulcrum.
As the rack moves up the cam rotates and reduces the distance between the line of action of the weight and the axle thus reducing the torque produced by the weight and hence the torque exerted by the pinion.
Hence the force on the rack/piston is reduced.

Update
Schematic diagram of apparatus

When the piston has moved a distance $x$ from the bottom of the cylinder the rack has also moved upwards a distance $x$.
At the same time the pinion and the cam have rotated through an angle $\theta$.
$x=a \theta$ where $a$ is the fixed radius of the pinion.
For an adiabatic expansion $PV^\gamma = {\rm constant} = \dfrac F A (Ax)^\gamma \Rightarrow F x^\gamma = \rm constant$
With the symbols as defined in the diagram $F = \dfrac b a mg \Rightarrow b\;\theta^\gamma = \rm constant$ and this is the equation for the shape of the cam.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I disable SSH KeychainIntegration in OS X Mavericks? I'm having some issues with SSH KeychainIntegration in OS X Mavericks.  I've tried poking around Apple's support site, but haven't seen anyone having my issue.  I have seen lots of people who seemingly don't know how to use SSH that well, so I decided to try another community.
First, my configuration is working.  I am able to use my key pair and ssh to hosts as I need to, with my credentials being cached in the agent.  I am able to see my cached credentials via "ssh-add -l", as expected.  I am prompted to input my password by an OS X-style dialog, with a checkbox that says "Remember password in my keychain".  I usually ignore this checkbox, but when I check it, I do see my key stored in the keychain.  This key stored in the keychain is seemingly never used, however, since I have a password on it.  At least that's what I've gleaned from various things I've read.  When I enter my password into the dialog, and the key is cached in the agent, I successfully connect, but not before being told "Saving password to keychain failed".  Seeing this error message is what led me to investigate further; I don't like getting an error every time I connect.
Things get interesting when looking at the manpage SSH_CONFIG(5).  Two options for dealing with the keychain exist, specific to Apple:  AskPassGUI, and KeychainIntegration.  You're able to toggle these in ~/.ssh/config, and doing so yields some interesting results.
Setting AskPassGUI to no, you'll no longer be prompted with an OS X-style dialog, instead an input text line in your terminal.  No biggie.  But if you do this, then ssh-agent will not cache your credentials.  This is plainly broken, and frustrating because I could easily live with the text prompt if the credentials were cached.
Setting KeychainIntegration to no, ssh throws a hard error, as follows:
~/.ssh/config: line 11: Bad configuration option: KeychainIntegration
~/.ssh/config: terminating, 1 bad configuration options

My question, simply, is this:  Is there a way to actually disable OS X Keychain Integration for SSH?

A: Based on the source code for the current version of SSH that's shipping with Mavericks (located here), it appears that the functionality of the config option KeychainIntegration has not yet been implemented. I'm making this assumption based on the contents of openssh/readconf.h, which does not reference the KeychainIntegration option. It does, however, reference the askpassgui option. Checking the "keywords" struct in that file does indeed show that the keychainintegration option is not present (which in turn implies that the oBadOption (NULL) op code would be returned).
Another clue implying that the functionality you desire is not implemented in the way the man page specifies is the file: openssh/keychain.c. The source code actually shows that the defaults system (i.e., Property List files) is being used to store settings related to KeychainIntegration. Specifically, lines from the store_in_keychain function reference KeychainIntegration:
/* Bail out if KeychainIntegration preference is -bool NO */
if (get_boolean_preference("KeychainIntegration", 1, 1) == 0) {
    fprintf(stderr, "Keychain integration is disabled.\n");
    goto err;
}

Here is the corresponding get_boolean_preference function. Note that it's using CFPreferencesCopyAppValue to obtain a boolean from the "org.openbsd.openssh" application identifier:
#if defined(__APPLE_KEYCHAIN__)

static int get_boolean_preference(const char *key, int default_value,
int foreground)
{
int value = default_value;
CFStringRef keyRef = NULL;
CFPropertyListRef valueRef = NULL;

keyRef = CFStringCreateWithCString(NULL, key, kCFStringEncodingUTF8);
if (keyRef != NULL)
    valueRef = CFPreferencesCopyAppValue(keyRef,
        CFSTR("org.openbsd.openssh"));
if (valueRef != NULL)
    if (CFGetTypeID(valueRef) == CFBooleanGetTypeID())
        value = CFBooleanGetValue(valueRef);
    else if (foreground)
        fprintf(stderr, "Ignoring nonboolean %s preference.\n", key);

if (keyRef)
    CFRelease(keyRef);
if (valueRef)
    CFRelease(valueRef);

return value;
}

#endif

This might imply that you can disable the KeychainIntegration functionality for yourself by performing this defaults command:
defaults write org.openbsd.openssh KeychainIntegration -bool NO
or to set it for all users:
sudo defaults write /Library/Preferences/org.openbsd.openssh KeychainIntegration -bool NO


text:
Q: ¿Sacar información de una tabla? Compañeros, alguien me puede colaborar con este pequeño detalle que tengo necesito sacar la información de una tabla con serenity y java, pero no lo he logrado.
Cuerpo HTML:

                            Tasa mes vencida utilizada en la simulación
                            1.75%

Java:
String tasaMesVencidoTexto = Serenity.getWebdriverManager().getCurrentDriver().findElement(By.xpath("//table[@class = 'table table-datos']//tbody/tr[2]/td[2]")).getText();

Esta es la tabla, en general solo necesito ese dato, si alguien me puede decir donde conseguir información al respecto o decirme de que manera hacerlo, estaría muy agradecido.
Gracias

A: Estimado pruebe las siguientes alternativas

*

*Verifique su xpath estoy viendo un xpath absoluto, intenta construir un xpath relativo. Te dejo documentación https://www.guru99.com/xpath-selenium.html

*Verifique que no exista un iframe en la estructura del dom, por que si existe un iframe no podras llegar a la tabla y mucho menos capturar lo que tiene.

*Continua debugendo y probando sus xpath, por que siento que por ahí es el problema el codigo en general lo veo bien.

Saludos.


text:
Q: Modular arithmetic proposition I am trying to solve this Modular arithmetic problem but I have no idea how to verify if the proposition holds or not.

$\forall a,b \in \mathbb{Z}: (a \equiv b \pmod{5}  \Rightarrow 2a \equiv 2b \pmod{5} )$

A: Try it this way:
$$ a \equiv b \pmod 5  \implies \exists (k_a, k_b, m \in \Bbb N) : \\a = 5k_a+m , \\b = 5k_b+m,  \\0 \leq m <5
$$
Okay, now what about comparing $2a$ and $2b$?
One thing to try is to multiply those relations above by 2, getting
$$
2a = 10k_a+2m , \\2b = 10k_b+2m,  \\0 \leq 2m <10
$$
If $2m < 5$ it is easy to see that $2a \equiv 2b$ by using multipliers $k'_a = 2k_a$ and $k'_b = 2k_b$.  That leaves the headache of the possibility that $2m > 5$.
Can you see how to handle that case and thus complete the proof?  (Hint - what happens if you use $k'_a = 2k_a + 1$ ?)

A: You can prove this directly.
$$a \equiv b \pmod {5} \iff 5|(b-a) \iff b-a = 5k ~(\text{for some } k \in \Bbb Z)\\ \iff 2b-2a =5(2k) \iff 5|(2b-2a) \iff 2a \equiv 2b \pmod {5}.$$


text:
Q: Coin Flip Statistics Program - undefined method I'm trying to write a coin flip program where I can analyze the percentage of Heads flipped.  I've gotten coin flip to work, just not the actually analyzing yet.
The problem is when I created a Coin class in order to further break down the object into something like Coin.length afterwards.
Why am I getting an "undefined method 'flip' for Coin:Class (NoMethodError)"   from flip.rb:14:in 'times'
    from flip.rb:14:in <main>
 when I indeed have one?
class Coin

def flip
  flip = 1 + rand(2)
    if flip == 2
        then puts "Heads"
    else
        puts "Tails"
    end
end

end

10.times do
  Coin.flip
end

Here's a die roll example that I am somewhat trying to emulate:
 class Die

     def roll
       1 + rand(6)
     end

  end

    #  Let's make a couple of dice...
    dice = [Die.new, Die.new]

    #  ...and roll them.
    dice.each do |die|
      puts die.roll
    end

A: Coin.flip is not a method you defined; this would be a class method, and to define a class method called flip you would write:
class Coin
  def self.flip
    ...
  end
end

What you created is an instance method, and as such it requires that it is called on an instance:
coin = Coin.new
coin.flip
# or
Coin.new.flip

In your second example (with the Dice), you are correctly calling new and creating instances.

A: you defined instance method filp, but there is no class method called Coin.flip.


text:
Q: Best practices for SQL transactions in Java For a particular problem, I'm looking to use Database transactions.
I have never done that in past. My question is if I could use plain JDBC for that or Java provides something nicer (framework..) to implement this?
Is there any design pattern I could look at?
Thanks

A: You can find the answer on the internet, but i will summarize it for you. In the case of transactions you basically have to follow a few steps:
In the try block:

*

*you have to set auto commit to false,

*do your sql queries and stuff (PreparedStatement outperforms the simple Statement),

*make sure you commit.

In the catch block:

*

*rollback the database changes (in case of an error).

In the finally block:

*

*check if not null and close all the PreparedStatements,

*check if not null and close the database connection.

Here is a sample:
try{
    connection = getDatabaseConnection();
    //set connection auto commit to false
    connection.setAutoCommit(false);

    PreparedStatement sqlPreparedStatement = connection.prepareStatement("sql statement here");
    //set all the values in the prepared statement
    sqlPreparedStatement.setString(1,"string");
    sqlPreparedStatement.setString(2,"anotherstring");

    sqlPreparedStatement.executeUpdate();

    PreparedStatement secondSqlStatement = connection.prepareStatement("sql statement here");
    //set all the values in the prepared statement
    secondSqlStatement.setString(1,"whatever");
    secondSqlStatement.setString(2,"sample");

    secondSqlStatement.executeUpdate();

    //commit the changes
    connection.commit();
} catch (SQLException e) {
    e.printStackTrace();//or whatever
    //rollback the changes
    connection.rollback();
} finally {
    //close the PreparedStatement and the connection if not null
    if (sqlPreparedStatement != null) {
        sqlPreparedStatement.close();
    }
    if (secondSqlStatement != null) {
        secondSqlStatement.close();
    }
    if (connection != null) {
        connection.close();
    }
}


text:
Q: How to use below code in entity framework delete asp_testtable
where  userid='XYZ'
and    SL=12
and    userAmount=13

where:

*

*asp_testtable is the table name

*userid is a column of type varchar

*SL is a column of type bigint

*userAmount is a column of type decimal
These are the three steps i followed but non of them are working
Step 1:
asp_testtable map = DBContext.asp_testtable.RemoveRange(DBContext.asp_testtable.Where(c => c.userid == tbuserid.Text.Trim() && c.SlNo == Convert.ToInt64(lbSlNo.Text.ToString()) && c.userAmount == Convert.ToInt16(ddluserAmount.SelectedValue.ToString()))).SingleOrDefault();

DBContext.asp_testtable.Remove(map);

Step 2:
var y = (from x in asp_testtable where x.userid == tbuserid.Text.Trim() && x.SlNo == Convert.ToInt64(lbSlNo.Text) && x.userAmount == Convert.ToInt16(ddluserAmount.SelectedValue) select x.FeeMappingSlNo).First();

DBContext.asp_testtable.RemoveRange(y);

step 3:
feedetail = new asp_testtable()
{
    userid = tbuserid.Text.Trim(),
    SlNo = Convert.ToInt64(lbSlNo.Text),
    userAmount = Convert.ToInt16(ddluserAmount.SelectedValue)
};

DBContext.asp_testtable.Remove(feedetail);

A: context.asp_testtable.Select(item => item.userid == "XYZ" && item.SL = 12 &&
item.userAmount == 13).ToList().ForEach(context.asp_testtable.DeleteObject);
context.SaveChanges();

Find the relevant items and remove them using DeleteObject

A: Try this:
string DeleteStatement = "DELETE FROM asp_testtable " +
    "WHERE userid = 'XYZ' AND SL=12 AND userAmount=13 ";

yourcontext.Database.SqlQuery(DeleteStatement);


text:
Q: overriding subclasses in actionscript Trying to find a straight answer for this. I am going to be creating some sub classes in actionscript 3. I was wanting to know if it is possible to override the parent class. If so, do I need to put a override assigner on the parent class method or what.
Thanks guys

A: You can override any non-private method in your subclass.
And there is no keyword to indicate in the base class whether a method can or has to be overridden (like virtual in C++).
E.g.

public class A
{
  public function methodOfA():void
  {
  }
}

public class B extends A
{
  override public function methodOfA():void
  {
    // do something more specific to B
  }
}


text:
Q: ASP.Net Environment.NewLine stops working half way through a script? I'm using a script to construct an email, and half way through the NewLines just quit working. I don't see any errors, nor do I can any when it's executed.
Here is the code:
message = message & "Zoning Selections -" & Environment.NewLine & Environment.NewLine
message = message & "Standard Report: " & Request.QueryString("chkList0") & Environment.NewLine
message = message & "Summary Zoning Report: " & Request.QueryString("chkList1") & Environment.NewLine
message = message & "Executive Summary: " & Request.QueryString("chkList2") & Environment.NewLine
message = message & "ZIP Report: " & Request.QueryString("chkList3") & Environment.NewLine
message = message & "Custom Report - Individual Products: " & Request.QueryString("chkList4") & Environment.NewLine
message = message & "Certificate of Occupancy: " & Request.QueryString("chkList5") & Environment.NewLine
message = message & "Building Code Violation: " & Request.QueryString("chkList6") & Environment.NewLine
message = message & "Code Compliance Violation: " & Request.QueryString("chkList7") & Environment.NewLine
message = message & "Fire Code Violation: " & Request.QueryString("chkList8") & Environment.NewLine
message = message & "Saftey Code Violation: " & Request.QueryString("chkList9") & Environment.NewLine
message = message & "Condemnation Report: " & Request.QueryString("chkList10") & Environment.NewLine

message = message & "Property Use: " & Request.QueryString("property_use") & Environment.NewLine

and here is the output:
Zoning Selections -
Standard Report: yes
Summary Zoning Report: yes
Executive Summary: yes
ZIP Report: yes
Custom Report - Individual Products: yes Certificate of Occupancy: yes Building Code Violation: yes Code Compliance Violation: yes Fire Code Violation: yes Saftey Code Violation: yes Condemnation Report: yes Property Use: Office

As you can see, the NewLine works until half way through, and then it simply prints everything on the same line. (also, the other NewLines were added to the file at another time than the ones printing correctly)
What am I missing?
EDIT
Apparently the plain-text formating of an email break all Environment.NewLine line breaks for the rest of the email when it encounters a line longer than 40-50 character (I was using Outlook 2013).
My solution was simple, switch to HTML format and use  tags for line breaks instead.


text:
Q: QSortFilterProxyModel sorts only the fetched data I have a QTableView with a QSortFilterProxyModel as its model which has a QSqlRelationalTableModel as its source model.
When I sort or filter the viewed data through the QSortFilterProxyModel, only the fetched data is affected.
I managed to get it work by fetching all data from the table by using
if model.canfetchMore():
   model.fetchMore()

The problem is the table has a large number of records (200,000 records).
Is there any other way to sort and filter the proxymodel without fetching all the data from the database?

A: You probably work with Sqlite as you have to use fetchMore().
When you work with large number of records, it's slow to load 200.000 records or so from database at once, and it's not fetchMore() that's problematic, but just loading that quantity of data from database is slow. It is slow even when you work with PostgreSQL where you don't have to use fetchMore(). So I use a trick to have all records, but don't have to wait too long. I split (the same) table into two views, I call it parent and child:
import sys
import random

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtSql import *

class Window(QWidget):
    def __init__(self, parent=None):
        #QWidget.__init__(self, parent)
        super(Window, self).__init__(parent)

        self.search_label = QLabel("Name:")
        self.search_lineedit = QLineEdit('')

        self.parent_model = QSqlQueryModel(self)
        self.refresh_parent()
        self.parent_proxy_model = QSortFilterProxyModel()
        self.parent_proxy_model.setSourceModel(self.parent_model)
        self.parent_view = QTableView()
        self.parent_view.setModel(self.parent_proxy_model)
        self.parent_view.setSelectionMode(QTableView.SingleSelection)
        self.parent_view.setSelectionBehavior(QTableView.SelectRows)
        self.parent_view.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.parent_view.horizontalHeader().setStretchLastSection(True)
        self.parent_view.verticalHeader().setVisible(False)
        self.parent_view.setSortingEnabled(True)
        self.parent_view.horizontalHeader().setSortIndicator(0, Qt.AscendingOrder)
        self.parent_view.setAlternatingRowColors(True)
        self.parent_view.setShowGrid(False)
        #self.parent_view.verticalHeader().setDefaultSectionSize(24)
        self.parent_view.setStyleSheet("QTableView::item:selected:!active { selection-background-color:#BABABA; }")
        for i, header in enumerate(self.parent_headers):
            self.parent_model.setHeaderData(i, Qt.Horizontal, self.parent_headers[self.parent_view.horizontalHeader().visualIndex(i)])
        self.parent_view.resizeColumnsToContents()

        self.child_model = QSqlQueryModel(self)
        self.refresh_child()
        self.child_proxy_model = QSortFilterProxyModel()
        self.child_proxy_model.setSourceModel(self.child_model)
        self.child_view = QTableView()
        self.child_view.setModel(self.child_proxy_model)
        self.child_view.setSelectionMode(QTableView.SingleSelection)
        self.child_view.setSelectionBehavior(QTableView.SelectRows)
        self.child_view.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.child_view.horizontalHeader().setStretchLastSection(True)
        self.child_view.verticalHeader().setVisible(False)
        self.child_view.setSortingEnabled(True)
        self.child_view.horizontalHeader().setSortIndicator(1, Qt.AscendingOrder)
        self.child_view.setAlternatingRowColors(True)
        self.child_view.setShowGrid(False)
        #self.child_view.verticalHeader().setDefaultSectionSize(24)
        self.child_view.setStyleSheet("QTableView::item:selected:!active { selection-background-color:#BABABA; }")
        for i, header in enumerate(self.child_headers):
            self.child_model.setHeaderData(i, Qt.Horizontal, self.child_headers[self.child_view.horizontalHeader().visualIndex(i)])
        self.child_view.resizeColumnsToContents()

        search_layout = QHBoxLayout()
        search_layout.addStretch()
        search_layout.addWidget(self.search_label)
        search_layout.addWidget(self.search_lineedit)

        view_layout = QHBoxLayout()
        view_layout.addWidget(self.parent_view)
        view_layout.addWidget(self.child_view)

        layout = QVBoxLayout(self)
        layout.addLayout(search_layout)
        layout.addLayout(view_layout)
        #self.setLayout(layout)

        self.parent_view.selectionModel().currentRowChanged.connect(self.parent_changed)
        self.search_lineedit.textChanged.connect(self.search_changed)

        self.parent_view.setCurrentIndex(self.parent_view.model().index(0, 0))
        self.parent_view.setFocus()

    def refresh_parent(self):
        self.parent_headers = ['Category']
        query_string = "SELECT category FROM parent"
        query = QSqlQuery()
        query.exec(query_string)
        self.parent_model.setQuery(query)
        while self.parent_model.canFetchMore():
            self.parent_model.fetchMore()

    def refresh_child(self, category=''):
        self.child_headers = ['Category', 'Name', 'Description']
        query_string = ("SELECT category, name, description FROM child "
            "WHERE child.category = '{category}'").format(category = category)
        query = QSqlQuery()
        query.exec(query_string)
        self.child_model.setQuery(query)
        while self.child_model.canFetchMore():
            self.child_model.fetchMore()

    def parent_changed(self, index):
        if index.isValid():
            index = self.parent_proxy_model.mapToSource(index)
            record = self.parent_model.record(index.row())
            self.refresh_child(record.value("parent.category"))
            #self.child_view.scrollToBottom() # if needed

    def search_changed(self, text):
        query_string = ("SELECT category, name FROM child WHERE name = '{name}'").format(name = text)
        query = QSqlQuery()
        query.exec(query_string)
        if query.next():
            category = query.value('category')
            start = self.parent_proxy_model.index(0, 0)
            matches = self.parent_proxy_model.match(start, Qt.DisplayRole, category, 1, Qt.MatchExactly) # Qt.MatchExactly # Qt.MatchStartsWith
            if matches:
                print('parent matches')
                index = matches[0]
                self.parent_view.selectionModel().select(index, QItemSelectionModel.Select)
                self.parent_view.setCurrentIndex(index)
                self.refresh_child(category)
                #------------------------------------------------
                start = self.child_proxy_model.index(0, 1)
                matches = self.child_proxy_model.match(start, Qt.DisplayRole, text, 1, Qt.MatchExactly) # Qt.MatchExactly # Qt.MatchStartsWith
                if matches:
                    print('child matches')
                    index = matches[0]
                    self.child_view.selectionModel().select(index, QItemSelectionModel.Select)
                    self.child_view.setCurrentIndex(index)
                    self.child_view.setFocus()

def create_fake_data():
    categories = []
    #import random
    query = QSqlQuery()
    query.exec("CREATE TABLE parent(category TEXT)")
    for i in range(1, 201):
        category = str(i).zfill(3)
        categories.append(category)
        query.prepare("INSERT INTO parent (category) VALUES(:category)")
        query.bindValue(":category", category)
        query.exec()
    query.exec("CREATE TABLE child(category TEXT, name TEXT, description TEXT)")
    counter = 1
    for category in categories:
        for i in range(1, 1001):
            name = str(counter).zfill(6)
            description = str(random.randint(1,100)).zfill(3)
            counter += 1
            query.prepare("INSERT INTO child (category, name, description) VALUES(:category, :name, :description)")
            query.bindValue(":category", category)
            query.bindValue(":name", name)
            query.bindValue(":description", description)
            query.exec()

def create_connection():
    db = QSqlDatabase.addDatabase("QSQLITE")
    #db.setDatabaseName('test.db')
    db.setDatabaseName(":memory:")
    db.open()
    create_fake_data()
    print('database is full, now starting a program...')

app = QApplication(sys.argv)
create_connection()
window = Window()
#window.resize(800, 600)
#window.show()
window.showMaximized()
app.exec()

It is possible only if you have an attribute (or a prefix of an attribute, or more than one attributes) that you can use as a "category".
This program loads slowly, but only database input. Once database is full, the program works fast. This is just an example, in real app you have your database full.
With this trick, you can handle 1.000.000 records, just use 1.000 x 1.000 (or 200 x 5.000, or some other combination). The problem is that search and filter are harder to implement this way. I showed one way how to implement search.
Regarding "Why don't you implement filtering and sorting using SQL" comment, that's because sql can only return data in one order and one (fixed) filter, and with QSortFilterProxyModel you can sort and filter data additionally any way you like and way faster than using sql once you have your data in models.


text:
Q: Similar and congruent triangles Let $ABC$ be a triangle and $h_a,h_b,h_c$ the length of the heights.
(a) Find similar triangles at which it holds that $ah_a=bh_b$.
(b) Use (a) to show : Is $A'B'C'$ a second triangle and $h_a,h_b,h_c$ are again the length of the heights of this triangle, so these triangles are congruent.
$$$$
For (a) do we have to give two specific triangles, i.e. give the negth of the sides? Or what exactly is asked?

A: For part (a), yes, we have to find two similar triangles for which $ah_a=bh_b$ holds.
Draw $h_a$ and $h_b$ inside $\triangle ABC$. $h_a \cap BC \in D$. $h_b \cap CA \in E$. With simple angle chasing, $$\triangle ADC \sim \triangle BEC$$


text:
Q: Preselect an option based on a parameter in URL New to jQuery/JS... A few posts on Stackoverflow were helpful, but i could not trigger the change function once the get.URL function runs.
I am trying to create a simple page with a pulldown that filters. I also want this pulldown to have the ability to preselect an option based on a value in URL watch=Cat1
Here's the code for the select:
<select name="watch" id="watch">
<option value="All">All news</option>
<option value="Cat1">Category 1</option>
<option value="Cat2">Category 2</option>
<option value="Cat3">Category 3</option>

Here are my scripts:
<script>
  //Filter News
  $('select#watch').change(function() {
    var filter = $(this).val()
    filterList(filter);
  });

  //News filter function
  function filterList(value) {
    var list = $(".news-list .news-item");
    $(list).fadeOut("fast");
    if (value == "All") {
      $(".news-list").find("article").each(function(i) {
        $(this).delay(200).slideDown("fast");
      });
    } else {
      //Notice this *=" <- This means that if the data-category contains multiple options, it will find them
      //Ex: data-category="Cat1, Cat2"
      $(".news-list").find("article[data-category*=" + value + "]").each(function(i) {
        $(this).delay(200).slideDown("fast");
      });
    }
  }

</script>
<script>
     function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
var val = getURLParameter('watch');
$('#watch').val(val);   //  assign URL param to select field
    ('select#watch').trigger("change");}
    </script>

I am able to select the correct option based on the URL parameter, however, the select box no longer updates the page according to the selection.
Thank you in advance,
Udi


text:
Q: Finding the number of solutions of the equation $c_1 + c_2 + c_3 = 20$ in the nonnegative integers if $c_2$ is even and $c_3$ is odd Find the number of nonnegative integer solutions to the equation $c_1 + c_2 + c_3 = 20$, where $c_2$ is even and $c_3$ is odd.
I started with finding the total number of solutions, $C(22,20)=231$. Then I tried to apply the inclusion-exclusion principle. Let $P_1$ be the number of solutions that do not satisfy the condition for $c_1$, $P_2$ for $c_2$ and so on.
$N-P_1-P_2-P_3+P_1P_2+P_2P_3+P_1P_3-P_1P_2P_3$ gives us the desired number of solutions. $P_1, P_1P_2, P_1P_3$ and $P_1P_2P_3$ are all zero because there is no condition for $P_1$. To find $P_2$, I assigned odd numbers to the $c_2$ and then calculated the number of solutions which is $110$. $P_3$ is also $110$. If I'm right up to this point, I'm stuck at finding $P_2P_3$.
To find the number of solutions that do not satisfy $c_2$ and $c_3$, I assigned $c_2$ odd numbers and $c_3$ even numbers. Adding an even and an odd number gives us an odd number. From what I previously calculated, I think there is a total of $110$ solutions again.
Thus, $231-110-110+110=121$. Is this true?

A: For reasons I will explain below, it is easier to solve this problem directly than to use the Inclusion-Exclusion Principle.
A direct approach:
Since $20$ is an even number, $c_2$ is odd, and $c_3$ is even, $c_1 = 20 - c_2 - c_3$ is also an odd integer.  Thus, there exist nonnegative integers $x_1, x_2, x_3$ such that $c_1 = 2x_1 + 1$, $c_2 = 2x_2$, and $c_3 = 2x_3 + 1$.
\begin{align*}
c_1 + c_2 + c_3 & = 20 \tag{1}\\
2x_1 + 1 + 2x_2 + 2x_3 + 1 & = 20\\
2x_1 + 2x_2 + 2x_3 & = 18\\
x_1 + x_2 + x_3 & = 9 \tag{2}
\end{align*}
Equation 2 is an equation in the nonnegative integers which has the same number of solutions as equation 1 subject to the stated constraints.  A particular solution of equation 2 corresponds to the placement of two addition signs in a row of nine ones.  For instance,
$$++ 1 1 1 1 1 1 1 1 1$$
corresponds to the solution $x_1 = x_2 = 0$, $x_3 = 9$ (and $c_1 = 1, c_2 = 0, c_3 = 19$), while
$$1 1 1 1 + 1 1 1 + 1 1$$
corresponds to the solution $x_1 = 4$, $x_2 = 3$, $x_3 = 2$ (and $c_1 = 9, c_2 = 6, c_3 = 5$).  The number of solutions to Equation 2 is
$$\binom{9 + 3 - 1}{3 - 1} = \binom{11}{2}$$
since we must select which two of the eleven positions required for nine ones and two addition signs will be filled by addition signs.
Remarks about your approach:
If you define $P_i$ to be the number of solutions that violate the constraint on $c_i$, then $P_iP_j$ is the product of $P_i$ and $P_j$.  Presumably, you meant $P_iP_j$ is the intersection of the sets of solutions that violate the constraint on $c_i$ and the constraint on $c_j$.
If you wish to the Inclusion-Exclusion Principle, you should define $A_i$ to be the set of solutions that violate the constraint on $c_i$, in which case the number of admissible solutions is
$$N - |A_1 \cup A_2 \cup A_3|$$
where
\begin{align*}
|A_1 \cup A_2 \cup A_3| & = |A_1| + |A_2| + |A_3|\\
                        & \quad - |A_1 \cap A_2| - |A_1 \cap A_3| - |A_2 \cap A_3|\\
                        & \qquad + |A_1 \cap A_2 \cap A_3|
\end{align*}
As stated above, the constraint that $c_2$ is even and $c_3$ is odd imposes the additional constraint that $c_1$ is odd.
Let's examine $|A_1|$.  If the condition that $c_1$ is odd is violated, then we need to find the number of solutions of the equation
$$c_1 + c_2 + c_3 = 20$$
subject to the constraint that $c_1$ is even.  If $c_1$ is even, then either $c_2$ and $c_3$ are both even or they are both odd.  If $c_2$ and $c_3$ are both odd, we need to find the number of solutions of the equation $c_1 + c_2 + c_3 = 20$ in which exactly two of the variables are odd, that is, we need to solve the original problem in order to use the Inclusion-Exclusion Principle. Therefore, it makes more sense to solve the problem directly.

A: Lets try to use generating functions such that
$c_1=x^0+x^1+...=\frac{1}{1-x}$
$c_2=x^0+x^2+....=\frac{1}{1-x^2}$
$c_3=x^1+x^3+...=\frac{x}{1-x^2}$
Then , $[x^{20}] \frac{1}{1-x} \times \frac{1}{1-x^2} \times \frac{x}{1-x^2} $.
So ,we should find the coefficient of $x^{19}$ in the expression of$C(k+1-1,k)x^k \times C(m+2-1,m)x^{2m} $ where $k+2m=19$
For $k=1 ,m =9 \rightarrow 10$
For $k=3 ,m =8 \rightarrow 9$
For $k=5 ,m =7 \rightarrow 8$
For $k=7 ,m =6 \rightarrow 7$
For $k=9 ,m =5 \rightarrow 6$
For $k=11 ,m =4\rightarrow 5$
For $k=13 ,m =3 \rightarrow 4$
For $k=15 ,m =2 \rightarrow 3$
For $k=17 ,m =1 \rightarrow 2$
For $k=19 ,m =0 \rightarrow 1$
As a result , the sum of coefficients are equal to $55$ . Then the answer is $55$

A: Alternative approach:
Any solution to $c_1 + c_2 + c_3 = 20$ where $c_2, c_3$ are of opposite parity (i.e. one odd, the other even) will occur if and only if $c_1$ is odd.  Further, for each of these solutions, you know by symmetry, that exactly $(1/2)$ of them will represent $c_2$ even and $c_3$ odd.
So, you may assume that $c_1 \in \{1,3,5,\cdots, 19\}.$
Further, for each such value of $c_1$, the problem will be represented by :
$c_2 + c_3 = (20 - c_1)$, which will have
$\displaystyle \binom{[20 - c_1] + [2-1]}{[2-1]} = (21 - c_1)$ solutions.
Therefore, the desired tally is
$$\left(\frac{1}{2}\right) \times \sum_{k = 1}^{10} (21 - [2k-1]) ~=~ \left(\frac{1}{2}\right) \times \sum_{k = 1}^{10} (22 - [2k]).$$
The right hand factor above is $220 - 2(55) = 110$.
Therefore, the final computation is $(110/2) = 55.$


text:
Q: text not showing in forcelayout d3js but present in view text is visible in source when viewed from web inspector but is not visible on real graph
<html>
<head>
<title>D3</title>
<script src="d3.min.js"> </script>
</head>
<body>

 <script type="text/javascript">

        //Width and height
        var w = 500;
        var h = 300;

        //Original data
        var dataset = {
            nodes: [
                { name: "Adam" },
                { name: "Bob" },
                { name: "Carrie" },
                { name: "Donovan" },
                { name: "Edward" },
                { name: "Felicity" },
                { name: "George" },
                { name: "Hannah" },
                { name: "Iris" },
                { name: "Jerry" }
            ],
            edges: [
                { source: 0, target: 1 },
                { source: 0, target: 2 },
                { source: 0, target: 3 },
                { source: 0, target: 4 },
                { source: 1, target: 5 },
                { source: 2, target: 5 },
                { source: 2, target: 5 },
                { source: 3, target: 4 },
                { source: 5, target: 8 },
                { source: 5, target: 9 },
                { source: 6, target: 7 },
                { source: 7, target: 8 },
                { source: 8, target: 9 }
            ]
        };

        //Initialize a default force layout, using the nodes and edges in dataset
        var force = d3.layout.force()
                             .nodes(dataset.nodes)
                             .links(dataset.edges)
                             .size([w, h])
                             .linkDistance([50])
                             .charge([-100])
                             .start();

        var colors = d3.scale.category10();

        //Create SVG element
        var svg = d3.select("body")
                    .append("svg")
                    .attr("width", w)
                    .attr("height", h);

        //Create edges as lines
        var edges = svg.selectAll("line")
            .data(dataset.edges)
            .enter()
            .append("line")
            .style("stroke", "#ccc")
            .style("stroke-width", 1);

        //Create nodes as circles
        var nodes = svg.selectAll("circle")
            .data(dataset.nodes)
            .enter()
            .append("circle")
            .attr("r", 10)
            .style("fill", function(d, i) {
                return colors(i);
            })
           .call(force.drag);

         //To display text
        nodes.append("text")
            .attr("x", 12)
            .attr("dy", ".35em")
            .text(function(d){  return d.name;

              });
        //Every time the simulation "ticks", this will be called
        force.on("tick", function() {

            edges.attr("x1", function(d) { return d.source.x; })
                 .attr("y1", function(d) { return d.source.y; })
                 .attr("x2", function(d) { return d.target.x; })
                 .attr("y2", function(d) { return d.target.y; });

           // nodes.attr("cx", function(d) { return d.x; })
            //     .attr("cy", function(d) { return d.y; });
             nodes.attr("transform", function(d){
                 return "translate(" + d.x + "," + d.y + ")";
            });

        });

</script>
</body>
</html>

here i am following this example:
http://bl.ocks.org/mbostock/2706022
and also followed this post:
D3.js, force-graph, cannot display text/label of nodes
Here is the jsfiddle for this code:
http://jsfiddle.net/devprashant/7kWwL/

A: The problem you're having is that your current code is appending <text> to a <circle>, which won't show up. Instead, you need to create a group <g> for each node that contains both the <circle> and the <text>. Try this:
var nodes = svg.selectAll("g")
    .data(dataset.nodes).enter()
    .append("g");

nodes.append("circle")
    .attr("r", 10)
    .style("fill", function (d, i) { return colors(i); })
    .call(force.drag);

nodes.append("text")
    .attr("x", 12)
    .attr("dy", ".35em")
    .text(function (d) { return d.name; });

Updated JSFiddle here.


text:
Q: can't find the error in Depth First Search code that runs forever Trying to implement Depth First Search. Implemented adjacency list using vector. Keeping track of vertices that have been explored by set "explored". "s" is the starting vertex. I think the problem is in while loop but can't figure out.
void AddEdge(vector<vector<int>>& adjList, int u, int v) {
    adjList[u].push_back(v);
    adjList[v].push_back(u);
}

    void dfs(vector<vector<int>>& adjList, int s) {
    stack<int> adjacent;
    set<int> explored;
    adjacent.push(s);
    while(adjacent.size() != 0) {
        int vertex = adjacent.top();
        adjacent.pop();
        if(explored.count(vertex) == 0)
            explored.insert(vertex);
            for(vector<int>::iterator itr = adjList[vertex].begin();
                    itr != adjList[vertex].end(); ++itr) {
                adjacent.push(*itr);
            }
    }
    for(set<int>::iterator itr = explored.begin(); itr != explored.end();
        ++itr) {
        cout << "vertices reachable from " << s << " are " << "--> " << *
        (itr);
    }
    }

Thanks in advance.

A: Your indentation is misleading you: the for loop is not inside the if block, and so it will make that adjacent gets the neighbors of visited vertices too. That ensures that the outer loop never ends.
Fix by adding braces:
    if(explored.count(vertex) == 0) { // <-- brace
        explored.insert(vertex);
        for(vector<int>::iterator itr = adjList[vertex].begin();
                itr != adjList[vertex].end(); ++itr) {
            adjacent.push(*itr);
        }
    } // <-- brace


text:
Q: Spring : How to configure tomcat Datasource Programatically in Groovy DAO I have my tomcat datasource configured in XML as below:
<bean id="docDataSource"
    class="org.apache.tomcat.jdbc.pool.DataSource"
    destroy-method="close"
    p:driverClassName="${doc.database.driver}"
    p:url="${doc.database.url}"
    p:username="${doc.database.user}"
    p:password="${doc.database.password}"
    p:validationQuery="select 1"
    p:testOnBorrow="true"
    p:minIdle="2"
    p:maxIdle="4"
    p:maxActive="6"
    p:defaultTransactionIsolation="1">
</bean>

And my customDAO(groovy class) uses the above datasource as below
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Component
import groovy.sql.Sql
import org.apache.log4j.Level
import javax.sql.DataSource
import java.util.Map
import java.util.Map.Entry
import java.util.ResourceBundle

@Component
public class customDao implements GroovyInterceptable {

    @Autowired
    private Services services

    @Autowired
    @Qualifier("docDataSource")
    private DataSource            dataSource
   // implementation
}

I wanna switch my tomcat dataSource to a class file instead of XML. Can someone help me how to do this?

A: Here's the piece of code you can follow (with PostgreSQL, but it should more or less work the same):
import org.postgresql.ds.PGPoolingDataSource
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

import javax.sql.DataSource

@Configuration
class PostgreSQLDatasourceConfiguration {

  @Bean(name = 'dataSource')
  DataSource ds(@Value('${DATABASE_URL}') String databaseFullUrl) {
    assert databaseFullUrl, 'Database URL is required to start the application'

    URI uri = new URI(databaseFullUrl)
    def (_, dbUsername, dbPassword) = (uri.getUserInfo() =~ /(.*):(.*)/)[0]

    (DataSource) new PGPoolingDataSource().tap {
      url = "jdbc:postgresql://$uri.host:${uri.port}$uri.path"
      password = dbPassword
      user = dbUsername
    }
  }
}


text:
Q: How to make background service run as a seperate process? We have developed one android application which will send the request and receive the response from the server and based on the response it will update the UI.This application handles so many different types of requests and it will enunciate as well as display the server status on the status bar.
this application is having around more than 50 different activities and one service handles all request/response and all activities bound to this service so whoever will send the request he will bind with the service and send the request and get the response back.
Now what problem we are facing is as we have added so many request/response because of that it seems like service becomes more overloaded, so obviously application is also get very slow.
So we have decided to make service as separate process including android:process for service in manifest file and try to implement AIDL for that.
But it is not that much easy because each activities making the connection with service and sends its textView,handler, activity to service using Service register() method.
so we can't go for AIDL because AIDL only supports primitive types.
So my doubts are:
1. can we make service as separate process and it should be there in same application and packaged with same apk?
2. how to handle situation mentioned above where activity depends on service with passing some objects to service and service updates those objects and activity uses it, when we implement AIDL(as far as i know AIDL only supports primitive types)?
3. Activity uses some member variables of service so if we changes to AIDL how to make use of those member variables(these member variables are custom objects)?
I tried my best to explain the problem with some examples so please provide me some valuable inputs.
Regards,
Piks.

A: Is it absolutely necessary that you send references to your text views? Sounds like adding android:process=":remote" should do what you want, but if you have the service running in another process, I don't think you should be trying to pass UI references. Can you not update the text views based on responses from the service?
If you are not allowing access from other application, you can just use a binder as described here http://developer.android.com/guide/developing/tools/aidl.html
This is what we did to pass lists of objects and it worked well.


text:
Q: Kendo UI Autocomplete open link in same tab/window Below example allow us to open a link in a new tab/window when user selects item from the AutoComplete.
http://jsbin.com/EQamewI/2/edit
How to modify window.open(href) to open the link in same tab/window?

A: Instead of window.open(href) use location.assign(href);
Documentation: http://www.w3schools.com/jsref/met_loc_assign.asp
If you are in an iframe, you can use top.location.assign(href);


text:
Q: Изменение шаблона регулярки Есть паттерн ~//(.+?)//~s, но нужно сделать, чтобы он не ловил http://site, то есть не срабатывал когда перед // идёт :.
Как можно это сделать?

A: Используйте блок предварительного просмотра назад (?<!:) (найди совпадение, если слева от текущей позиции нет :):
~(?<!:)//(.+?)//~s

Демо
В PHP есть возможность отлавливать нежелательные совпадения и отсеивать их с помощью (*SKIP)(*FAIL):
~\b(https?|ftps?)://(*SKIP)(*FAIL)|//(.+?)//~s

Ещё одно демо
Т.е. находим \b(https?|ftps?)://, границу слова, протоколы и ://, а потом  (*SKIP)(*FAIL) удаляют это совпадение из буфера, и следующее совпадение ищется с конца предыдущего совпадения.


text:
Q: Where to find $\lambda$-calculus examples? For instance, how to check if a list is empty? I'm trying to remove many layers of dust from my knowledge about $\lambda$-calculus, without my notes from classes (several hundreds of km and 5 years away).
I was trying to understand the examples in the web, but, even if they explain how different values are expressed and how functions should look like, they never explain how $\beta$-reduction is used to apply those functions to those values, and every explanation I could find on the web, without that crucial part, feels quite pointless. So, question 1, any place to find those examples? guess not, but this could be a nice place.
So as a simple example, how to check that a list is empty? I'm following the examples from here (good rank in google). So let's apply the "isEmpty" function to the empty list, that should be simple:

*

*$(\lambda l.l(\lambda a b.true)false)(\lambda fx.x)=_{ \alpha }$

*$ =_{ \alpha }(\lambda l.l(\lambda a b.\lambda a b.a)\lambda ab.b)(\lambda fx.x)=_{\beta}$

*$=_{\beta}(\lambda l.l(\lambda a b.\lambda a b.a)\lambda ab.b)[l:=(\lambda fx.x)]=_S$

*$=_S(\lambda fx.x)(\lambda a b.\lambda a b.a)\lambda ab.b= _{\beta}$

*$= _{\beta}(\lambda x.x)(\lambda a b.\lambda a b.a)[f:=\lambda ab.b]= _S$

*$= _S (\lambda x.x)\lambda ab.b= _{\beta}$

*$= _{\beta} x[x:=\lambda ab.b]= _S$

*$= _S \lambda ab.b =_{\alpha}$

*$=_{\alpha} false$

So the empty list is not empty...
question 2: What's wrong here?
Thank you very much.

A: Your reduction sequence looks correct, but the function you're applying is not isEmpty, but isNonempty.
If we're using Church representation and the the empty list is represented as $\lambda fx.x$, then the convention apparently is that the first argument to the list representation says what to do with a nonempty list, and the second argument is for an empty list. Your function is $\lambda l.l(\lambda ab.T)F$ which gives the list $F$ as a second argument -- and therefore $F$ is what you'll get at the end of the reduction.
As for web resources, a comment to this answer at SO leads to a site where you can enter lambda terms (in Haskell syntax) and see them reduce interactively.


text:
Q: Rotate linked list I'm currently solving problem.
If linked list is 1,2,3,4,5 and k=2 then output should be 4,5,1,2,3

My approach is create a two pointer for last node and second last node.After reaching a last node connect it's next to head and make second last pointer none.Continue this process till k values.
Excepted input and output are
class node:

def __init__ (self,data):
    self.data = data
    self.next = None

class linkedlist:

def __init__(self):
    self.head = None
    self.tail = None

def addlast(self,data):
    a = node(data)
    if self.head == None:
         self.head = a
         self.tail = a
    else:
        self.tail.next = a
        self.tail = a

def printlist(self):
    current = self.head
    while (current != None):
        print(current.data,"-->",end="")
        current = current.next
    print("NUll")

def rotatelist(self):
    k = 2
    while k:
        current = self.head.next
        previous = self.head

        while(current.next):
            current = current.next
            previous = previous.next

        current.next = self.head
        self.head= current
        previous = None

obj = linkedlist()
obj.addlast(1)
obj.addlast(2)
obj.addlast(3)
obj.addlast(4)
obj.addlast(5)
obj.rotatelist()
obj.printlist()

A: Try my solution.
class node:

    def __init__ (self,data):
        self.data = data
        self.next = None

class linkedlist:

    def __init__(self):
        self.head = None
        self.tail = None

    def addlast(self,data):
        if (self.head==None):
            self.head = self.tail = node(data)
        else:
            a = node(data)
            self.tail.next = a
            self.tail = a

    def printlist(self):
        current = self.head
        while (current != None):
            print(current.data,"-->",end="")
            current = current.next
        print("NUll")

    def rotatelist(self):
        k = 2
        while k:
            current = self.head.next
            previous = self.head

            while(current.next):
                current = current.next
                previous = previous.next

            current.next = self.head
            self.head= current
            previous.next = None
            k-=1
            if k<=0:
                break

obj = linkedlist()
obj.addlast(1)
obj.addlast(2)
obj.addlast(3)
obj.addlast(4)
obj.addlast(5)
obj.rotatelist()
obj.printlist()

A: There are four problems:

*

*The loop never ends because k is not adapted. It is more pythonic to loop over a range

*Setting previous to None does not do what you want. Instead previous.next should be set to None

*The function does not update self.tail, yet it should.

*There will be an error when the list has fewer than 2 elements -- then the code will make invalid references. You could capture this case and just return the list unchanged, as a rotation has no effect on a list with fewer than 2 elements.
Then, it is not very user-friendly to have the value of k hardcoded within this function. It should better be a parameter for which the caller can pass a value:
    def rotatelist(self, k):  # k should be parameter
        if self.head == self.tail:  # Fewer than 2 elements
            return
        for _ in range(k):  # Determine the number of iterations
            current = self.head.next
            previous = self.head

            while current.next:
                current = current.next
                previous = previous.next

            current.next = self.head
            self.head= current
            previous.next = None  # Correction
            self.tail = previous  # Update tail

obj = linkedlist()
obj.addlast(1)
obj.addlast(2)
obj.addlast(3)
obj.addlast(4)
obj.addlast(5)
obj.rotatelist(2)  # Pass the value of k
obj.printlist()

But still this method is not efficient. It needs to iterate the whole list for every rotation. Also, if k is much greater than the size of the list, a lot of time is wasted to rotate the list completely around, bringing it to its initial state again, and continue from there.
To make it more efficient, use k %= n (where n is the size of the list).
Temporarily make the list circular, then move the tail reference n-k steps forward, align head, and finally break the circle again:
    def size(self):
        size = 0
        current = self.head
        while current:
            size += 1
            current = current.next
        return size

    def rotatelist(self, k):
        if self.head == self.tail:
            return

        # Limit k to avoid useless iterations
        n = self.size()
        k %= n
        # Make list circular
        self.tail.next = self.head

        # Move tail
        for _ in range(n - k): # Determine the number of iterations
            self.tail = self.tail.next

        # Align head with tail
        self.head = self.tail.next
        # Break circle
        self.tail.next = None


text:
Q: GKE: kubernetes nodes don't require kubectl package Do we really need kubectl to be part of kubernetes nodes ?

A: I don't know if there is a "correct" answer to this. But, I feel it is needed as a resource created should be manageable.
I understand your point where we all have gcloud and kubectl installed to our local machine but this is not the case for everyone. There could be developers who only have SSH access to the nodes and not enough IAM role or even gcloud installed in their local machine. So, if you are just able to SSH into any of the nodes, you should be able to view (or add, delete and edit as per the requirement) the resources on the cluster.
Personally, I never felt a need for this in my case as I have an editor role in my project but there could be situations/people who do not even have gcloud or kubectl installed or any such access or they are using a VDI or for security constraints (e.g developers are allowed to carry their laptops to their homes) the organization not allowing these developers to have access to any such thing on there local and enforces to access them using these nodes only.
So, in my opinion, this could one of the use cases why the creators decided to keep it there in every node.

A: One more possibility can be compatibility issues. Imagine you upgrade kubectl on your local machine to a newer version that is incompatible(or a default behaviour is changed) with one of your older k8 clusters.
So in a way it is kind of ensuring that there is always a compatible version of kubectl running on the nodes.
Note: in ideal situations commands and apis should be backward compatible.


text:
Q: the remove method doesn't remove the class 'player--active' and the add method adds the class 'player--winner' but it doesn't apply the style why? The inspect window shows that the class 'player--active' was not removed and the class 'player--winner' was added but the style wasn't applied why?
let me just show to you my code....I'm a newbie and this is so confusing to me
THe HTML code
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <title>Pig Game</title>

Player 1

43

Current

0

Player 2

24

Current

0

      <button class="btn btn--new"> New game</button>
      <button class="btn btn--roll"> Roll dice</button>
      <button class="btn btn--hold"> Hold</button>

The CSS code
@import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}

html {
  font-size: 62.5%;
  box-sizing: border-box;
}

body {
  font-family: 'Nunito', sans-serif;
  font-weight: 400;
  height: 100vh;
  color: #333;
  background-image: linear-gradient(to top left, #753682 0%, #bf2e34 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* LAYOUT */
main {
  position: relative;
  width: 100rem;
  height: 60rem;
  background-color: rgba(255, 255, 255, 0.35);
  backdrop-filter: blur(200px);
  filter: blur();
  box-shadow: 0 3rem 5rem rgba(0, 0, 0, 0.25);
  border-radius: 9px;
  overflow: hidden;
  display: flex;
}

.player {
  flex: 50%;
  padding: 9rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.75s;
}

/* ELEMENTS */
.name {
  position: relative;
  font-size: 4rem;
  text-transform: uppercase;
  letter-spacing: 1px;
  word-spacing: 2px;
  font-weight: 300;
  margin-bottom: 1rem;
}

.score {
  font-size: 8rem;
  font-weight: 300;
  color: #c7365f;
  margin-bottom: auto;
}

.player--active {
  background-color: rgba(255, 255, 255, 0.4);
}
.player--active .name {
  font-weight: 700;
}
.player--active .score {
  font-weight: 400;
}

.player--active .current {
  opacity: 1;
}

.current {
  background-color: #c7365f;
  opacity: 0.8;
  border-radius: 9px;
  color: #fff;
  width: 65%;
  padding: 2rem;
  text-align: center;
  transition: all 0.75s;
}

.current-label {
  text-transform: uppercase;
  margin-bottom: 1rem;
  font-size: 1.7rem;
  color: #ddd;
}

.current-score {
  font-size: 3.5rem;
}

/* ABSOLUTE POSITIONED ELEMENTS */
.btn {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  color: #444;
  background: none;
  border: none;
  font-family: inherit;
  font-size: 1.8rem;
  text-transform: uppercase;
  cursor: pointer;
  font-weight: 400;
  transition: all 0.2s;

  background-color: white;
  background-color: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(10px);

  padding: 0.7rem 2.5rem;
  border-radius: 50rem;
  box-shadow: 0 1.75rem 3.5rem rgba(0, 0, 0, 0.1);
}

.btn::first-letter {
  font-size: 2.4rem;
  display: inline-block;
  margin-right: 0.7rem;
}

.btn--new {
  top: 4rem;
}
.btn--roll {
  top: 39.3rem;
}
.btn--hold {
  top: 46.1rem;
}

.btn:active {
  transform: translate(-50%, 3px);
  box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.15);
}

.btn:focus {
  outline: none;
}

.dice {
  position: absolute;
  left: 50%;
  top: 16.5rem;
  transform: translateX(-50%);
  height: 10rem;
  box-shadow: 0 2rem 5rem rgba(0, 0, 0, 0.2);
}

.player--winner {
  background-color: #2f2f2f;
}

.player--winner .name {
  font-weight: 700;
  color: #c7365f;
}

.hidden {
  display: none;
}

and finally the JavaScript code (which I think is the problem)
'use strict';
// Selecting elements
const player0El = document.querySelector('.player--0');
const player1El = document.querySelector('.player--1');
const score0El = document.getElementById('score--0');
const score1El = document.getElementById('score--1');
const diceEl = document.querySelector('.dice');
const current0El = document.getElementById('current--0');
const current1El = document.getElementById('current--1');
const btnNew = document.querySelector('.btn--new');
const btnRoll = document.querySelector('.btn--roll');
const btnHold = document.querySelector('.btn--hold');

// Starting conditions
score0El.textContent = 0;
score1El.textContent = 0;
diceEl.classList.add('hidden');
const scores = [0, 0]; // Arrays must start with const
let currentScore = 0;
let activePlayer = 0;

const switchPlayer = function () {
  document.getElementById(`current--${activePlayer}`).textContent = 0; // Which is basically for player 0
  currentScore = 0;
  activePlayer = activePlayer === 0 ? 1 : 0; // Changing the player
  player0El.classList.toggle('player--active');
  player1El.classList.toggle('player--active');
};

// Rolling dice functionality
btnRoll.addEventListener('click', function () {
  // 1. Generating a random dice roll
  let dice = Math.trunc(Math.random() * 6) + 1;
  // 2. display the dice
  diceEl.classList.remove('hidden');
  diceEl.src = `dice-${dice}.png`;
  // 3. CHeck for rolled 1
  if (dice !== 1) {
    // Add dice to current score
    currentScore += dice;
    document.getElementById(`current--${activePlayer}`).textContent =
      currentScore;
  } else {
    // Switch to next player
    switchPlayer();
  }
});

btnHold.addEventListener('click', function () {
  // 1. Add current score to the active player's score
  scores[activePlayer] += currentScore;
  // socres[1] = scores[1] + currentScore;
  document.getElementById(`score--${activePlayer}`).textContent =
    scores[activePlayer];
  // 2.check if the score is >= 100
  if (scores[activePlayer] >= 10) {
    // Finish the game
    document
      .querySelector(`.player--${activePlayer}`)
      .classList.add('.player--winner');
    document
      .querySelector(`.player--${activePlayer}`)
      .classList.remove('.player--active');
  } else {
    // Switch player
    switchPlayer();
  }
});

The inspect window shows that the class 'player--active' was not removed and the class 'player--winner' was added but the style wasn't applied why?


text:
Q: How to apply a clip rect to a group or something similar? I have a Phaser.group containing 6 images, the group has a height of 600px but I want only the first 3 images look with a height approximately 300px, for slot type effect on the images.
I have tried different options with .crop with mask, but I find the best solution.
How I can make a clipRect?
thanks

A: In the end I found a solution, I have problems with the positions of the Rectangle, here you have:
var maskGraphics = this.game.add.graphics(0,0);
maskGraphics.beginFill(200, 100, 0 , 0);
maskGraphics.drawRect(x , y, width,height);
maskGraphics.endFill();

this.mask = maskGraphics

You must create an image and give it a alpha 0, assigning the size you want it to have the visible.
Add that image as a mask to the object you want, in my case it is a group but can be another image or other objets.
Working correctly with phaser v2.0.6


text:
Q: java.lang.IllegalArgumentException: No view found for (android:id/content) A library we are using, Usabilla:
https://github.com/usabilla/usabilla-u4a-android-sdk/issues/180#
presents a banner fragment at any point in the app, when a certain event occurs.
The only method that we call to trigger the event, is this:
Usabilla.sendEvent(applicationContext,eventString)
It works fine when the activity layout has no fragment tag. But when we include a NavHostFragment in the layout, the app crashes because logger says that the view is null for (android:id/content). Any ideas what we could do to fix the issue (so that even with a NavHostFragment, the android:id/content will still be found)?
Stack trace:
2020-10-29 06:00:05.796 22184-22184/au.com.nib.memberapp.develop E/AndroidRuntime: FATAL EXCEPTION: main
Process: au.com.nib.memberapp.develop, PID: 22184
java.lang.IllegalArgumentException: No view found for id 0x1020002 (android:id/content) for fragment BannerFragment{32c54c0} (c7b3bbc0-668a-4553-9c52-f031b04f8a83) id=0x1020002}
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:315)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1199)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1368)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1446)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1509)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2181)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2004)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1959)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1861)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8167)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)

A: We resolved our issue above. The problem was with the Usabilla.updateFragmentManager (which needs to be called before Usabilla.sendEvent(applicationContext,eventString)). Before, we used the parentFragmentManager of the current fragment. We switched to activity.supportFragmentManager, and it worked.


text:
Q: Explanation of Android WebView onPageStarted/onPageFinished methods What I actually want to get specified, is that at what moments do these methods exactly get called?
Android documentation on WebView class references, that they get called when a page has finished loading and when a page has started loading. Loading what - loading the request or rendering the html?
I need to get a method to be called exactly when the html has been downloaded enough, that android webview will start displaying elements on the screen and the explanation for these methods in the documentation seem a bit confusing.
Thanks in advance,
ChillY

A: These methods are called when the network requests are started and finish. They have no relationship to content being ready to display or render.
Depending on your exact requirements, you could use the PictureListener callback[1] to let you know when the WebView has some content ready. However this may be flaky if you are loading many URLs, as the picture callback is not necessarily fired for the current URL load - you could receive a stale one for an old page during loading of the next page (e.g. imagine an old page was playing an animation while the new page is loading, or something like that).
An alternative that should work quite reliably is to play a short CSS animation in your HTML, and call back to Java via a JavaScript interface[2] when that animation completes. When you get that callback, WebView should be rendering the content.
[1] http://developer.android.com/reference/android/webkit/WebView.html#setPictureListener(android.webkit.WebView.PictureListener)
[2] http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)


text:
Q: Return products based on Seller ID - Amazon Product Advertising API I've been doing some research and it seems that the <MerchantId> was deprecated a few years ago. Anything other than "MerchantId"=>"Amazon" returns <MerchantId>Deprecated</MerchantId>
Has anyone found a way to search by merchant?


text:
Q: What do you call it when kernel of a matrix is sought with a set (nonzero) tolerance? This will be a strange question: I know what to do, and I am actually doing it, and it works, but I don't know how to write about it. Looking for solutions to a homogeneous matrix equation, say AX=0, I use the kernel of the parameter matrix A. But, the world being imperfect as it is, the matrix does not have a "perfect" kernel; it does have an "imperfect" one if you set a nonzero "tolerance" parameter. FWIW I'm using Scilab, the function is kernel(A,tol).
Now what are the correct terms for "imperfect kernel", or "tolerance" (of what?), how should this whole process be described in correct English and maths terminology? Should I say something like a "least-squares kernel"? "Approximate kernel"? Is tol the "tolerance of kernel-determination algorithm"? Sounds lame to me...

A: Depending on the method used (QR or SVD, third flag allows to choose this in Scilab implementation) the tolerance is used to determine when pivots (QR case) or singular values (SVD case) are consider to be zero. The kernel is then considered to be the associated subspace.


text:
Q: How to add a data point to an already existing .csv (with Python)? I am a complete newb at this and I have the following script..
It writes some random data to .csv.  My end goal is to keep this preexisting .csv but add ONE random generated datapoint to the beginning of this csv in a separate Python script.
Completely new at this -- not sure how to go about doing this.  Thanks for your help.
    output = [a,b]

    d = csv.writer(csvfile, delimiter=',', quotechar='|',

    quoting=csv.QUOTE_MINIMAL)
    d.writerow(output)

A: Are you sure you are trying to add it to the start of the file? I feel like you would want to add it to the end or if you did want to add it at the beginning you would at least want to put it after the header row which is ['name', 'value'].
As it stands your current script has several errors when I try to compile it myself so I can help you out a bit there.

*

*The directory string doesn't work because of the slashes. It will work if you add an r in front (for raw string) like so r'C:/Users/AMB/Documents/Aptana Studio 3 Workspace/RAVE/RAVE/resources/csv/temperature.csv'

*You don't need JSON to import json or logging if this is the entirety of your code.

*Inside of your for loop you redefine the temperature writer which is unnecessary, your definition at the start is good enough.

*You have an extra comma in your the line output = [timeperiod, temp,]
Moving on to a script that inserts a single data point. This script reads in your existing file. Inserts a new line (you would use random values, I used 1 for time and 2 for value) on the second line which is beneath the header. Let me know if this isn't what you are looking for.
directory = r"C:/Users/AMB/Documents/Aptana Studio 3 Workspace/RAVE/RAVE/resources/csv/temperature.csv"
with open(directory, 'r') as csvfile:
     s = csvfile.readlines()
time = 1
value = 2
s.insert(2, '%(time)d,%(value)d\n\n' % \
    {'time': time, "value": value})
with open(directory, 'w') as csvfile:
     csvfile.writelines(s)

This next section is in response to your more detailed question in the comments:
import csv
import random

directory = r"C:\Users\snorwood\Desktop\temperature.csv"

# Open the file
with open(directory, 'r') as csvfile:
    s = csvfile.readlines()

# This array will store your data
data = []

# This for loop converts the data read from the text file into integers values in your data set
for i, point in enumerate(s[1:]):
    seperatedPoint = point.strip("\n").split(",")
    if len(seperatedPoint) == 2:
        data.append([int(dataPoint) for dataPoint in seperatedPoint])

# Loop through your animation numberOfLoops times
numberOfLoops = 100
for i in range(numberOfLoops):
    if len(data) == 0:
        break

    del data[0] # Deletes the first data point
    newTime = data[len(data) - 1][0] + 1 # An int that is one higher than the current last time value
    newRandomValue = 2
    data.append([newTime, newRandomValue]) # Adds the new data point to the end of the array

    # Insert your drawing code here

# Write the data back into the text file
with open(directory, 'w') as csvfile: #opens the file for writing
    temperature = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)  # The object that knows how to write to files
    temperature.writerow(["name", "values"]) # Write the header row
    for point in data: # Loop through the points stored in data
        temperature.writerow(point) # Write current point in set


text:
Q: Multiplication In MASM611 hii i have a problem in multiplication for above 5 bits i'm working in MASM611 plz tell me the solution which is for atleast 8 bit multiplication in MASM611

A: for unsigned integer multiply, use mul; for signed use imul. if the operand is an 8-bit register, you get a 16-bit result.
for example:

mov al, 3
mov cl, 5
mul cl

puts 15 in ax.
study this page: http://web.archive.org/web/20120414214754/http://www.arl.wustl.edu/~lockwood/class/cs306/books/artofasm/Chapter_6/CH06-2.html


text:
Q: Error when opening Android Studio 3.0.1 Whenever I open my Android Studio 3.0.1 , I got this error

Error:Execution failed for task ':app:preDebugAndroidTestBuild'. >
  Conflict with dependency 'com.android.support:support-annotations' in
  project ':app'. Resolved versions for app (26.1.0) and test app
  (27.1.1) differ. See
  https://d.android.com/r/tools/test-apk-dependency-conflicts.html for
  details.

Please help.

A: use same version of dependencies
com.android.support:support-annotations:27.1.1

A: I also faced the same problem.So I am sharing solution which worked for me.Hope, help for you as well.
Go to the module level build.gradle in android studio and then change these three value that given below , sync the gradle.Install the plugin whatever android studio asking for downloading.

*

*compileSdkVersion 27

*targetSdkVersion 27

*implementation 'com.android.support:appcompat-v7:27.1.1'


text:
Q: ASP.NET SQL Server ConsumePreLoginHandshake Not enough memory Exception I have a web site that has recently started throwing the following error:
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - Not enough memory is available to complete this request)

Source: .Net SqlClient Data Provider

Method: Void OnError(System.Data.SqlClient.SqlException, Boolean)

Stack Trace:    at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.ConsumePreLoginHandshake(Boolean encrypt, Boolean trustServerCert, Boolean& marsCapable)
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at rbm.Portal.DAL.SiteManagerDB.GetTopLinks()

The GetTopLinks() is defined as:
public static List<Link> GetTopLinks()
        {
            List<Link> lLinks = new List<Link>();

            try
            {
                using(DbCommand dbCommand = GenericDataAccess.CreateCommand())
                {
                    dbCommand.CommandText = "RBM_V1_GetTopLinks";

                    dbCommand.Connection.Open();

                    using(DbDataReader dbReader = dbCommand.ExecuteReader())
                    {
                        if(dbReader.HasRows)
                        {
                            int intId = dbReader.GetOrdinal("id");
                            int intText = dbReader.GetOrdinal("text");
                            int intLink = dbReader.GetOrdinal("link");

                            while(dbReader.Read())
                            {
                                lLinks.Add(FillTopLinkDataRecord(dbReader, intId, intText, intLink));
                            }
                        }

                        dbReader.Close();
                    }

                    dbCommand.Connection.Close();
                }
            }
            catch(Exception ex)
            {
                lLinks = null;
                SiteManager.Instance.LogError(ex);
            }

            return lLinks;
        }

The FillTopLinkDataRecord method is defined as:
private static Link FillTopLinkDataRecord(IDataRecord drLink, int intId, int intText, int intLink)
        {
            Link lLink = new Link();

            if(!drLink.IsDBNull(intId))
            {
                lLink.Id = drLink.GetInt32(intId);
            }

            if(!drLink.IsDBNull(intText))
            {
                lLink.Text = drLink.GetString(intText);
            }

            if(!drLink.IsDBNull(intLink))
            {
                lLink.Url = drLink.GetString(intLink);
            }

            return lLink;
        }

The CreateCommand() is defined as:
public static DbCommand CreateCommand()
        {
            DbConnection dbConnection = CreateConnection();

            DbCommand dbCommand = dbConnection.CreateCommand();
            dbCommand.CommandType = CommandType.StoredProcedure;

            return dbCommand;
        }

        public static DbConnection CreateConnection()
        {
            DbProviderFactory dbFactory = DbProviderFactories.GetFactory(RbmConfiguration.DbProvideName);

            DbConnection dbConnection = dbFactory.CreateConnection();
            dbConnection.ConnectionString = RbmConfiguration.DbConnectionString;

            return dbConnection;
        }

The GetTopLinks is called from this code:
try
                {
                    if(HttpContext.Current.Cache["TopLinks"] == null)
                    {
                        HttpContext.Current.Cache.Insert("TopLinks", SiteDB.GetTopLinks() ?? new List<Link>(), null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
                    }

                    return ((List<Link>)HttpContext.Current.Cache["TopLinks"]);
                }
                catch(Exception ex)
                {
                    SiteManager.Instance.LogError(ex);
                    return null;
                }

Nothing much has changed with this code, it reads data from the SQL server and builds a menu for the site.
I'm confused as to where the problem lies, from the error I would assume that the SQL box is the problem, however an IISRESET on the IIS box seems to fix the problem for approx 24 hours.  The SQL box is W2K8R2 (64bit) and has 8 cores (2.99GHz), 8GB RAM and lots of free space (250+ GB).  The IIS box is W2K8R2 (64bit) and has 8 cores (2.66GHz), 4GB RAM and lots of free space (16 GB).
Has anyone seen this problem before?  Is the problem with SQL or IIS?  Any help would be appreciated.

A: There are a couple issues I see.
First, I don't see where you are disposing of your connections.  Which is probably the main issue here and why an IISRESET temporarily fixes the problem.
Connections will eventually get recycled, but if your load is high enough (and it doesn't have to be very high for this to break) then it's going to run out of memory for the pool.
Second, I know a number of dev's like to abstract away CreateCommand and CreateConnection, but I've never seen it implemented in a way that works long term.  The first thing I would do is rip those methods out as they are just single lines of code to begin with anyway.
FYI last week I fixed a site that used nearly the exact same code layout.  It was breaking with various errors with 30 people using the site.  Once I got rid of all the generic command and connection instantiation and properly surrounded the data calls with using statements the errors went away and now easily supports 100 times that number.


text:
Q: How to find the X and Y coordinates of a div element on-screen? So I have a div element that gets animated when you hover over it. I want to detect when the div element leaves the point 0, 0, and when it returns to 0, 0. I have the base code already, I just don't know the variables I would plug in.
var divx = getElementById("div").position.x;
var divy = getElementById("div").position.y;
if (divx === 0 && divy === 0) {
    window.alert("Div has returned to starting position")

And to finish off, I am just starting HTML and JavaScript, so if this is a super obvious solution, then I guess I'll have to go do more reasearch.

A: You can use getBoundingClientRect()
var rect = obj.getBoundingClientRect();

rect is an object with eight properties: left, top, right, bottom, x, y, width, height
source from MDN


text:
Q: Installing x64 Access driver on x64 Windows 7 with 32 bit Office I'm developing a Java application which needs to write to an Access database.   I am working on a Windows 7 x64 machine, using an x64 JVM, but our network team has installed the x86 (32 bit) versions of Office applications on our machines.   So when I try to install the x64 Access driver on my machine, I get this message:
You cannot install the 64-bit version of Microsoft Access Database Engine 2010
because you currently have 32-bit Office products installed.   If you want to
install 64-bit Microsoft Access Database Engine 2010, you will first need to
remove the 32 bit installation of Office products.   After uninstalling the
following product(s), rerun setup in order to install 64-bit version of Microsoft
Access Database Engine 2010:

Microsoft Office Professional Plus 2007

Does anyone have a clever way of bypassing this message?


text:
Q: what is ${wf:id()} meaning in HUE? Recently,I'm trying to understand company's code in HUE, I'm quite confused with the "${wf:id()}" in HDFS. Can someone explain what does it mean?

A: It is ooze expression language function, ${wf:id()} returns the workflow job ID for the current workflow job. Check section 4.2.3 Workflow EL Functions for detailed description.


text:
Q: Regular expression for any domain followed by a folder I have the following regular expression which basically returns .domain.com/
^[0-9a-zA-Z_\-.]{1,256}\.domain\.com/

I am looking to change the expression so that it returns any domain with a dot com extension that is followed by /js can anyone tell me how I can do this?
Thanks

A: Try this one:
^([\w\d_\-]+[\.]?[\w\d\-_]+)+\.com\/js$

A: You can try the following:
(?:http:\/\/)(.*?\.com(?=\/js\/))

If you can tell your regex processor to return capture group #1, you'll get any domain preceded by http:// and followed by /js/.
Otherwise (i.e. using this expression as a stand-alone), you'll get the domain including the http://.


text:
Q: Can anyone tell me why I'm still getting an INVALID_CLIENT message? Spotipy on mac I am trying to build a Spotify player with python and spotipy. I keep getting a message that says INVALID_CLIENT. The client id is entered properly along with the secret and the username
import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyClientCredentials

cid ="xx"
secret = "xx"
username = "xx"

client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

scope = 'user-library-read playlist-read-private'
token = util.prompt_for_user_token(username,scope,client_id='http://localhost:8888/callback/',client_secret='http://localhost:8888/callback/',redirect_uri='http://localhost:8888/callback/')

if token:
    sp = spotipy.Spotify(auth=token)
else:
    print("Can't get token for", username)
cache_token = token.get_access_token()

sp = spotipy.Spotify(cache_token)
currentfaves = sp.current_user_top_tracks(limit=20, offset=0, time_range='medium_term')

print(currentfaves)

A: You're using both the Client Credentials and Authorization Code Flow. To get user's top tracks, you need to use Authorization Code Flow.
You should remove the client credentials lines, then make sure the util.prompt_for_user_token call is configured properly. In your code, you have all parameters set to your redirect URI, which is giving you the Invalid Client error. Seems like you're following the Spotipy documentation, which is incorrect for this call. I'll try to make a PR.
Your code should look like this:
import spotipy
import spotipy.util as util

cid ="xx"
secret = "xx"
username = "xx"

scope = 'user-library-read playlist-read-private'
token = util.prompt_for_user_token(username,scope,client_id=cid,client_secret=secret,redirect_uri='http://localhost:8888/callback/')

if token:
    sp = spotipy.Spotify(auth=token)
else:
    print("Can't get token for", username)
cache_token = token.get_access_token()

sp = spotipy.Spotify(cache_token)
currentfaves = sp.current_user_top_tracks(limit=20, offset=0, time_range='medium_term')

print(currentfaves)


text:
Q: infinite algorithm. javascript i'm pretty new to js. i'm sorry if this sounds dumb.I have such an algorithm for javascript. when executed, it loops. Why? What is his mistake?
I have such source data
enter image description here
let incomesArray = [];
incomesArray[0] = {

    income_id: incomeList[0].id,
    worker_id: incomeList[0].worker_id,
    worker_surname: incomeList[0].worker_surname,
    worker_name: incomeList[0].worker_name,
    incomeList: [
        {
        provider_name: incomeList[0].provider_name,
        product_category: incomeList[0].product_category_name,
        product_name: incomeList[0].product_name,
        product_count: incomeList[0].product_count,
        purchase_price: incomeList[0].purchase_price
        }
    ],
    incomeDate: incomeList[0].date,
    total: incomeList[0].total
}

if(incomesArray.length > 0 ){
  for(let i = 1; i < incomeList.length; i++) {
    for(let j = 0; j < incomesArray.length; j++){
      if(incomeList[i].id == incomesArray[j].id){
          for(let k = 0; k < incomesArray[j].incomeList.length; k++){
                  incomesArray[j].incomeList.push({
                      provider_name: incomeList[i].provider_name,
                      product_category:
                      incomeList[i].product_category_name,
                      product_name: incomeList[i].product_name,
                      product_count: incomeList[i].product_count,
                      purchase_price: incomeList[i].purchase_price
                   })
               }
      } else if (incomesArray[j].id !== incomeList[i].id) {
        incomesArray.push({
            income_id: incomeList[i].id,
            worker_id: incomeList[i].worker_id,
            worker_surname: incomeList[i].worker_surname,
            worker_name: incomeList[i].worker_name,
            incomeList: [
                {
                provider_name: incomeList[i].provider_name,
                product_category: incomeList[i].product_category_name,
                product_name: incomeList[i].product_name,
                product_count: incomeList[i].product_count,
                purchase_price: incomeList[i].purchase_price
                }
            ],
            incomeDate: incomeList[i].date,
            total: incomeList[i].total
        })
      }
    }
  }
}

I will be grateful for any help or hint.

A: It's your else part that causes the problem. For every item in incomesArray that has a different id than the item in incomeList you add another entry to incomesArray; while you're iterating over that array. Like this gif:

Extending the track while you're driving on it.
Second, your comparison: if(incomeList[i].id == incomesArray[j].id) but incomesArray[j] has no id, only a income_id, so you'll always run into the else part where you add more items to incomesArray.
I've restructured your code a bit:
const incomesArray = [];

for (const row of incomeList) {
  let target = incomesArray.find(item => item.income_id === row.id);

  if (!target) {
    incomesArray.push(target = {
      income_id: row.id,
      worker_id: row.worker_id,
      worker_surname: row.worker_surname,
      worker_name: row.worker_name,
      incomeList: [],
      incomeDate: row.date,
      total: row.total
    });
  }

  target.incomeList.push({
    provider_name: row.provider_name,
    product_category: row.product_category_name,
    product_name: row.product_name,
    product_count: row.product_count,
    purchase_price: row.purchase_price
  });
}


text:
Q: Excel: "SUMIF" with multiple criterias I want to do a sum of cells, with multiple criterias. I have found out that the way to do it is with sumproduct. Like this
=SUMPRODUCT((A1:A20="x")*(B1:B20="y")*(D1:D20))

The problem I am having is that the A row consists of merged cells (which I can't change)
In my case I want to do a sum of every number in the given row under both 2010 and 2011 meeting my criterias.
2010 sum:
Every number in the same column as

*

*Row 1 = "Felles" and Row 3 = "2010"

*and

*Row 2 = "Ordinary" and Row 3 = "2010"

This seems easy enough.
=sumproduct((A1:L1 = "Felles") * (A3:L3 = 2010) * (A5:L5)) + sumproduct((A2:L2 = "Ordinary") * (A3:L3 = 2010) * (A5:L5))

The problem arises when I am to do the same for the 2011 numbers. The only problem is that "Felles" is not in the same column, as it is merged with 6 cells covering each group.
2011 sum:
Every number in the same column as
- Row 1 (2 columns back) = "Felles" and Row 3 = "2011"
- and
- Row 2 = "Ordinary" and Row 3 = "2011"

A: Have you looked at SUMIFS(), its for doing SUMIF() with multiple criteria. This function will allow you to do exactly what you want to do, see the SUMIFS documentation.
Example:
SUMIFS(A5:L5,A3:L3,"=2010",A2:L2,"=Ordinary")

If you are having trouble with merged cells just un-merge them, or try using named ranges (under the formulas tab).


text:
Q: How to reference another method of the same class in Javadoc? Suppose your class has 2 methods:
contains() and
containsSame()

The distinction between them is subtle and you'd like to mention it as part of Javadoc
In Javadoc, how can you reference a method in the same class, by name?

A: Use the @link inline tag, and refer to the method with a leading #.
/**
 * ...
 * This method is similar to {@link #contains()}, with the following differences:
 * ...
 */
public boolean containsSame();

/**
 * This method does ...
 */
public boolean contains();

This example only works if there is actually a contains() method which has no arguments (which, actually, seems to be not that useful). If you have only a contains method with arguments, then either write the argument types in the parentheses:
/**
 * ...
 * This method is similar to {@link #contains(Element)}, with the following differences:
 * ...
 */
public boolean containsSame(Element e);

/**
 * This method does ...
 */
public boolean contains(Element e);

Or you can omit the parentheses completely:
/**
 * ...
 * This method is similar to {@link #contains}, with the following differences:
 * ...
 */
public boolean containsSame(Element e);

/**
 * This method does ...
 */
public boolean contains(Element e);

If you have several methods named contains (with different parameter lists), this version can't decide which one to use (the link will jump to any of them, hopefully they are all together and do similar things).


text:
Q: How would I use the objects from a related Model to populate the initial value of a Field in a ModelForm? My issue is with the 5th line below (the one with all of the question marks):
class EditProfileForm(forms.ModelForm):
    """ Base form used for fields that are always required """
    first_name = forms.CharField(label=_(u'First name'), max_length=30, required=False)
    last_name = forms.CharField(label=_(u'Last name'), max_length=30, required=False)
    language = forms.ModelMultipleChoiceField(label=_(u'Language'), queryset=Language.objects.all(), initial=VolunteerLanguage.objects.filter(volunter=??????????))
    categories = forms.ModelMultipleChoiceField(label=_(u'Categories'), queryset=TaskCategory.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False)

    def __init__(self, *args, **kw):
        super(EditProfileForm, self).__init__(*args, **kw)
        self.profile = super(EditProfileForm, self).save(True)
        # Put the first and last name at the top
        new_order = self.fields.keyOrder[:-3]
        new_order.insert(0, 'first_name')
        new_order.insert(1, 'last_name')
        new_order.insert(2, 'language')
        self.fields.keyOrder = new_order

    class Meta:
        model = get_profile_model()
        exclude = ['user', 'editions', 'tasks', 'signed_up', 'language']

    def save(self, force_insert=False, force_update=False, commit=True):
        profile = super(EditProfileForm, self).save(commit=commit)
        # Save first and last name
        VolunteerLanguage.objects.filter(volunteer=profile).delete()
        for lang in self.cleaned_data['language']:
            languages = VolunteerLanguage(volunteer=profile, language=lang)
            languages.save()
        user = profile.user
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

        return profile

The problem is that I cannot retrieve the objects from VolunteerLanguage (link table) as I need to pass a Volunteer object to it in order to filter it. I can do that in the save method, but not on line 5

A: If you want to pass an additional parameter to your form and use that value to setup a field you can do something like this:
class EditProfileForm(forms.ModelForm):

    def __init__(self, initial_volunteer, *args, **kwargs):
            super(EditProfileForm, self).__init__(*args, **kwargs)
            self.fields['language'] = forms.ModelMultipleChoiceField(
            label=_(u'Language'),
            queryset=Language.objects.all(),
            # now you have the value you passed to use here
            initial=VolunteerLanguage.objects.filter(volunteer=initial_volunteer)
            )

If the self.profile already in your __init__ is the one you want to use you can create your field in the __init__ the same way as my example just don't pass a new value and use your self.profile instead.


text:
Q: Nautilus will not launch after update to 12.10 I updated to Ubuntu 12.10 today from 12.04 using the graphical update tool.  Everything seemed to be fine until I went to open Nautilus, and it would not open.  Bizarrely, I am able to open a file that I happen to have on my desktop, but when I click on the launcher, it never opens.  When I enter 'nautilus' in the terminal, I get this:
    (nautilus:8557): Gdk-CRITICAL **: gdk_x11_display_get_xdisplay: assertion `GDK_IS_DISPLAY (display)' failed
    zsh: segmentation fault (core dumped)  nautilus

I am not a total novice with ubuntu or linux, but all I can tell is that there is some problem with X.  Can someone please point me in the right direction as far as fixing this?  I really don't want to have to do a fresh install.  Thank you very much.

A: I have updated my Nautilus and since the update I experience the same issues, obviously this is a bug in the current release and will hopefully get fixed as soon as possible.
if you want to get it back to work you either wait for an update or you roll back to Nautilus 3.4, using the following command:
 sudo ppa-purge ppa:gnome3-team/gnome3

if you haven't installed it yet, just run
sudo aptitude install ppa-purge

it should be in the offical repository, if this is not the case, here is the ppa
ppa purge  ppa
EDIT: the latest update of Nautilus solved this issue, its now possible to use nautilus 3.6 again!