text:
Q: Using Google Colab and need help in output of plotting I have the following code that I ran on Google Colab but I think it should plot a graph on output ! Is this right or wrong ?
Code:
# plotting a scatter matrix
from matplotlib import cm
from pandas.plotting import scatter_matrix

X = fruits[['height', 'width', 'mass', 'color_score']]
y = fruits['fruit_label']
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

cmap = cm.get_cmap('gnuplot')
scatter=pd.plotting.scatter_matrix(X_train, c= y_train, marker = 'o', s=40, hist_kwds={'bins':15},
figsize=(9,9), cmap=cmap)
scatter

I am getting the output as following:

A: Thank you to all the people who tried solving my problem !
I just found out the solution.I used the following code in the beginning:
%matplotlib inline
plt.close('all')


text:
Q: Attribute contains word selector returning empty array I have some HTML resembling this:
<input name="arr[something completely random][something else I can't rely on][initial]" />
<!-- ... -->
<input name="arr[dadedadeda][blahblahblah][initial]" />

And my JavaScript document.querySelectorAll('[name~="initial"]') returns [] (empty). Why? Are multidimensional arrays in names dealt with differently? Is there something I'm missing?
I just tried document.querySelectorAll('[name$="[initial]"]'), the ends with selector (attr$="endStr"), and this returns what I need, but I still need to know why the attribute contains selector (attr~="inStr") is failing to work

A: For the word contains filter, the word should be separated by spaces, in your case that fails since you have the word enclosed in []
instead you can use contains selector like
document.querySelectorAll('[name*="initial"]')
document.querySelectorAll('[name*="[initial]"]')//to be more specific

redpajama_set_name: RedPajamaStackExchange


text:
Q: Employee churn as time-to-failure/survival analysis? I have an employee churn problem where I have data for every three months of employees in a company ranging from 2015-2019. Does it make sense to model this problem as a time-to-failure/survival analysis problem?
I've seen some studies where survival analysis/time-to-failure has been applied to customer churn, however I am wondering if it also applies to employee churn.
Furthermore:

*

*An assumption in time-to-failure is that the observations have a degrading aspect with relation to time, which I don't think it is quite applicable to churn. I.e. a customer/employee who has stayed for 20 years with the company is less likely to leave it, not more likely as time-to-failure analysis would expect it to. Am interpreting this wrong?

*If these types of analysis fit churn prediction, should only the churning employees/customers be considered in the training set, or should all employees/customers be considered?
Thank you!

A: Yes it makes sense, and all employees should be considered (up to the time they leave)
I think you are slightly confusing the time to failure analysis:
Probability of failing in each time period is independent of what happened before. However, a basic model with no time dependence fitted to eg up to 5 year employees will sooner or later churn, so your 20 year employee is unlikely to occur... But there is no reason that you can't add eg time dependence in your model ( eg probability of churning in each 3 month period decays linearly with time period), and you can add arbitrary nonlinear functions of time too.
Treat as discrete time survival analysis
Use a probabilistic classifier such as logistic regression or xgboost to predict churn in each 3 month period for each employee (add all the variables you want, time or employee..
)
Then you have 2 small issues.
A) generate person period data set
B) generate survival time profile by chaining survival probability of each period. IE prob survival in 9 months  = product of probability of survival of each 3 month period.
https://stats.idre.ucla.edu/r/faq/how-can-i-convert-from-person-level-to-person-period/


text:
Q: HTML: defining relative paths relative to another file Question: How would I construct relative paths in HTML relative to a different file than that I am working in?
Purpose: The navigation menu is ported to each page using the PHP include function. This, however, destroys the relative links embedded in the menu.


text:
Q: How do you make a cursor loop a JFrame to keep it in focus? So I am making a 3D game in Java with no engine, and the only problem I've encountered is that if I move the cursor too much to one side, it will become visible again (as I make it invisible when focused) and lose focus. Is there some method I can implement that would loop the cursor back to the other end of the screen, instead of going off the screen? An example would be an 800x600 window of Minecraft open and you move the cursor all the way to one side, but it still stays focused on the game.

A: You can use the Robot.moveMouse(...) method to move the mouse cursor. I guess you would do this when you loseFocus.


text:
Q: Partition problem While doing some programming, I found that I needed to design or implement an algortihm to basically do the same as the Partition Problem,that consists in partitioning a set of integers in two groups with the most equitative sum, but with floating point numbers. Is there any "efficient" solution? I know it is NP-hard, but I at least would like a "not-so-exponential" algorithm. Any help or ideas is greatly appreciated.

A: Well, the best answer depends on the parameters of the problem. It is only nasty-nasty-nasty exponential if the numbers get large - large as in n bits for a large value of n, not large as in the number itself is large. For instance, if you had a thousand files that were all less than 10 megabytes in size and you wanted (for some reason) to put them on two DVDs and you wanted both DVDs to have the exact same amount of file space used, THAT could be solved very quickly. It would only take billions of billions of years if you threw out the constraint that they were all less than 10 megabytes in size and had the sizes capable of being things like 10^100 megabytes. This is the difference between strongly exponential and just exponential - because 10^100 is only a 100-digit number you see, and only takes 300ish bits to express.
One thing you could do - is use the fourier transform, and the property that convolution in time domain is equivalent to multiplication in frequency domain. So the dual possibilities that an element is in one set of the partition or the other, means it is either added or subtracted. So basically, if your numbers are 3, 7, 37, 22, and 101, you would have a function which is an impulse at 3 and -3, and another function which is an impulse at 7 and -7, etc., and then you convolve them all together; and by that I mean, you take the fourier transform, you multiply them, and then you just take the average of that function - if it is 0, then there is a frequency-0 component of 0, meaning there is no solution. And if it is nonzero, then there is a solution.
If however you do have some fairly large numbers (numbers like 10^100 taking 300 bits, not numbers like 10^300000 taking a megabyte), and you weren't concerned with getting an EXACT solution but just wanted to see if there was a NEAR solution, you could do the same concept - except just divide all the numbers by a power of 2 and round to the nearest integer, or perhaps round up AND down and have impulses at both integers, perhaps have the one it is closer to be an appropriately larger impulse. Then you wouldn't be doing a fourier transform on an unruly large quantity of points.


text:
Q: Add new status for task in Maniphest (Phabricator)? How can I add a new status in Phabricator's Maniphest? I want to add In Progress.

*

*The feature seems to be available: https://secure.phabricator.com/T1812

*But no documentation on how to use it: https://secure.phabricator.com/book/phabricator/ (or I have missed it)

Yes thanks, something like this gets me there:
https://my.phab.com/config/edit/maniphest.statuses/

A: Config -> Applications -> Maniphest -> maniphest.priorities


text:
Q: NaN values in pivot_table index causes loss of data Here is a simple DataFrame:
> df = pd.DataFrame({'a': ['a1', 'a2', 'a3'],
                     'b': ['optional1', None, 'optional3'],
                     'c': ['c1', 'c2', 'c3'],
                     'd': [1, 2, 3]})
> df

    a          b   c  d
0  a1  optional1  c1  1
1  a2       None  c2  2
2  a3  optional3  c3  3

Pivot method 1
The data can be pivoted to this:
> df.pivot_table(index=['a','b'], columns='c')
                d
c              c1   c3
a  b
a1 optional1  1.0  NaN
a3 optional3  NaN  3.0

Downside: data in the 2nd row is lost because df['b'][1] == None.
Pivot method 2
> df.pivot_table(index=['a'], columns='c')
      d
c    c1   c2   c3
a
a1  1.0  NaN  NaN
a2  NaN  2.0  NaN
a3  NaN  NaN  3.0

Downside: column b is lost.
How can the two methods be combined so that columns b and the 2nd row are kept like so:
                d
c              c1   c2   c3
a  b
a1 optional1  1.0  NaN  NaN
a2      None  NaN  2.0  NaN
a3 optional3  NaN  NaN  3.0

More generally: How can information from a row be retained during pivoting if a key has NaN value?

A: Use set_index and unstack to perform the pivot:
df = df.set_index(['a', 'b', 'c']).unstack('c')

This is essentially what pandas does under the hood for pivot.  The stack and unstack methods are closely related to pivot, and can generally be used to perform pivot-like operations that don't quite conform with the built-in pivot functions.
The resulting output:
                d
c              c1   c2   c3
a  b
a1 optional1  1.0  NaN  NaN
a2 NaN        NaN  2.0  NaN
a3 optional3  NaN  NaN  3.0

A: You could use fillna to replace the None entry:
df['b'] = df['b'].fillna('foo')
df.pivot_table(index=['a','b'], columns=['c'])
----
                    d
c              c1   c2   c3
a  b
a1 optional1  1.0  NaN  NaN
a2 foo        NaN  2.0  NaN
a3 optional3  NaN  NaN  3.0

A: Use this one:
def pivot_table(df, index, columns, values):
    df = df[index + columns + values]
    i  = len(index)
    df = df.set_index(index+columns).unstack(columns).reset_index()
    df.columns = df.columns.droplevel(1)[:i].append(df.columns.droplevel(0)[i:])
    return df

pivot_table(df, index =['a', 'b'], columns= ['c'], values= ['d'])

A: You can use fillna to replace type None to string "NULL"
Say...
df.fillna("NULL").pivot_table(index=['a'], columns='c')


text:
Q: Javascript not importing variable from another file formFields.js
export const invoiceFormFields = [
    {label: 'First Name', name: 'firstName', type: 'text'},
    {label: 'Last Name', name: 'lastName', type: 'text'},
    {label: 'Deliverables', name: 'deliverables', type: 'text'},
    {label: 'Email', name: 'email', type: 'email'},
    {label: 'Amount', name: 'amount', type: 'number'}
]

InvoiceForm.js
import React, { useContext } from 'react'
import { NewInvoiceContext } from '../../contexts/newInvoice.context'
import { Link } from 'react-router-dom'
import {
    Typography,
    Paper,
    TextField,
    makeStyles,
    Button,
    CssBaseline,
} from '@material-ui/core'

import { invoiceFormFields } from './formFields'

const useStyles = makeStyles((theme) => ({
    title: {
        marginBottom: '1rem',
    },
    form: {
        display: 'flex',
        flexDirection: 'column',
    },
    formInput: {
        marginTop: '1rem',
    },
    formButtons: {
        display: 'flex',
        marginTop: '2rem',
        justifyContent: 'space-between',
    },
}))

const InvoiceForm = ({ history }) => {
    const classes = useStyles()
    const {formDetails, handleFormChange, handleShowReview} = useContext(NewInvoiceContext)

    const newInvoiceFields = invoiceFormFields.map(({ label, name, type }) => (
        <TextField
            key={name}
            label={label}
            name={name}
            className={classes.formInput}
            type={type}
            required
            onChange={handleFormChange}
            value={formDetails[name]}
        />
    ))

}

export default InvoiceForm

I'm getting the error
Attempted import error: './formFields' does not contain a default export (imported as 'formFields').
From what I can see I'm exporting and importing correctly - does anyone have any ideas what could be happening here?
Thanks

A: I suppose this would make it work.
export const invoiceFormFields = [
    {label: 'First Name', name: 'firstName', type: 'text'},
    {label: 'Last Name', name: 'lastName', type: 'text'},
    {label: 'Deliverables', name: 'deliverables', type: 'text'},
    {label: 'Email', name: 'email', type: 'email'},
    {label: 'Amount', name: 'amount', type: 'number'}
];

export default {
    invoiceFormFields,
}

import { invoiceFormFields } from './formFields';


text:
Q: How to access the outlook folders other than default ones (like Inbox, Sent) using python win32com? This is how I am able to access the inbox:
   outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
   inbox = outlook.GetDefaultFolder("6")

When I tried to access the user created folders in Outlook using the below code:
   outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
   Folder = outlook.Folders[1]
   print (Folder)

I got this error:
  raise IndexError("list index out of range")

IndexError: list index out of range

Any help would be appreciated.

A: Globally, you can do:
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
root_folder = outlook.Folders.Item(1)

Then you can check the name of this folder by
print (root_folder.Name)

And to know the names of the subfolders you have:
for folder in root_folder.Folders:
    print (folder.Name)

Finally, let's say you want to access a subfolder named folder_of_soldy in your root_folder, you do:
soldy_folder = root_folder.Folders['folder_of_soldy']

And so on if you have other subfolders in folder_of_soldy.
Hope you find what you need


text:
Q: How do you update a Stripe customer's usage record at the end of a billing cycle? For a metered pricing plan, rather than running a daily cron to create usage records for every customer, I'm listening for the invoice.created event triggered at the end of a billing cycle and updating the invoice with metered usage.
Unfortunately, I can't add a usage record because ERROR: Cannot create the usage record with this timestamp because timestamps must be after the subscription's last invoice period (or current period start time). So I have to manually create a new line item instead of using the pricing plan.
It would be great if usage records created during the draft period of an invoice could be added to that billing cycle. Is that possible? I imagine it would save Stripe a massive amount of api hits if it were. Is there another webhook right before an invoice gets created I can hook into?


text:
Q: Edit and delete row functionality in datatables using jquery? I had to design a table view using datatables and bootstrap which has the following view

I added values to table by using the following code
function updateTable(){
     var content = $.ajax(
      {
       url:"http://192.168.1.2:8080/alpharithm/employee/employeeDetails",
       dataType:"json",
        type:"GET",

        success : function(data) {

         var arr1= [];
            var arr= new Array();
            $.each( data, function(i, obj) {
                     arr = obj;
                     arr1.push(arr);

            });

        console.log(arr1[0]);

         $('#employeeTable').dataTable( {

          "aaData":arr1,
          "destroy":true,
           /*"columns": [
              { "data": "employee_id" },
              { "data": "division" },
              { "data": "first_name" },
              { "data": "mobile_number" },
              { "data": "home_number" },
              { "data": "company_mail" },
              { "data": "personal_mail" },
              { "data": "date_of_birth" },
              { "data": "date_of_joining" },
              { "data": "blood_group" },
              { "data": "emergency_contact" },
              { "data": "emergency_phone" },
              { "data": "permanent_address" },
              { "data": "current_address" },
              { "data": "bank_name" },
              { "data": "bank_branch" },
              { "data": "banck_account_no" },
              { "data": "pancard_no" },
              { "data": "" },
              { "data": "" }

              ],*/
           "aoColumns": [{
              "sWidth": "5%",
            "mData": "employee_id"
              }, {
            "sWidth": "5%",
            "mData":  "division"
              }, {
            "sWidth": "5%",
            "mData": "first_name",
            "mRender":function(data, type, full){
                  return full.first_name +" "+ full.last_name ;
                   }
              }, {
            "sWidth": "5%",
            "mData": "mobile_number"
              }, {
            "sWidth": "5%",
            "mData": "home_number"
              }, {
            "sWidth": "5%",
            "mData": "company_mail"
              },{
            "sWidth": "5%",
            "mData": "personal_mail"
              },{
            "mData": "date_of_birth"
              }, {
            "sWidth": "5%",
            "mData":  "date_of_joining"
              }, {
            "sWidth": "5%",
            "mData": "blood_group"
              }, {
            "sWidth": "5%",
            "mData": "emergency_contact"
              }, {
            "sWidth": "5%",
            "mData": "emergency_phone"
              }, {
            "sWidth": "5%",
            "mData": "permanent_address"
              },{
            "sWidth": "5%",
            "mData": "current_address"
              },{
            "sWidth": "5%",
            "mData": "bank_name"
              },{
            "sWidth": "5%",
            "mData": "bank_branch"
              }, {
            "mData": "banck_account_no"
              }, {
            "sWidth": "5%",
            "mData":  "pancard_no"
              },
                          {
            "mData": null,
            "bSortable": false,
            "mRender": function(data, type, full) {
              return '';
                            }
              },
              {
            "mData": null,
            "bSortable": false,
            "mRender": function(data, type, full) {
              return 'Edit&nbspDelete';
            }
              }],
           "iDeferLoading": 57
           });

        }

      });

  }

I want to edit and delete and edit each row separately.I tried many methods but edit an delete is not working. How to Edit and delete rows separately? Thanks in advance.

A:  $('#employeeTable a.delete').on('click', function(e) {

The above line is not working, because the delete button is dynamic created, you may use
 $('#employeeTable').on('click', 'a.delete', function(e) {

instead
Besides, your delete and edit button are inside the detail panel, you cannot just simply use
var nRow = $(this).parents('tr')[0];
oTable.fnDeleteRow(nRow);

to delete the whole record, because nRow is the expanded detail panel only, if you investigate using the chrome inspector/firebug, you would see that, once you clicked the "+" detail button, a  with class "child" will be append to your target row.
One of the solution you may try is
$('#employeeTable').on('click', 'a.delete', function(e) {
    e.preventDefault();
    var nRow = $(this).parents('tr')[0];
    var parent = $(nRow).prev();
    oTable.fnDeleteRow(parent);
});

I guess there may be some better approach other than using $(nRow).prev() to get its parent row
Demo link:
http://jsfiddle.net/s5k4hL0v/


text:
Q: Wizard populating Combobox column on Winform DataGridView I'm using C# VS2010 Entity Framework sql Server.
I have a very (read-only) simple app to show and filter work orders by project and discipline. It uses EF to populate the controls. Using the wizard, I changed the Foreign Key reference column "DisciplineID" (int) to a ComboBox column. When I changed it using the wizard, I populated the box using the EF datasource for the Discipline table (tblDiscipline) to simply display the Discipline (Plumbing, Electrical, etc.) instead of the integer foreign key. Here's the wizard image:

When I leave the ProjectID column as a text box control, it works fine, showing the integer Discipline ID. When I change it as shown, I get the following

"System.ArgumentException: DataGridViewComboBoxCell value is not
  valid"

.
The DisciplineID can be null. Is that the issue? How do I deal with it? Or is something else wrong. This is a production db, so referential integrity guarantees no invalid keys, though null is allowed...
Ideas?


text:
Q: SharePoint Online Connectors not working and now missing I'm using SharePoint online, Plan 1 with modern Team sites and Communication sites.  I was having an issue adding any connector, I could add the connector but when I clicked on "configure connector", I would get a "Something went wrong" error with a sad face.  I've tried creating new site collections, tried different site templates, tried all the web connectors I could find, and still the same error.  I'm particularly interested in the Jira and Webhooks connectors but also tried Asana and several other.  I have also noticed the same error when using Yammer connectors however unsure if related.
After a lengthy email exchange with Office 365 support, I find that connectors are no longer available to me and now missing.  I also received an email stating the following:

After some consultation and research, we're very sorry to inform you
  that the issue seems to be a bit out of scope and we don't have a
  specialist to help you out either, however, below, I've attached a
  link which takes you to our solution providers for SharePoint. There
  are a few solution providers, who should be able to help you, and
  please choose the one that fits your issue. Type SharePoint on the
  search section. The support on that platform is paid support, and not
  free like ours.

Has anyone else run across issues with the Connectors?   I'm tempted to go back to the "classic" site but was really liking the modern web parts and connectors.   I'm surprised it's not more functional by now.


text:
Q: Get all databases and convert to String Array How to add all the databases from server to String array in java? I am using JOOQ api to execute SQL statements and i need to get all the databases in comboBox where i can select specific database.

A: You have several options. For instance, you could use the generated
classes from jOOQ-meta (or generate the information_schema yourself),
and then write:
Factory create = new Factory(connection, dialect);
String[] array =
create.selectDistinct(TABLES.TABLE_SCHEMA)
      .from(TABLES)
      .fetchArray(TABLES.TABLE_SCHEMA);

The same can be achieved through plain SQL, of course:
String[] array =
create.selectDistinct(field("table_schema"))
      .from("information_schema.TABLES") // Watch for case-sensitivity on MySQL
      .fetchArray(0, String.class);

Or, using the SHOW TABLES command:
String[] array =
create.fetch("SHOW TABLES")
      .intoArray(0, String.class);

Another option would be to read from JDBC's DatabaseMetaData:
Connection connection = ...;
DatabaseMetaData meta = connection.getMetaData();
String[] array = create.fetch(meta.getSchemas()).intoArray(0, String.class);

In jOOQ 3.0, you will also be able to read the meta data through the jOOQ API:
List<Schema> schemas = create.meta().getSchemas();


text:
Q: Hibernate assertEquals fails after objects are persisted I am using Hibernate for my DAO implementation. I created the mappings and I overriden the equals method.
When I use assertEquals(object,object) it fails even though the objects are identical.
Book.java
package tn.jebouquine.pojo;

@Entity
public class Book {
    @Id
    private String ISBN;
    @NotEmpty
    private String name;
    @NotNull
    @DecimalMin(value = "0.00")
    private BigDecimal price;
    private String description;
    @ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    @NotEmpty
    private List<Author> authors = new ArrayList<Author>();
    @ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    private List<Category> categories = new ArrayList<Category>();
    @ElementCollection(fetch = FetchType.EAGER)
    private List<BookComment> bookComments = new ArrayList<BookComment>();

    public String getISBN() {
        return ISBN;
    }

    public void setISBN(String ISBN) {
        this.ISBN = ISBN;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<Author> getAuthors() {
        return authors;
    }

    public void setAuthors(List<Author> authors) {
        this.authors = authors;
    }

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }

    public List<BookComment> getBookComments() {
        return bookComments;
    }

    public void setBookComments(List<BookComment> bookComments) {
        this.bookComments = bookComments;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Book)) return false;

        Book book = (Book) o;

        if (!ISBN.equals(book.ISBN)) return false;
        if (!authors.equals(book.authors)) return false;
        if (bookComments != null ? !bookComments.equals(book.bookComments) : book.bookComments != null) return false;
        if (categories != null ? !categories.equals(book.categories) : book.categories != null) return false;
        if (description != null ? !description.equals(book.description) : book.description != null) return false;
        if (!name.equals(book.name)) return false;
        if (!price.equals(book.price)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = ISBN.hashCode();
        result = 31 * result + name.hashCode();
        result = 31 * result + price.hashCode();
        result = 31 * result + (description != null ? description.hashCode() : 0);
        result = 31 * result + (authors != null ? authors.hashCode() : 0);
        result = 31 * result + (categories != null ? categories.hashCode() : 0);
        result = 31 * result + (bookComments != null ? bookComments.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Book{" +
                "ISBN='" + ISBN + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", description='" + description + '\'' +
                ", authors=" + authors +
                ", categories=" + categories +
                ", bookComments=" + bookComments +
                '}';
    }
}

HibernateBookDAO.java
package tn.jebouquine.dao.hibernate;
public class HibernateBookDAO implements BookDAO {

    @Override
    public void create(Book book) {
        Session session = SessionUtilities.openSessionAndBeginTransaction();

        session.save(book);

        SessionUtilities.commitAndCloseSession(session);
    }

    @Override
    public Book retrieve(String ISBN) {
        Session session = SessionUtilities.openSessionAndBeginTransaction();

        Book book = session.get(Book.class , ISBN);

        SessionUtilities.commitAndCloseSession(session);
        return book;
    }

    @Override
    public void update(Book book) {
        Session session = SessionUtilities.openSessionAndBeginTransaction();

        session.update(book);

        SessionUtilities.commitAndCloseSession(session);
    }

    @Override
    public void delete(Book book) {
        Session session = SessionUtilities.openSessionAndBeginTransaction();

        session.delete(book);

        SessionUtilities.commitAndCloseSession(session);
    }
}

BookTest.java
public class BookTest {

   private Book book;
    private static BookDAO bookDAO;
    private static Logger logger;
    @BeforeClass
    public static void beforeClass() {
        bookDAO = new HibernateBookDAO();
        logger = LoggerFactory.logger(BookTest.class);
    }
    @AfterClass
    public static void afterClass(){
        bookDAO = null;
        logger = null;
    }

    @Before
    public void setUp() {
        Author author = new Author();
        author.setName("The lonely developer");
        book = new Book();
        book.setISBN("isbn:9780137081073");
        book.setName("The Adventures of the little guy in Java persistance world: Testing At midnight for the next saturday :(");
        book.setPrice(new BigDecimal("10.00"));
        book.getAuthors().add(author);

    }

    @Test
    public void createTest() {
        bookDAO.create(book);
    }

    @Test
    public void retrieveTest() {
        book.setISBN("isbn:9780137081074");
        bookDAO.create(book);
        Book book1 = bookDAO.retrieve(book.getISBN());
        assertEquals(book, book1);
    }

All the other classes have the equals and the hashcode implemented. I am using gradle to build the project.

A: Problem solved. While mapping a List which is ordered it turns out I need to specify a column to be used for the ordering. So the final result looks something like this.
@ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@OrderColumn(name="INDEX")
@NotEmpty
private List<Author> authors = new ArrayList<Author>();

Or alternatively I could have used a Set which is not ordered.


text:
Q: D3 Force Directed Graph Design Can someone review my implementation on JSFiddle and give me some pointers making my code cleaner and robust?
I've been working on this in JsFiddle. I am attempting to get a nice clean graph implementation for workflow design. For instance, we have input and output nodes and processes in between. Although I've done linq style functional programming in C#, this javascript implementation is a bit tougher to get my head around. All of the functionality that I want is in the various example pieces of code. I have attempted to bring them together, but it could be tidier and nicer.
http://jsfiddle.net/3ckG5/9/

These definitions confuse me, they have different names and properties across the examples. Really not getting it.
var svg = d3.select('body')
    .append('svg')
    .attr('width', width)
    .attr('height', height);

The object scopes confuse me and I don't fully understand them.
Here is a list of functionality, a bold text indicates working. This example forms the basis of the implementation (http://bl.ocks.org/rkirsling/5001347), and others are linked next to the bit of functionality that they confer. However i am getting confused as they each work slightly differently and bringing them together is more of a challenge than anticipated.
Nodes
Nodes repel each other with charge value
Control node colour
Control node radius
Control node label
Delete a node
Deleting a node, also deletes that node's inputs and outputs       //Node selector???
Node dragging and repositioning. kinda.... but oh so buggy   (http://bl.ocks.org/norrs/2883411)
Only process nodes can be dragged and repositioned.
Node inputs or outputs repositioned based on associated process node position.
Labels on nodes
Only node inputs and outputs can form links
Only node inputs can connect to node outputs and vice versa.
Can only connect if same input/output type
Change colour of all nodes of the same type that can be connected to, when going to connect two nodes.
Links
Set link lengths
A drag line is is made on mouse down.
Markers on links
Markers always point from input to output.
Area
Pan/Zoom (http://bl.ocks.org/benzguo/4370043)
Any tips would be greatly appreciated.
DUPLICATED IN STACKEXCHANGE..... although they feel it is off topic on there. Anyone? Anyone at all have some positive input here?


text:
Q: Angular 2 (Reactive forms) Listing all validation rules (like pattern, minlength, maxlength) in a form control whether or not in an error object I am creating a component where I need to list all the validation rules of an input.
home.component.html
<input-validation>
   <input type="text" class="form-control" formControlName="name">
</input-validation>

home.component.ts
export class HomeComponent implements OnInit {
    public myForm: FormGroup;

    constructor(private _fb: FormBuilder) { }

    ngOnInit() {
        this.myForm = this._fb.group({
            name: ['', [ <any>Validators.minLength(5), <any>Validators.pattern('^[0-9]*$')]],
            address: this._fb.group({
                street: ['', <any>Validators.required],
                postcode: ['8000']
            })
        });

    }
}

For template driven forms I am using

_rawValidators

property of FormControlName.
But I noticed that _rawValidators does always returns empty array for Reactive forms.
As you can see in above example formControlName="name" has two validators here minlength and pattern. Now unless you starts writing in this input, the errors object of FormControl is null.
So if anyone could help me to understand how ReactiveForms works(validates) or where it stores all its validators  would be much appreciable.
Thanks

A: From documentation

A FormControl constructor accepts three, optional arguments: the
  initial data value, an array of validators, and an array of async
  validators.

So you have you validator in an array. You can beforehand assign it to a variable and get it anywhere else. Like
this.validator1 = [ Validators.minLength(5), Validators.pattern('^[0-9]*$')]
...
console.log(this.validator1);

A: Not sure if this is what you're looking for, but the validator property on AbstractControl returns a single function which is composed of all validation logic.  If you call that function and pass in the control you want to validate, it will apply all validation and return an object containing information about each validator that failed, or null if no validators failed.
For example, on an input with a minlength="3" validator, the following is the return value when you only enter 2 characters:
{"minlength":{
    "requiredLength":3,
    "actualLength":2
  }
}

Whereas it returns the following when a required validator fails:
{"required": true}


text:
Q: Salesforce PostInstallation code In my PostInstallation code I need to access the Salesforce organization id, organization name. In salesforce documentation I read that it is a special user which has all the permissions to run this code. Can I get my required information from this special user? Or is there any other way I can get the required information in the Post installation code?

A: I have an InstallHandler that on completion sends an email with this subject line:
private void sendSuccessEmail(InstallContext context) {
    User user = [Select Name, Email from User where Id = :context.installerId()];
    String subject = 'Xyz InstallHandler executed in org '
          + UserInfo.getOrganizationName() + ' '
          + UserInfo.getOrganizationId()
          + ' for user "' + user.Name
          + (context.previousVersion() != null
                  ? ' (previous version was ' + context.previousVersion() + ')'
                  : '');

So the organization id and organization name are available through the normal UserInfo object in this context.


text:
Q: Can i post data from a select drop down to email using PHP? I'm currently building an html form with an action to a php-file.
In the form i have some drop down menus in which the user needs to select one of the values. I need to retrieve that value and post it to an email. I know almost nothing of php and cannot find anywhere how this should be done. All i find online is doing this in combination with mysql or some database but i'm not working with databases here.
Is this possible?
thank you for the replies, but honestly i'm having too much problems getting it to work. I've been looking around for tutorials and demos but i just can't seem to get it to work properly. After so many hours i really need some help please
my html is
<form method="post" name="contact_form" action="contact.php">

                        Select your profile

                        <select id="user-type" class="selectlist">
                            <option value="option1">I'm a first-time user</option>
                            <option value="option2">I would like to renew or upgrade</option>
                        </select>

                        SEN

                        <input type "text" name="input1" class="input1">

                        Email Address

                        <input type "text" name="input2" class="input2">

                        Select your product

                        <select id="product" class="selectlist">
                            <option value="option1">JIRA</option>
                            <option value="option2">Confluence</option>
                            <option value="option3">JIRA Service Desk</option>
                            <option value="option15">Other</option>
                        </select>

                        Specify your product

                        <input type "text" name="input2" class="input2">

                        Select your license

                         <select id="select" class="selectlist">
                            <option value="option1">25 users</option>
                            <option value="option2">50 users</option>
                            <option value="option3">100 users</option>

                        </select>

                        <input type="submit" name="submit" value="Submit" class="submit-button-atl" />

                </form>

my php reads like this
if(!isset($_POST['submit']))
{
    echo "error; you need to submit the form!";
}
$profile = $_POST['profile'];
$SEN = $_POST['SEN'];
$email = $_POST['email'];
$product_choice = $_POST['product_choice'];
$product = $_POST['product'];
$license_choice = $_POST['license_choice'];

//Validate first
if(empty($SEN)||empty($email))
{
    echo "SEN and email are mandatory!";
    exit;
}

if(IsInjected($email))
{
    echo "Bad email value!";
    exit;
}

$email_from = 'test@gmail.com';//<== update the email address
$email_subject = "Atlassian";
$email_body = "You have received a new message from the user $email.\n".
    "Here is the message:\n $message".

$to = "test@gmail.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank-you.html');

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}

I'm sure i'm doing a million things wrong but i have too little knowledge of programming to realize what it is. I do want to learn however but i just need help to get me on the right track.
By the way, there is some javascript involved too, when a user selects one of the two options in the first select box, the input fields (div2 and div3) appear or disappear. I assume that wouldn't have to be a problem for php?

A: You can use PHP's built-in mail function to accomplish this.
http://us1.php.net/manual/en/function.mail.php
You do not need to first write the information to a database or do something else with it.  You can pass the variables directly to PHP's mail function.
<?php

// IF YOU HAVE A SELECT MENU NAMED select_menu,
// YOU CAN PULL THE VALUE OUT AND STORE IT INTO A VARIABLE
$select_menu_val = $_POST['select_menu'];

// THEN YOU CAN PASS THAT ALONG TO THE MAIL FUNCTION
$to = 'rick@rick.com';
$subject = 'This is a test';
$message = 'My select menu value is '.$select_menu_val;

mail($to, $subject, $message);

A: Your are not on proper way, you have to set names of all the elements, I have implemented your code, and will work fine
<?php
if(!isset($_POST['submit']))
{
    echo "error; you need to submit the form!";
}
$profile = $_POST['profile'];
$SEN = $_POST['SEN'];
$email = $_POST['email'];
$product = $_POST['product'];
$product_choice = $_POST['product_choice'];
$product = $_POST['product'];
$license_choice = $_POST['license_choice'];

//Validate first
if(empty($SEN)||empty($email))
{
    echo "SEN and email are mandatory!";
    exit;
}

if(IsInjected($email))
{
    echo "Bad email value!";
    exit;
}

$email_from = 'test@gmail.com';//<== update the email address
$email_subject = "Atlassian";
$email_body = "You have received a new message from the user $email.\n".
    "Here is the message:\n $message".

$to = "test@gmail.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank-you.html');

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}
?>
<form method="post" name="contact_form" action="contact.php">

                        Select your profile

                        <select id="user-type" name="profile" class="selectlist">
                            <option value="option1">I'm a first-time user</option>
                            <option value="option2">I would like to renew or upgrade</option>
                        </select>

                        SEN

                        <input type "text" name="sen">

                        Email Address

                        <input type "text" name="input2" class="input2">

                        Select your product

                        <select id="product" name="product"class="selectlist">
                            <option value="option1">JIRA</option>
                            <option value="option2">Confluence</option>
                            <option value="option3">JIRA Service Desk</option>
                            <option value="option15">Other</option>
                        </select>

                        Specify your product

                        <input type "text" name="input2" class="input2">

                        Select your license

                         <select id="select" name="license_choice" class="selectlist">
                            <option value="option1">25 users</option>
                            <option value="option2">50 users</option>
                            <option value="option3">100 users</option>

                        </select>

                        <input type="submit" name="submit" value="Submit" class="submit-button-atl" />

                </form>


text:
Q: How to add multiple 3d objects to one modelviewer how to add multiple 3d objects in a modelviewer.
I tried this https://github.com/google/model-viewer/issues/482#issuecomment-551268896
but it didn't work.
code
<model-viewer>
<model-node src="a.glb"></model-node>
<model-node src="b.glb"></model-node>

</model-viewer>

A: The feature of adding multiple model nodes into a single <model-viewer> was only conceptualized, and has not been implemented.
As stated by the Github post that you linked to:

This suggests a declarative API for incorporating multiple models into a single  element (emphasis mine)...

The conversation in this Github issue goes on to describe multiple implementation suggestions if they were to incorporate the feature.
If you're looking to create a scene with multiple models, you're going to need to use a library such as three.js until they've ironed out the details of this proposed feature.
If you use ReactJS, you can use gltfjsx, which significantly simplifies the process of importing a model with multiple mesh nodes. It builds a component for you using react-three/drei, and separates out each mesh node in the component for you.
Here's an example of a component generated with gltfjsx:
import React, { useRef } from 'react'
import { useGLTF } from '@react-three/drei'

export default function Model(props) {
  const group = useRef()
  const { nodes, materials } = useGLTF('/example-3d.glb')
  return (
    <group ref={group} {...props} dispose={null}>
      <group scale={56.66}>
        <mesh geometry={nodes.Curve001_1.geometry} material={materials.Material} />
        <mesh geometry={nodes.Curve001_2.geometry} material={materials['Material.002']} />
      </group>
    </group>
  )
}

useGLTF.preload('/example-3d.glb')

This component can now be used anywhere to include your 3d model.


text:
Q: How to solve this optimisation problem?
Dalto Pizza currently sells 1000 pizzas per week at \$18 per pizza. It is planning to reduce the unit price of each pizza. It estimates that for every \$1 discount in price, it can sell 100 more pizzas each week.

*

*(a) Form the weekly revenue function of Dalto Pizza in terms of p, the new unit price of the pizza.

*(b) What should the new unit price be in order to maximize weekly revenue? What is the maximum weekly revenue?

My solution is:
    $$
R(p)=(18-p)(1000+100p)=-200p^2+800p+18000
$$
$$
R'(p)=-400p+800
  $$
    let R'(p)=0 and p=2
    $$
R''(p)=-400
$$
   (which is <0)  So p=2 is a maximum point,
Unit Price = 18-2=$16

Sales Volume = 1000+200=$1200

R(max)= $16*$1200=$19200

The solution for weekly revenue function is = 2800-100p^2

p=14

R(max)=$19600

A: If we let $N(x)$ be the number of units sold at a price of $x$, then the revenue function $R(x)=xN(x)$.
As $N(x)$ is linear, $N(x)=ax+b$.
We have also been told that $N(x-1)=N(x)+100$, or equivalently $N(x-1)-N(x)=100$, and so $a(x-1)-ax=100$, and therefore $a=-100$.
We also know $N(18)=1000=18a+b$ and so we can deduce that $b=2800$.
This gives a function $R()x)=x(-100x+2800)=-100x^2+2800x$.
This differentiates to $-200x+2800$, and has a zero at $x=14$, which is a maximum because the coefficient of $x^2$ is negative.
Therefore the maximum revenue possible is at $x=14$, and $R(14)=14\times N(14)=14\times 1400=19600$.
The method you give uses the substitution $x=18-p$. The price is then calculated as $18-p$, and the number of unit sold is $1000+100p$, which gives a revenue function of $(18-p)(1000+100p)$.
When you multiplied this out, you have a $-200p^2$ term which should be $-100p^2$. You can check algebra online at sites like MathPapa.
Substituting $p=18-x$ into $-100p^2+800p+18000$ gives:
$-32400+3600x-100x^2+14400-800x+18000=2800x-100x^2$.


text:
Q: How to calculate the expected value of a function of the 'history' of a Markov chain? Suppose I have a system which can have two states, 0 and 1, with a transition probability matrix T such as, for example,
[[ 0.8  0.2]
 [ 0.1  0.9]]

Define S(N) as the cumulative sum of the state indices visited after N transitions, given that the initial state is 0. I would like to calculate the expected value of S(N).
For example, $S(2) = 0.8^{2}\times0 + 0.8\times0.2\times1 + 0.2\times0.1\times1+0.2\times0.9\times2 = 0.54$.
What would be a general formula/algorithm to calculate this? I could simply keep track of all the 'branches' of the tree, but their number increases exponentially with N and this doesn't seem like an efficient method.

A: I realized that this can be solved using the recursive relation
$$S(i,n) = \sum_{j} T_{ij}\left[i + S\left(j, n-1\right)\right]$$
where $S(i, n)$ is the expected value of the cumulative sum $S$ given an initial state $i$ after $n$ transitions. This can be implemented using bottom-up dynamic programming. For example, in Python,
import numpy as np

T = np.array([[0.8, 0.2],
              [0.1, 0.9]])

N = 2
S = np.zeros((2, N+1))
S[0, 0] = 0
S[1, 0] = 1
for n in range(1, N+1):
    for i in range(2):
        S[i, n] = sum(T[i, j] * (i + S[j, n-1]) for j in range(2))
print(S)

which prints
[[ 0.    0.2   0.54]
 [ 1.    1.9   2.73]]

from which we can read off that $S(0, 2) = 0.54$. This can be checked with a Monte Carlo simulation:
def simulate_S(initial_state, N):
    old_state = initial_state
    S = 0
    for n in range(N):
        new_state = np.random.choice(range(2), p=T[old_state, :])
        S += new_state
        old_state = new_state
    return S
N_simulations = 10000
S_estimate = np.mean([simulate_S(initial_state=0, N=2) for _ in range(N_simulations)])
print(S_estimate)

which (for one instance) prints 0.5426, in good agreement with the analytical result.


text:
Q: Can I Store my ehcache3.xml file in an external file In ehcache2, I stored my properties externally and read them using a input stream which was an available option for configuring this, but the same option isn't present in ehcache3.
ehcache2 code which works: https://www.ehcache.org/documentation/2.8/code-samples.html
Create a CacheManager from a configuration in an InputStream.
try {
  CacheManager manager = CacheManager.newInstance(fis);
} finally {
  fis.close();```

Is there any work around for the same in ehcache3?

A: Ehcache3 doesn't have as straightforward a way of doing this as was present in ehcache2, but it definitely is possible.
You need to use the "import org.w3c.dom.Document" class and pass a Document to the XMLConfiguration constructor which you can use to build your cache manager:
      cacheManager = CacheManagerBuilder.newCacheManager(xmlConfiguration);
The document itself is build like this:
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(true);
      Document document = factory.newDocumentBuilder().parse(inputStream);
      XMLConfiguration xmlConfiguration = new XMLConfiguration(document);

And now it should work.  You might have xml related errors, but otherwise, this should work perfectly normal if your xml is of the correct format.


text:
Q: NHibernate and a denormalised table Working on a website that has Employee and Branch entities, using a database table "Employees" which also contains the branch id and branch name. I can't change the client's database so I need to map Employees and Branches from the same table.
I guess I need some type of distinct clause in the mapping XML to get a distinct list or set of branches from the employee table?
Is there a way I can map both classes on the same table? (Can it be done with Fluent NHibernate?)

A: Stefan is correct, use components. In FluentNHibernate, it will look like:
class Branch
{
    string Name { get; set; }
    DateTime DateOpened { get; set; }
}

class Employee
{
    int Id { get; set; }
    string Name { get; set; }
    Branch Branch { get; set; }
}

class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        Component<Branch>(x => x.Branch, c => {
            c.Map(x => x.Name);
            c.Map(x => x.DateOpened);
        });
    }
}

The Component<Branch> can be shortened to just Component since the compiler will figure out the type automatically. Also, what I like to do is provide an AsComponent function on a class for my component so I don't have to repeat myself everywhere I map the component:
public static class BranchMap
{
    public Action<ComponentPart<Branch>> AsComponent()
    {
        return c =>
        {
            c.Map(x => x.Name);
            c.Map(x => x.DateOpened);
        };
    }
}

This also makes it easy to add in prefix/suffix functions for the cases where an entity may have more than one instance of a component with a different naming scheme.

A: Use components. I don't know FluentNhibernate, but in xml, it looks like this:
<class name="Employee">
  ...

  <component name="MyBranch">
    <!-- Branche properties are here: -->
    <property name="BrancheName"/>
    <property name="..."/>
  </component>
</class>

class Employee
{
  Branch MyBranch { get; private set; }
}

class Branch
{
  string BrancheName { get; private set; }
}

It's actually pretty straight-forward. You also do this for performance reasons, because you don't need to join tables when there is always a branch on an employee.
Note: If all columns are null, myBranch will be null.


text:
Q: How to find values with minimal absolute values in several columns ignoring NaNs? I have the following two pandas time series (but the question is also applicable to numpy array):
NaN               NaN
NaN               2
NaN               1
NaN               0
NaN              -1
NaN              -2
6                -3
5                -4
4                -5
3                NaN
2                NaN

I would like to combine these two columns in the following way. If both columns contain NaN, the resulting column gets NaN, otherwise we get the value with the minimal absolute value.
For example in the considered case we should get:
 NaN
 2
 1
 0
-1
-2
-3
-4
 4
 3
 2

A: Let, df the dataframe with two columns, apply conditional absolute minimum over rows using axis=1
Here, x[np.argmin(x.abs())] checks the row index with absolute minimum and return the the original value with sign.
Also, we would need pd.isnull(x.min()) check for 'All-NaN slice encountered i.e when both the columns have NaN values.
In [3]: df.apply(lambda x: x.min() if pd.isnull(x.min()) else
                           x[np.argmin(x.abs())], axis=1)
Out[3]:
0    NaN
1      2
2      1
3      0
4     -1
5     -2
6     -3
7     -4
8      4
9      3
10     2
dtype: float64

A: OK, after reading and understanding your question and not being able to find a vectorised approach, we can define a custom function and call apply and pass each row.
So this will check if either column is null if so return the min value, it then compares the abs value of either column and then returns the column that has smallest abs value but the original value including sign:
In [269]:

def func(x):
    if pd.isnull(x.a) or pd.isnull(x.b):
        return x.min()
    elif np.abs(x.a) < np.abs(x.b):
        return x.a
    else:
        return x.b

df.apply(lambda row: func(row), axis = 1)
Out[269]:
0    NaN
1      2
2      1
3      0
4     -1
5     -2
6     -3
7     -4
8      4
9      3
10     2
dtype: float64


text:
Q: Pandas: while loop before a for loop until a certain condition is respected I have a dataframe, filled_orders, like that:
   price  amount  side  fees                   timestamp
0      0       2  bids     0  2019-06-25 12:24:46.570000
1      3       2  asks     0  2019-06-25 12:22:46.570000
2      2       4  bids     0  2019-06-25 12:22:46.570000
3      5       1  asks     0  2019-06-25 12:24:46.570000
4      1       4  asks     0  2019-06-26 12:24:46.570000

Then a loop like that:
for index, row in filled_orders.iterrows():
 if row.side == 'asks':
    filled_orders = filled_orders.drop(index)
elif row.side == 'bids':
    filled_orders = filled_orders.drop(index)

What I need to do is to do this loop until there is either one asks or one bids remaining. What I tried right above the loop is the following:
while (filled_orders.side == 'bids').empty == True or (filled_orders.side == 'asks').empty == True:

at the end what I need in the dataframe example above is the following:
   price  amount  side  fees                   timestamp
4      1       4  asks     0  2019-06-26 12:24:46.570000

Basically, no matter what input I put in that code, at the end what I need is just rows with only bids or asks
But it does not work... any idea? Thanks!
the full code looks like this:
while (filled_orders.side == 'bids').any() == False or (filled_orders.side == 'asks').any() == False:
     for index, row in filled_orders.iterrows():

            if row.side == 'asks':
                if filled_orders.index.contains(filled_orders.first_valid_index()):
                    if filled_orders.loc[index, 'amount'] == filled_orders.loc[filled_orders.first_valid_index(), 'amount'] and filled_orders.loc[filled_orders.first_valid_index(), 'side'] == 'bids':
                        filled_orders = filled_orders.drop(filled_orders.first_valid_index())
                        filled_orders = filled_orders.drop(index)

                    elif filled_orders.loc[index, 'amount'] < filled_orders.loc[filled_orders.first_valid_index(), 'amount'] and filled_orders.loc[filled_orders.first_valid_index(), 'side'] == 'bids':
                        filled_orders.at[filled_orders.first_valid_index(), 'amount'] = float(filled_orders.at[filled_orders.first_valid_index(), 'amount'])  - float(filled_orders.at[index, 'amount'])
                        filled_orders = filled_orders.drop(index)

                    elif filled_orders.loc[index, 'amount'] > filled_orders.loc[filled_orders.first_valid_index(), 'amount'] and filled_orders.loc[filled_orders.first_valid_index(), 'side'] == 'bids':
                        filled_orders.at[index, 'amount'] = float(filled_orders.at[index, 'amount']) - float(filled_orders.at[filled_orders.first_valid_index(), 'amount'])
                        filled_orders = filled_orders.drop(filled_orders.first_valid_index())

            if row.side == 'bids':
                if filled_orders.index.contains(filled_orders.first_valid_index()):
                    if filled_orders.loc[index, 'amount'] == filled_orders.loc[filled_orders.first_valid_index(), 'amount'] and filled_orders.loc[filled_orders.first_valid_index(), 'side'] == 'asks':
                        filled_orders = filled_orders.drop(filled_orders.first_valid_index())
                        filled_orders = filled_orders.drop(index)

                    elif filled_orders.loc[index, 'amount'] < filled_orders.loc[filled_orders.first_valid_index(), 'amount'] and filled_orders.loc[filled_orders.first_valid_index(), 'side'] == 'asks':
                        filled_orders.at[filled_orders.first_valid_index(), 'amount'] = filled_orders.at[filled_orders.first_valid_index(), 'amount']  - filled_orders.at[index, 'amount']
                        filled_orders = filled_orders.drop(index)

                    elif filled_orders.loc[index, 'amount'] > filled_orders.loc[filled_orders.first_valid_index(), 'amount'] and filled_orders.loc[filled_orders.first_valid_index(), 'side'] == 'asks':
                        filled_orders.at[index, 'amount'] = float(filled_orders.at[index, 'amount']) - float(filled_orders.at[filled_orders.first_valid_index(), 'amount'])
                        filled_orders = filled_orders.drop(filled_orders.first_valid_index())

The error that I receive is the following:
AttributeError: 'NoneType' object has no attribute 'side'

A: Based on your sample data and desired output, couldn't you just:
df.loc[df['side'].isin(['bids', 'asks'])].tail(1)

    price   amount  side    fees    timestamp
4   1   4   asks    0   2019-06-26 12:24:46.570000


text:
Q: Can't curl key values locally for backup in consul I am using single instance for consul. Everything is working fine, the web-ui, ACL etc. But when I try to access the all the key values locally using curl command the response is 404 not found even if the key value is already there and can be seen in web-ui.
Config.json file
{
    "bootstrap": true,
    "server": true,
    "log_level": "DEBUG",
    "enable_syslog": true,
    "datacenter": "dc1",
    "addresses" : {
      "http": "P.P.P.P"
    },
    "bind_addr": "P.P.P.P",
    "node_name": "P.P.P.P",
    "data_dir": "/home/ubuntu/consuldata",
    "ui_dir": "~/dist",
    "acl_datacenter": "dc1",
    "acl_master_token": "xxxxxxxxxxxxxxxxxxxxx",
    "acl_default_policy": "deny",
    "encrypt": "pXoaLOJ816mO+da8y8zrsg=="
}

where P.P.P.P is the private IP and xxxxxxxxxxxxxxxxxxx is the master token.
I have started consul by the following command
consul agent -config-dir ~/server -ui-dir ~/dist -bootstrap true -client=P.P.P.P
After running this the web-ui is working fine and I am able to create ACL and key-value
Now am trying to get all the key value pairs by the following command
curl -v http://P.P.P.P:8500/v1/kv/?recurse
Following is the output
* Hostname was NOT found in DNS cache
*   Trying P.P.P.P...
* Connected to P.P.P.P (P.P.P.P) port 8500 (#0)
> GET /v1/kv/?recurse HTTP/1.1
> User-Agent: curl/7.35.0
> Host: P.P.P.P:8500
> Accept: */*
>
< HTTP/1.1 404 Not Found
< X-Consul-Index: 488
< X-Consul-Knownleader: true
< X-Consul-Lastcontact: 0
< Date: Tue, 10 May 2016 13:08:44 GMT
< Content-Length: 0
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host P.P.P.P left intact

where P.P.P.P is the private IP of the consul instance.
Following is the output of netstat -tlpn
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:22                  0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:8600          0.0.0.0:*               LISTEN      1339/consul
tcp        0      0 P.P.P.P:8300              0.0.0.0:*               LISTEN      1339/consul
tcp        0      0 P.P.P.P:8301              0.0.0.0:*               LISTEN      1339/consul
tcp        0      0 P.P.P.P:8302              0.0.0.0:*               LISTEN      1339/consul
tcp        0      0 127.0.0.1:8400          0.0.0.0:*               LISTEN      1339/consul
tcp        0      0 0.0.0.0:80                  0.0.0.0:*               LISTEN      -
tcp        0      0 P.P.P.P:8500              0.0.0.0:*               LISTEN      1339/consul
tcp6       0      0 :::22                   :::*                    LISTEN      -

I have tried the curl command on each of these addresses on which consul is listening but getting the same error.

A: Finally, I got the problem. The config.json file should be changed to for http from public IP to 0.0.0.0 (Anywhere). Here I made a blog post on how to setup consul server on a single instance. This is the Youtube video for the same.


text:
Q: Retrieving a post's likes In my application, I have a 'user_post' feed which is responsible for storing the posts of a user. I would like a way to retrieve the likes of each individual post.
If I added a feed called 'post_like' I could store the likes of each post in their own feed. Is this approach efficient?

A: I'd suggest using a notification feed for that, not a flat feed. Set the verb to 'like' or whatever is appropriate for your app, and the actor is the user who 'liked' the original activity. When you call the user's notification feed, you'll get a list of all users who liked it.
If you store the likes in your own database and send the like to us with a foreign ID then you can always remove the activity later if they 'un-like' something afterward.


text:
Q: What exactly does a HTTP or jquery $.ajax timeout mean? When I issue an $.ajax query with a timeout: parameter, and my timeout is met such that error: is invoked, what does that mean?
More specifically:
 does that mean the server received the request, but is still processing it? That may mean some effect may occur, so I may have to cancel it on the server, or somehow invalidate data that was already partially written to a database.
Or does that mean I was never able to reach the server at all? This is nice to know since then I don't have to deal with partial data on a server "save"
Or does that mean the request made it part of the way, and now we lost track of it? In this case, I'd have to actually ask the server, "Oh hey, about that request I sent awhile ago... did you get that one? yeah? okay ignore that last save"
OS Commands like tracert make it clear there  may be many servers for a TCP command to go through, so if one becomes unresponsive, it's hard to tell if it got it or not. But some protocols require an echo-back to be considered receivable (so I'm not sure if HTTP or Apache is involved in this)

A: It is how long the client will wait to hear from the server before giving up.
The server may or may not have done its part.  The only way for the client to know about that is for the client to be notified.  Since you don't want to to leave a process or a human waiting forever, by using a timeout you specify the time to wait for success before giving up.


text:
Q: Select Cells in Column Up to End of Data in Adjacent Column on OSX I know there is a command to do this but I just can't find it.  The answer here should have used this command but did not.
Q: Given an empty column (B) adjacent to a column populated with data (A). There is a way to:

*

*Enter a formula in B#

*Use shortcut_1 to select from B# to the last cell in B to have adjacent data in A.

*ctrl+enter to propagate the selected formula to the selected cells.

Does anyone know the keystroke for shortcut_1 on OSX?
On windows I think the shortcut is ctrl + shift + ↓ (noted here).  However, ctrl+↓ brings up the application mode in OSX.

A: It's the same as Windows, but use the Command key instead of Ctrl: ⌘+Shift+arrow key
More shortcuts here: Excel keyboard shortcuts for Mac OS


text:
Q: connection to sql from config variables cause error (php code) I am using variables from config file to establish sql connection on my php files. Connection works fine in those files but to make the website more organized I decided to have one file for connection. I got the code from the internet, the connection does not worked.
giving me this error:
' Error: Connect failed: Access denied for user 'something'@'server.com' (using password: NO)'
The user info at the config file is different and the password is set.
This is the details:
My website like this structure:
root ----> 1)config.ini 2)public_html folder
public_html ----> website pages including 1)db_functions.php and 2)admin folder
admin ---->login.php and loginCode.php.

in the config.ini
[database]
username = someone
password = something
dbname = something

in db_functions.php file
<?php
/**
 * Database functions for a MySQL with PHP tutorial
 *
 * @copyright Eran Galperin
 * @license MIT License
 * @see http://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17
 */

/**
 * Connect to the database
 *
 * @return bool false on failure / mysqli MySQLi object instance on success
 */
function db_connect() {

    // Define connection as a static variable, to avoid connecting more than once
    static $connection;

    // Try and connect to the database, if a connection has not been established yet
    if(!isset($connection)) {
        // Load configuration as an array. Use the actual location of your configuration file
        $config = parse_ini_file('../config.ini');
        $connection = mysqli_connect('server',$config['username'],$config['password'],$config['dbname']);
    }

    // If connection was not successful, handle the error
    if($connection === false) {
        // Handle error - notify administrator, log to a file, show an error screen, etc.
        return mysqli_connect_error();
    }
    return $connection;
}
?>

in loginCode.php
<?php

require_once('../db_functions.php');
$connection = db_connect();
      //if connection fails, stop script execution
      if (mysqli_connect_errno()) {
            $Message = "Error: " . $sql  .  "Connect failed: ". mysqli_connect_error();
        echo $Message;
      }
      else
          echo 'no error';
?>

Those cods have error:
Error: Connect failed: Access denied for user 'something'@'server.com' (using password: NO)
However when I copied the same function from db_functions.php file to loginCode.php file and change this line $config = parse_ini_file('../config.ini'); to $config = parse_ini_file('../../config.ini'); , it works perfectly and the connection  success.
Also it works without error when I replaced the connection variables in db_functions.php by the actual database user information, calling the function from loginCode.php.
I think there is a problem on db_functions.php who can not assess information in config file but why the other files can access it?
update: I moved loginCode.php file to public_html folder connection works. and I moved  db_functions.php file to admin folder it worked also.

A: worked when I put both files loginCode.php and db_functions.php in the same folder.


text:
Q: Is it possible for the compiler to have a maximum on output? [original text][1]
[results when i print out within Server Class][2]
In my Server Class I want to read each line of the text file, including empty lines but it starts in the middle of the file.  I believe it has to do with the ecplise max output.  I know because I get the correct output of bytes from each line.

A: Use a loop and iterate over the entire file:
while ((line = buffer.readLine()) != null)) {
    pr.println(line);
}

A: You need some kind of loop to iterate through the BufferedReader. If readLine() returns null, you're at the end of the stream and you can break out of the loop.
See API for BufferedReader.


text:
Q: X-Forwarding on server It is possible to use X11-forwarding running on a common remote server without GPU ?

A: Yes.
X11-Forwarding does not require any kind of graphics ability on the host, and is commonly used in this configuration (among many others no doubt) when remotely maintaining VM's.  [ If you are using Linux, the only thing you need installed on the remote host by way of an "X" environment is xauth, and possibly some fonts - you don't even need X installed].


text:
Q: How can there be alternatives for the foundations of mathematics? How can set theory and category theory both be plausible theories for the foundations of mathematics? If these two theories are not mathematically equivalent, does it not mean that the rest of mathematics, when taken exclusively with either of these two theories as foundation, will be distinct; that is, unless these two theories are, in some way, equivalent.
Thanks

A: There are two ways to answer your question:

*

*what does foundation mean? The two areas address 'foundation' from different perspectives. Set theory (and logic) are attempts at foundations of mathematical knowledge about how we can know mathematical truths - how do you know that a theorem is 'true' (and what does true mean) ? (set theory does this by allowing a translation from your favorite branch of mathematics to sets, and then formalizing the inference operations on just the set  objects; everything can be converted to a set)

Category theory is a foundations for -what- we know about mathematics - what similarities/commonalities are among disparate areas of mathematics. Take your favorite brach of mathematics, define some objects and some suitable functions and then you get all sorts of theorems for free (everything can be viewed through the 'category' lens. everything is a category)
Of course you can use one of these for the other (give a -logical- foundation of category theory, e.g. the objects and morphisms are implemented with sets; give a -categorical- foundation for set theory/logic, e.g. one can have a category of 'set' with 'functions' as the morphisms).

*

*as to your title, how can there be more than one foundation at all, even of the same kind?There can certainly be more than one truth foundation (intuitionistic, constructivist, allowing different set axioms, different rules of inference, ZFC, NBG, etc.) each allowing desired features and disallowing unwanted features. And there have been many unification foundations (set theory can be viewed as one (just sets as the things that can be manipulated), group theory, algebra as a whole (symbolic manipulation), just category theory is the latest and best unification.

A: I'm learning about some of this right now! As far as I know, you already need quite a lot of set theory to say topos. An (elementary) topos is is a category closed under a lot of common constructions.
These topos gadgets also have an internal logic (usually intuisionistic), and given for instance a natural number object you can perform many of the well-known constructions of mathematics, such as those of the real numbers (here the Cauchy and Dedekind reals may be different). This is what we do in the topos of sets!
An elementary topos $E$, by the way, is a cartesian closed category (which means it has a terminal object $1$, products, exponentiation, and an adjunction between the two, i.e. $\hom_E(X\times Y,Z)\cong\hom_E(X,Z^Y)$) with a subobject classifier $\Omega$ together with a morphism $\top:1\to\Omega$ called true, such that any monic $f:Y\to X$ is the pullback of a unique morphism $\chi(f):Y\to\Omega$. We also require pullbacks along $\top$ to exist. It follows that $E$ has finite limits and colimits, and that the subobject functor $Sub:E\to Set$ is represented by $\Omega$ (i.e. $Sub(-)\cong\hom(-,\Omega)$).


text:
Q: Parameter objects placeholder? If a method has too many parameters, the suggestion is to convert them into a parameter object. Where to place such parameter objects? in domain/entity classes package? or if I have a separate package for DTO's, should I place there?

A: In layman's terms:
I'd suggest you put it in the same package as the class whose method, having initially such a long signature, originated the need for such a paramter object.
Parameter classes are classes nonetheless are they belong to the package where the rest of related classes are located. It doesn't matter whether or not they have behavior whichm by the way, they could end up having down the road.

A: First thing I try to do is to somehow conceptualize the parameters into one or more cohesive classes. Let's say we have method like this:
public void sendEmail(String firstName, String lastName, String email, String subject, Map<String, String> headers, String body)

I can see two cohesive groups of parameters. It makes sense to create kind of "concepts" from these - User and EmailMessage. These concepts (classes) seem quite reusable (they might even already exist!) so I put these into dto package.
Of course, this example is trivial, reality is more complex, but it is often possible to create meaningful and cohesive concepts after some thinking.
If you can't find reasonable concepts in the parameters, it might be sign of code smell. Method is trying to do too much etc.
But let's say the design is good but you still have a lot of parameters. These cases happen. You create parameter class, it's used only in one of your methods signatures. In that case I often put this class as inner static class near its usage in the method's signature (in class or interface) - e.g. directly above it.
Alternatively you can also put this into a dto package. In my opinion, these cases should be rather rare and it's kind of OK either way. You won't find single definite solution unfortunately.


text:
Q: Java: Store reference to static class is variable I need to store a reference to a class in a variable, such that I can call the static methods of that class on the variable.
Main.java
public class Main {

    private static SomeClass cls;

    private static void main(String[] args) {
        **cls = SomeClass;**
        cls.doSomething();
    }

SomeClass.java
public class SomeClass() {
    public static doSomething() {
    }
}

cls = SomeClass is not working here, but I also don't want to instantiate SomeClass.
Can anyone help?

A: This makes no sense.
You can write
private static SomeClass cls = null;

(or leave it unassigned, since the default value would be null anyway)
and
cls.doSomething()

will not throw NullPointerException and will call the static method.
However, there's no reason to do it. Regardless of what you assign to the cls variable, it will always call SomeClass.doSomething(), so it would make more sense to eliminate that variable and simply call SomeClass.doSomething().

The idea is that cls can reference several classes based on some condition which is not provided in the code above

This idea won't work. The compile time type of the cls variable will determine the class of the static method being called. Since it can only have a single type, it will always be the same static method.

A: You can use reflection for this requirement. Below is example:
public class Reference {

    public static Class clazz = null;

    public static void main(String[] args) {
        try {
            refer(Something.class);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void refer(Class clazzToBeCalled) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        clazz = clazzToBeCalled; //No need to store it on class level
        Method methodToBeCalled = clazz.getMethod("doSomething");
        methodToBeCalled.invoke(null);
    }
}


text:
Q: Is there suitable statistics test to compare number of observations from 2 groups (1x2, Fishers?)? I did a research on group of cases and controls. During my research I observed 7  variants in group of cases while I did not observe any in controls.
I would like to test is there a significant difference between 7:0 finding.
I thought of doing Fishers exact test, but not sure how it can be performed on 1x2 table and is it a suitable test for such analysis. Also, I thought of correction, to exclude 0 from statistics, so maybe to compare 7.5 and 0.5.
Is there a better test to perform for such a cases?
All suggestions are welcomed. Thank you.

A: You have a 2x2 table, but you are ignoring one of the rows. You need to add how many non-variants you had in each group. The answer to your question depends on that. Say you had 7 variants out of 30 cases and 0 variants out of 20 controls. Your contingency table would look like this:

Cases
Controls

Variants
7
0

Non-variants
23
20

Without this information, testing makes no sense. Now, you can use an exact test, such as Fisher's (conditional) or Barnard's (unconditional). I have described an unconditional test that seems to be more powerful than those (link). In this case,
> library(mtest)
> m.test(list(c(7, 23), c(0, 20)))
[1] 0.01702871


text:
Q: How to do Join in Linq query on column A or column B I want to perform a join on a any of the two columns that has the given value
How to convert for example the following SQL query to it's equivalent in Linq (method syntax):
select f.Id fId, b.Id bId from Foo f
inner join Bar b on f.FooVal = b.BarValCol1 or f.FooVal = b.BarValCol2

I started doing the following :
Context.Foos
.Join(Context.Bars, f => f.FooVal, b => b.BarValCol1 [OR?] b.BarValCol2, (f, b) => new { f, b })
.Select(bf => new { fId = bf.f.Id, bId = bf.b.Id })

(in this example the two columns contain integer values)

A: INNER JOIN is a more readable syntax, but it can be translated, in pure SQL, into cartesian product of the tables filtered with a WHERE clause.
So we can simply use a WHERE clause and build the linq from that:
from x in Foo
from y in Bar
    .Where(y => y.field1 == x.field1 || y.field2 == x.field2)

Ps: INNER JOIN and WHERE are not evaluated at the same time in SQL so they are not equivalent. ON condition filter the INNER JOIN then the WHERE is apply. But even they will have the same result but not the same execution plan depending on the Database of course.

A: You could use your LINQ twice:
Context.Foos
  .Join(Context.Bars, f => f.FooVal, b => b.BarValCol1, (f, b) => new { f, b })
  .Select(bf => new { fId = bf.f.Id, bId = bf.b.Id }).ToList().AddRange(
  Context.Foos
    .Join(Context.Bars, f => f.FooVal, b => b.BarValCol2, (f, b) => new { f, b })
    .Select(bf => new { fId = bf.f.Id, bId = bf.b.Id })
  ).Distinct();


text:
Q: Implementing route based models in Vue3 (Inertia.js) I am following the following this guide, that shows how to enable "Route Based Modals" in Inertia.js.
The post is written for Vue2, and I am using Vue3 - and I am having some issues getting it to work.
This is my "Composable" for my "useModal" method:
//Composables/useModal.js
const useModal = {
    computed: {
        modalComponent() {
            return this.$page.props.modal
                ? () => import(`@/Pages/${this.$page.props.modal}`)
                : false
        }
    }
}

export { useModal }

I then declare it in my app.js file as per below:
//app.js
//...

import {useModal} from "@/Composables/useModal";

createInertiaApp({
    title: (title) => `${title}`,
    resolve: (name) => require(`./Pages/${name}.vue`),
    setup({ el, app, props, plugin }) {
        return createApp({ render: () => h(app, props) })
            .use(plugin)
            .component("Link", Link)
            .mixin(useModal)
            .mixin({ methods: { route } })
            .mount(el);
    },
});

In my main layout, called AppLayout I have declared the Component:
<body>

<!-- Main elements are here, removed for clarity -->
<Component
        v-bind="$page.props"
        v-if="$root.modalComponent"
        :is="$root.modalComponent"
    />

</body>

Further, I have declared the modal() method in my AppServiceProvider:
public function boot()
{
    ResponseFactory::macro('modal', function ($modal) {
        inertia()->share(['modal' => $modal]);
    });
}

Now, I am trying to render a Vue component in a modal like so:
//FileController.php

public function show(File $file){
   \inertia()->modal('File/Show');

   return $this->index($file);
}

When linking to the modal component, the following Warning is issued:

[Vue warn]: Invalid VNode type: undefined (undefined)
at <Anonymous key=0 ...

A: I ended up fixing this by using defineAsyncComponent instead:
//Composables/useModal.js
import {defineAsyncComponent} from "vue";

const useModal = {
    computed: {
        modalComponent() {
            return this.$page.props.modal
             ? defineAsyncComponent(() => import(`@/Pages/${this.$page.props.modal}`))
                : false
        }
    }
}

export { useModal }


text:
Q: How to use php as a template engine without requiring third party libs I am tasked with updating a website for some people and the webhost is pretty terrible and I'm not that familiar with Php, but what I am looking for is Php template engine that I can use standalone instead of having to roll my own. Does anyone have any suggestions? I have found a lot that require composer, but the webhost doesn't have composer.

A: PHP can itself be used as a template engine in a pinch. Write templates in individual files like:
Hello, <?= htmlspecialchars($name) ?>!

They can be rendered with a simple function like:
function render_template($_path, $_vars=array()) {
    extract($_vars, EXTR_SKIP);
    ob_start();
    require($_path);
    return ob_get_clean();
}

In practice:
print render_template("templates/hello.php", array("name" => "world"));

-> Hello, world!

The ob_start() and ob_get_clean() in render_template() may be omitted if you always want to render templates directly. (That is, if you will always want the output of a template to be printed, rather than returned as a string.)
Note that the use of underscores in the variable names $_path and $_vars is significant: it reduces the risk that they will conflict with variables used by the template itself.

A: I'm a big fan of Twig. It's simple, powerful, and very well written. Composer is not required, but it is the easiest way to install Twig.
You also don't need Composer to be installed in order to use it. Just download composer.phar and upload it to your webhost, then use it like this php composer.phar install.


text:
Q: WCF UriTemplate for RESTful resource As mentioned in 2009, WCF could not differentiate the following urls to return a list of Users and a specific User:
/users
/users/{id}

Is this still the case with WCF4?

A: David's answer is great, but I'd use:
[OperationContract(Name="Op1")]
[WebGet(UriTemplate = "DoWork/")]
int[] DoWork();

[OperationContract(Name = "Op2")]
[WebGet(UriTemplate = "DoWork/{id}")]
int[] DoWork(string id);

A: You can do this now:
[OperationContract(Name="Op1")]
[WebInvoke(Method= "GET", UriTemplate = "DoWork/")]
int[] DoWork();

[OperationContract(Name = "Op2")]
[WebInvoke(Method = "GET", UriTemplate = "DoWork/{id}")]
int[] DoWork(string id);

The important thing is that the OperationContract must have the Name= property with different names for each operation.


text:
Q: Jquery removeClass - addClass within a section I have a div (#my-div) and an element in it (#element). The element is invisible at origin. I would like that when my-div is on the screen, the element becomes visible and when we leave up or down, the element becomes invisible again.
I use a script and it works when I scroll first down up to my-div but when I scroll downer or I scroll upper, the element remains visible, no further animation happens.
I use CSS for the transition.
The HTML:

It is just a DIV

My DIV

The element

The CSS:
section {
    width:100%;
    min-height: 4000px;
    text-align: center;
    background-color: #e0e0e0;
}
#whatever {
    width: 80%;
    height: 500px;
    margin: 10%;
    background-color: #d0d0d0;
}
#my-div {width: 80%;
    height: 300px;
    margin: 10%;
    background-color: grey;
}
#element {
    width: 80%;
    height: 100px;
    background-color: red;
    -webkit-transition: all 1500ms cubic-bezier(0.680, 0, 0.265, 1); /* older webkit */
    -webkit-transition: all 1500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
     -moz-transition: all 1500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
     -ms-transition: all 1500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
     -o-transition: all 1500ms cubic-bezier(0.680, -0.550, 0.265, 1.550);
     transition: all 1500ms cubic-bezier(0.680, -0.550, 0.265, 1.550); /* easeInOutBack */
}
.invisible {
    opacity: 0;
}
.visible {
    opacity: 1;
}

The jQuery script:
$(window).scroll(function(){
    if ($(window).scrollTop() <= $('#my-div').offset().top) {
        $('#element').removeClass('invisible').addclass('visible');
    }
    if ($(window).scrollTop() > $('#my-div').offset().bottom) {
        $('#element').removeClass('invisible').addclass('visible');
    }
    else {
        $('#element').removeClass('visible').addclass('invisible');
    }
});

The fiddle to see it live: http://jsfiddle.net/igorlaszlo/u0tzu02b/

A: First off, here's a fiddle with the thing working.
I've remade the check that you were doing. I've used a function to determine if the div is on screen or not (I took it from here). Hope you don't mind.
$(window).scroll(function () {
    if (isScrolledIntoView('#element')) {
        $('#element').removeClass('invisible').addClass('visible');
    } else {
        $('#element').removeClass('visible').addClass('invisible');
    }
});

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}


text:
Q: How can I get the Creative Sound Blaster X-Fi Surround 5.1 Pro volume control to work? I've been using the X-Fi for some time on Windows and it works great. However, on my MacBook Pro I can't get the volume control to work.
I see the device in "System Preferences -> Sound" and in "Audio MIDI Setup" and I can switch output to it and it works great, except for volume control. Is it possible to get it to work too?

A: The workaround I found so far is to use Soundflower as an intermediate filter between PC output and the X-Fi. This allows to control volume from Mac OSX at the price of some sound processing. I cannot comment yet on sound quality but on first auditions it seems to sound better than setting the volume to 1/100 in Songbird (my FLAC player).


text:
Q: Linq to SQL - Best way to work with a collection of objects inside another object I have a table of Items for auction and a table of bids made for those items.  There's much more to the database but we'll keep it simple.
public class Items
{
    public int ItemID { get; set; }
    public string ItemName { get; set; }
    public List<Bid> Bids { get; set; }
}

public class Bids
{
    public int BidID { get; set; }
    public int ItemID  { get; set; }
    public decimal Amount { get; set; }
    public datetime BidTime { get; set; }
    public int CustomerID { get; set; }
}

I want to return a dataset that includes the ItemID, the ItemName and all of the associated bid records ordered by BidTime, descending.  Finally, I'd like to only see Items that a certain Customer has bid on and I'd like to only see their bids for that item.  There is a foreign key relationship between Bids.ItemID and Items.ItemID.  I'm using Linq to SQL.
This works and appears to return the correct dataset:
from i in Items
from b in i.Bids
where i.AuctionID == 2 && b.CustomerID == (Int32?)1165
orderby b.BidTime descending
select new
{
    i.ItemID,
    i.ItemName,
    i.Bids
}

I'm a SQL guy trying to wrap my head around the OO nature of Linq.  Is this the best way (or even a good way) to get the results I want?  Is there a better way?
Thanks,
BK

A: How about this one (slightly more simple syntax):
 Updated where clause due to comment
from i in db.items
where i.AuctionID == 2 && i.Bids.Any(c=>c.CustomerID == (Int32?)1165)
select new
{ i.ItemId,
  i.ItemName,
  i.Bids.Where(b=>b.CustomerID == (Int32?)1165 ).OrderbyDescending(b=>b.BidTime)
 }

Make sure you profile the sql and verify that you get only ONE sql statement. If not, you need to have to add LoadOptions to your datacontext (that will make sure all the bids are eager loaded with your items).
This one will also order the bids per item (not sure if yours will do the same.... but  I guess you checked that).


text:
Q: How to prevent restrict PARTS of a web site to just INTRANET I am working on an asp.net mvc 5 project.  My clients want a program that will over their company INTRANET.... but certain parts of the project need to have INTERNET access to deal with external business partners...
Is it possible to make a single project / website where only parts are available over the INTERNET...
Of course the project has role based security trimming so you can only see the program features that you have access to .... but I suspect this will not be secure enough for this client... I suspect what they want is a way to totally restrict certain parts of the project from being accessed over the INTERNET even if the program user has the role that would allow them normally let them access these features...
The only thing that comes to mind is to extend the mvc framework with a custom security filter that checks the IP address to enforce what is available over the INTERNET .... Is this the best way to go?  Are there other options?
Does anyone know of any websites that would help with designing this solution (tutorial, examples, papers, etc..).


text:
Q: find the number of pairs of elements such that their sum add up to 8, Array is a=[3, 5, 6, 3, 2, 1, 3] My code is not running, please debug it. I am getting error as Index out of range in line (a[i+1]==a[i]) but i never reaches n-1
Please correct this code and remove the error. Answer is 4
a=[3, 5, 6, 3, 2, 1, 3]

a=sorted(a)
m=0
if(a[0]>=8):
    print(0)
else:
    for i in range(7):
        if(a[i]>8):
            break

    a=a[0:i+1]
    n=len(a)
    i=0
    j=n-1
    x=0
    y=0
    while(i!=j or i<j):
        if((a[i]+a[j])>8):
            j=j-1
        elif(a[i]+a[j]==8):
            if(a[j-1]==a[j]):
                j=j-1
                x=x+1
            else:

                if(a[i+1]==a[i]):
                    i=i+1
                    y=y+1
                else:
                    x=x+1
                    y=y+1
                    m=m+x*y
                    x=0
                    y=0
                    i=i+1
                    j=j-1
        else:
            i=i+1
    print(m)

A: >>> sum(a.count(8 - a.pop()) for _ in a[:])
4

A: from itertools import combinations
a=[3, 5, 6, 3, 2, 1, 3]

# To eliminate duplicates
set(x for x in combinations(a,2) if sum(x) == 8)

# To keep duplicates
list(x for x in combinations(a,2) if sum(x) == 8)

Output:
{(3, 5), (5, 3), (6, 2)}
[(3, 5), (5, 3), (5, 3), (6, 2)]


text:
Q: Converting Summation into matrix form Would require some help on this
$\sum{r_i^2 * e_i^2}$
would it be equivalent to
$(re)^T(re)$. It does seem to be equivalent but i cannot seem to prove it.
Assuming r and e are both vectors.
Thanks!

A: Just write it out componentwise for two dimensional vectors.
If $re$ is the dot product as you say in the comments it is not.  $\sum r_i^2*e_i^2=r_1^2e_1^2+r_2^2e_2^2$ while $re$ is a scalar $(re)=r_1e_1+r_2e_2$ and $(re)^T(re)$ is the square of this which includes a term $2r_1e_1r_2e_2$
If $(re)$ is a vector that is the componentwise product of $r$ and $e$ it is true.  Write it out for yourself.


text:
Q: How to make the php extension(.so) file portable with dependent libraries? I need to make an php extension(.so) file which can be made portable. The created library works fine on one of my machines, but, when I send it to other machine, it does not load properly as a dependency of cJSON is missing on the target machine. I do not have accessibility to install the cJSON library on the machine, though I can copy all the required files.
My current libtool command is :
/bin/bash /home/ubuntu/php-extension/libtool --mode=link cc -DPHP_ATOM_INC -I/home/ubuntu/php-extension/include
-I/home/ubuntu/php-extension/main -I/home/ubuntu/php-extension -static -I/usr/include/php/20170718
-I/usr/include/php/20170718/main
-I/usr/include/php/20170718/TSRM
-I/usr/include/php/20170718/Zend
-I/usr/include/php/20170718/ext
-I/usr/include/php/20170718/ext/date/lib
-I/usr/local/include
-L/usr/local/lib -lcjson
-DHAVE_CONFIG_H  -g -O2
-o myextension.la -export-dynamic -avoid-version -prefer-pic -module -rpath /home/ubuntu/php-extension/modules
myextension.lo

How should I build the extension so it contains all the dependent libraries and there is no need to install library on target machine?


text:
Q: How to know the command run by a process? I have run multiple commands in different time as background process.
wget -r url1 &
wget -r url2 &
..............
..............
The result of ps -e shows 2 process named wget---
     2552 ?        00:00:01 wget
     2576 ?        00:00:00 wget
     ......        .............
     ......        .............

Now, I want to kill the process which is executing url2. How can I know which process runs which url?

A: Instead of -e option for ps command, use -f option.
user1    14298 13518  0 00:11 pts/1    00:00:00 sleep 100
user1    14299 13518  0 00:11 pts/1    00:00:00 sleep 50

This way you will see the parameters passed to the command as well, in your case different URLs

A: If this was done in an interactive shell setting, the second backgrounded job can be killed with kill %2.
If this was done in a shell script, you can record the PIDs and signal them thusly:
#!/bin/bash
wget http://example.com/bigfile1 &
pid1=$!
wget http://example.com/biggerfile2 &
pid2=$!
# Time passes..
# Impatience intensifies...
kill $pid2

If you want to see the full command lines (and environments) of your current session, you can use ps ex.


text:
Q: How do I make my command not mention the user? I just started coding my Discord bot and I made a command that replies to every message that isn't sent by a bot. When I tried it in DMs it works fine, but when I tried it in my server it would mention the user before the command. In the DM it would say just "test", but in the server it would say something like "@ExampleUser, test".
Is there a way I can fix this? Here's my code:
const Discord = require('discord.js');
const client = new Discord.Client();

client.on("message", (message) => {
  if (message.author.bot) return;
  return message.reply("test")
});

A: Instead of message.reply('test') use message.channel.send('test') that sends a message to the channel the original message was sent to.

A: Solution
use message.channel.send('string'); instead of .reply()

A: It's very easy :)
Instead of saying message.reply('message') you just have to say message.channel.send('message')


text:
Q: Background (cover) for iPad, iPhone I came across several ways and questions about the sizes of the ipad and iphone and how to use different css. Is it really necessary, especially now with more versions of the ipad and iphone to have a different background for each and every device?
Almost every answer/site about this problem tells the user to use the resolution 1024 for an iPad but according to Apple's site the latest iPad has a resolution of 2048 x 1536 pixels?
So do I need to make one background with 1024 in width for iPad 2 (or whatever), then one with 2048 for iPad 3, another one for iPhone etc or is there an easier solution?
I thought "background-size: cover" would be the solution for every resolution (since it scales automatically) but it apparently isn't since it doesn't seem to work on an iPad.

A:
So do I need to make one background with 1024 in width for iPad 2 (or
  whatever), then one with 2048 for iPad 3, another one for iPhone etc

No. Despite the different device resolutions, they still follow the original numbers in terms of targeting them with CSS. So all iPads respond to device-width: 1024px, and iPhones still stick with 320px, even if they now pack in far more pixels.
The only thing to be aware of is that iPhone5 is a little taller so it responds to 320 x 560px.
Anyhow, in terms of background-size, all of this is kind of irrelevant, because the whole point of it is that it can size the image appropriately to cover any screen if you use background-size: cover.