text:
Q: Working with a saved Access parameter query under (JDBC-)ODBC In my Java application I have to use data that comes from an Access 2010 database. I used the graphical query creator from Access to create the appropriate query and it works great.
Unfortunately, when I try to use a prepared statement with that query (in order to use a parameter) in my Java application I got an NPE
messageChildrenRequest.setString(1, blockId);
ResultSet result = messageChildrenRequest.executeQuery();

The NPE occurs when i set the parameter with setString() and my query is not execute but when i look with the debugger the statement is not null...
My query given by access is :
SELECT IRSIDD.[BLOCK ID], IRSIDD.[IDENTIFICATION CHIFFREE], IRSIDD.MSG_ID, MAIN.SUB_FIELD_ID, MAIN.ORDER, FIELD.[FIELD NAME], FIELD.TYPE, FIELD.[RC 'TYPE] "
FROM IRSIDD LEFT JOIN (MAIN LEFT JOIN FIELD ON MAIN.SUB_FIELD_ID = FIELD.[FIELD ID]) ON IRSIDD.[BLOCK ID] = MAIN.BLOCK_ID "
WHERE ((IRSIDD.[BLOCK ID])=?)

The StackTrace gives me :
Exception in thread "main"
java.lang.NullPointerException
    at sun.jdbc.odbc.JdbcOdbcPreparedStatement.clearParameter(Unknown Source)
    at sun.jdbc.odbc.JdbcOdbcPreparedStatement.setChar(Unknown Source)
    at sun.jdbc.odbc.JdbcOdbcPreparedStatement.setString(Unknown Source)

When I tried a very simple prepared statement :
SELECT * FROM table1 WHERE table1.id = ?

I didn't get any NPE when setting the parameter so I suspect that Access and java JDBC do not have the same way to deal with join.
Does someone already that kind of problem or can confirm that the structure of my query is the problem here?

A: Connection connection = null;
CallableStatement callStmt = null;
String myParam = "test";
String statement = "SELECT * FROM table1 WHERE table1.id = ?";
try {
connection = DatabasePoolUtil.getDefaultConnection(); //Connects
callStmt = connection.prepareCall(statement);
callStmt.setString(1,myParam);
callStmt.execute();
}
catch (SQLException ex) {
// Do something
}
finally { // connection has to be closed
if (callStmt != null) {
 callStmt.close();
  }
 if (connection != null) {
 connection.close();
}
}

A: The ODBC (and OLEDB) interfaces to an Access database expose different types of saved Access queries as either "Views" or "Stored Procedures":
Access query                     appears under ODBC/OLEDB as
-------------------------------  ---------------------------
Select query without parameters  View
Select query with parameters     Stored Procedure
Append query (INSERT)            Stored Procedure
Update query                     Stored Procedure
Delete query                     Stored Procedure

Since your Access saved query has parameters it will look like a Stored Procedure under ODBC and therefore you need to use a CallableStatement to work with it.
For example, given the following saved parameter query named [myParameterQuery] in Access
PARAMETERS specificID Long;
SELECT Table1.*
FROM Table1
WHERE (((Table1.ID)=[specificID]));

we need to use the following Java code to retrieve the row for ID=3:
String connectionString = "jdbc:odbc:"
        + "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
        + "DBQ=C:/Users/Public/32224442.accdb;";
try (Connection conn = DriverManager.getConnection(connectionString)) {
    try (CallableStatement cs = conn.prepareCall("{call myParameterQuery(?)}")) {
        cs.setInt(1, 3);  // set "specificID" parameter to 3
        try (ResultSet rs = cs.executeQuery()) {
            rs.next();
            System.out.println(rs.getInt(1));
        }
    }
} catch (Exception e) {
    System.err.println(e.getMessage());
    System.exit(0);
}

The corresponding C# code would be:
string myConnectionString =
        @"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
        @"Dbq=C:\Users\Public\32224442.accdb;";
using (var con = new OdbcConnection(myConnectionString))
{
    con.Open();
    using (var cmd = new OdbcCommand("{CALL myParameterQuery (?)}", con))
    {
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Parameters.Add("?", OdbcType.Int).Value = 3;  // set "specificID" parameter to 3
        using (OdbcDataReader rdr = cmd.ExecuteReader())
        {
            rdr.Read();
            Console.WriteLine(rdr[0]);
        }
    }
}


text:
Q: Exchange 2010 CAS and MB server In exchange 2010, can a CAS server from AD site A connect to a MB server on AD site B? Or it both of them have to be in the same AD site?
Thanks

A: A CAS server has to exist in each AD site that has a mailbox server.  Common with DAG though the mailbox itself might move between MB servers that are in different AD Sites.
I'm not really getting your question though.  Like Technet says, "When the Client Access server receives a user connection request, it queries Active Directory to determine which Mailbox server is hosting the user's mailbox. The Client Access server then retrieves the Active Directory site membership of that Mailbox server and proxies the connection to the Mailbox server."
If you are referring to a simple setup with a single CAS server and single MB server, then yeah I guess they do have to be in the same AD site since you have to have at least one CAS server in the site that holds a MB server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android folder not being created by eclipse On my new computer I downloaded eclispe Luna (4.4.2). I tried to install android on it (by going to https://dl-ssl.google.com/android/eclipse/ and installing all). It was installed, so I restarted eclipse and got the message:

Could not find SDK folder

And no android folder got created in any of my drives (its a new computer so I searched in any directory)! I removed eclipse, downloaded it again and tried and the same happend. I uninstalled DDMS and reinstalled it and the same happend. I uninstalled it and opened eclipse as administrator and reinstalled it and the same happend... If I click on Window -> Android SDK Manager I get that message and nothing happens.
What am I doing wrong? What am I missing? I am using the same workspace I used in my old computer that had worked fine with android (tough I used eclipse keplar, so when I opened the new workspace eclipse asked me to upgrage and I agreed).
Please don't tell me to move to Android Studio - my project in eclipse consists of many multiple sub projects and I really don't want to configure it a new (why the hell do we have Gradle?!)

A: It seems like you have only downloaded the plugin for eclipse. You also need to download the SDK from http://developer.android.com/sdk/index.html#Other

A: You should install Android SDK separately.
Here is the link to the page that will show you to install eclipse, adt and sdk.
Hope this helps.

A: I am assuming you are on a windows computer, so in Eclipse do the following:

*

*Window -> Preferences -> Android

*In the Android tab, there is a field saying "SDK Location". You can click browse and find where the folder "android-sdks" has been downloaded in your computer.

*Set the path to that folder as "SDK Location"

*It should be working now.

Usually the "android-sdks" folder is found under: C:\Users\< your-username >\android-sdks if it was downloaded from the ADT pluggin: https://dl-ssl.google.com/android/eclipse/


text:
Q: highcharts - Custom legend - sending the name of the filter to a php file I was able to reverse the behaviour of filters in highcharts so that clicking a series name, filters down, instead of removes the data.
and this is the code I used to do it.
                events: {
        legendItemClick: function(event) {
            if (!this.visible)
                return true;

            var seriesIndex = this.index;
            var series = this.chart.series;

            for (var i = 0; i < series.length; i++)
            {
                if (series[i].index != seriesIndex)
                {

                    series[i].visible ? series[i].hide() : series[i].show();
                }
            }

            return false;
        }
    },

Now, every time someone clicks on the a filter, I want to send the name of that filter to my php file for further processing, but havn't been able to do so. this is what I've tried
                events: {
        legendItemClick: function(event) {
            if (!this.visible)
                return true;

            var seriesIndex = this.index;
            var series = this.chart.series;

            for (var i = 0; i < series.length; i++)
            {
                if (series[i].index != seriesIndex)
                {

                    series[i].visible ? series[i].hide() : series[i].show();
                }
            }

                                                        if (window.XMLHttpRequest)
              {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
              }
            else
              {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
            xmlhttp.onreadystatechange=function()
              {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                }
              }
            xmlhttp.open("GET","/s.php?o="+series,true);
            xmlhttp.send();

            return false;
        }

    },

I think it could be a problem of not properly calling the name of the filter? where it says series, i've tried
seriesIndex, series, event.point.index.name,   and a lot of others with no luck. my question is if the current code I'm using in that events bracket is correct, and B, if I'm using the right string/variable to call the name of the filter/index.
correction* - using "seriesIndex" as the variable, works to an extent, it will send 0,1,2 (corresponding to the id of the filter), but only when it is the first selection clicked. It ceases to send itself to the php file if it is the 2nd filter clicked.
/// solved thanks to SteveP.
The function calling the php had to go before the first if statement, like this
                events: {
        legendItemClick: function(event) {
                                                                        if (window.XMLHttpRequest)
              {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
              }
            else
              {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
            xmlhttp.onreadystatechange=function()
              {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                }
              }
            xmlhttp.open("GET","/s.php?u="+this.name,true);
            xmlhttp.send();
            if (!this.visible)
                return true;

            var seriesIndex = this.index;
            var series = this.chart.series;
            for (var i = 0; i < series.length; i++)
            {
                if (series[i].index != seriesIndex)
                {
                    series[i].visible ? series[i].hide() : series[i].show();
                }
            }

            return false;
        }

    },

A: If you want to send the series name, try:
this.name

as 'this' should be the selected series, so this.name should be it's name, assuming you gave it one in your chart.


text:
Q: One signal - create segment to push to recent location I would like to, via OneSignal REST API :

*

*filter the push to users in a certain location (as in the doc) but it lacks sample code/relevant routes. The steps would be :

*

*store tags for users (documented here, this is fine)

*creating a segment (I don't see this in the docs)

*push by filtering by segment (this is covered here)

*Similarly I would like to be able to filter the push to users that visited a location in a certain date range (ex. last week, last month...). I am not completely sure this is possible using only OneSignal.
The minimum I would need is how to create a segment with OneSignal.
Edit : looks like there is a way in the dashboard, but I need to do it programmatically.

A: (I help work on OneSignal) OneSignal does not support programmatically targeting by a location at this time but we're planning on adding support for this in the near future.
One way to do some of this until then would be to provide the name or position of a location as tags. For instance you could use the tags lat=41.123, lon=55.331, then target users programmatically where the tags are greater than and less than the ranges you specify.
OneSignal does not provide built-in functionality to target by historical locations and we do not plan to add support for this, but you may be able to use tags to achieve your desired result.
Note that OneSignal does allow you to target by Player ID, so you could always store your users' Player IDs in your own system and do the calculation of who should receive a notification on your own.


text:
Q: Definition of C++ precompiled Headers Please help I've several questions : what are precompiled Headers ? what is their usage ? how to make one ? and how to include one ?

A: Precompiled headers (PCH for short) are something that the some compilers support. The support and what they contain [aside from "something that hopefully can be read quicker than the original header file"] is up to each compiler producer to decide. I have a little bit of understanding of how Clang does it's precompiled headers, and it's basically a binary form of the "parsed" C or C++ code in the header - so it produces a single file that doesn't need parsing [to the same level as the header file itself].
The purpose is to reduce the compile-time. However, in my experience, the LONG part of the compilation is typically code-generation with optimisation. However, in some instances, especially when LOTS of header-files are involved, the time to read and parse the header files can be a noticeable part of the overall compilation time.
Generally speaking, how they are used is that you tell the compiler that you want precompiled header, and for each compilation, the compiler will generate the precompiled header if it's not already there, and read it in when it is present [1] - commonly this is done for one named header file, which includes lots of other things. Microsoft Visual Studio typically has a file called "stdafx.h" that is precompiled - and at least in the case of MS products, this has to be the first file that is inclduded in a project [this is so that no other header file for example changes the meaning of some macro - I expect there is a hash of the compiler/command-line definitions of macros, so if one of those changes, the PCH is recompiled].
The idea is not to include every single header-file in this one precompiled file, but header files that are used in MOST files, and that are not changing often (the PCH needs to be regenerated if one if the files that is precompiled has changed, so it's no point in doing that if you keep changing the header-files frequently). Of course, like any other build dependency, anything using the precompiled header will need to be rebuilt if the PCH has changed.
For exactly how to use this, you will need to read the documentation for the compiler you are using.
[1] If nothing has changed that requires it to be rebuilt.


text:
Q: Cannot read property "name" of undefined while checking session So I'm new to express and I made some kind of program that registers the session only if you logged in successfully and then uses it in other routes to apply different stuff depending if the session exists or not.
However, the problem is that it gives me an error of
Cannot read property "name" of undefined

Why? I even logged in successfully so the session should exist, right?
This is the code:
// Importing modules/packages
let connection = require("./Connection.js");
let bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
let express = require("express");
let app = express();
var session = require("express-session");
app.use(cookieParser());
app.use(
  session({
    secret: "1E3ESS3DSS4DS4",
    saveUninitialized: true,
    resave: false,
    cookie: {
      path: "/",
      maxAge: 1000 * 60 * 60,
      httpOnly: true
    }
  })
);
let urlencodedParser = bodyParser.urlencoded({ extended: false });

// Server and routing
app.listen(3000, function() {});
app.set("view engine", "ejs");
app.get("/Signup", (req, res) => {
  res.render("Register");
});
app.get("/", function(req, res) {
  if (
    typeof req.session.user.name == "undefined" &&
    typeof req.session.user.password == "undefined"
  ) {
    res.render("Home");
  }
  res.redirect("Login");
});
app.get("/Login", function(req, res) {
  res.render("Login");
});

// Database's Connection
connection.connect(err => {
  if (err) {
    throw "ERROR! " + err;
  }
});

// Requesting and Receiving Data from body parser
app.post("/Signup", urlencodedParser, function(req, res) {
  res.render("Register");
  connection.query(
    `insert into users (Username, User_Password, Email_Address) values ("${
      req.body.Username
    }", ${req.body.Password}, "${req.body.Email}")`,
    function(err) {
      if (err) throw "An error has happened while excuting the query " + err;
    }
  );
});

app.post("/Login", urlencodedParser, (req, res) => {
  let sess = req.session;
  connection.query(
    `SELECT Username FROM users WHERE User_Password = ? AND Username = ?`,
    [req.body.Password, req.body.Username],
    function(err, results) {
      if (results.length === 0) {
        console.log(
          "Sorry, this username/password doesn't exist in our database."
        );
      } else {
        sess.user = {
          name: req.body.Username,
          password: req.body.Password,
          online: true
        };
        req.session.save();
      }
      res.render("Login");
    }
  );
});

How I fix it?

A: You have to check whole path if it exists not just last properties. If user is not an object even typeof will fail because it tries to access the property of undefined.
app.get("/", function(req, res) {
  if (
    typeof req.session.user != "object" || (
    typeof req.session.user.name == "undefined" &&
    typeof req.session.user.password == "undefined")
  ) {
    res.render("Home");
  }
  res.redirect("Login");
});


text:
Q: Communication between windows service and WPF with self-hosted owin web api I need to make a WPF application running under a regular account and a windows service that will run under the admin account. The WPF application will call a service that then performs the required tasks.
What I'm dealing with is the way of communication between these two elements. Mostly I came across references to WCF and named pipes with which I do not have much experience.
So I thought I would create a self-hosting owin web api and use it instead of WCF.
I would therefore like to ask what are the disadvantages of such a solution. Is the use of a self-hosted web api suitable for such purposes, or I would rather use WCF named pipes.
Thanks for any advice :-)


text:
Q: xml file does not save after element has been added I am trying to create a chat system and i want that every time after the user wrote a massage and pressed the button, the computer will add a new element to an xml file. I have succeded at creating a new massage element and adding it to the xml file but the problem is that afer i stop the debugging and check the xml file, I see that it didn't saved.
Here is the HTML file
    <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"              CodeFile="Chats.aspx.cs" Inherits="Chats" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

 Chat

                <input type="text" id="MassageText" />
                <button id="SendMassageButton" causesvalidation="False" type="submit" onclick="Chat(); return false">Send</button>

</asp:Content>

Here is the XML file:
    <?xml version="1.0" encoding="utf-8" ?>
<conversation>
  <massage>
    <from id="6">admin</from>
    <to id="7">blabla</to>
    <time>12/8/2014</time>
    <text>6 to 7</text>
  </massage>
  <massage>
    <from id="7">blabla</from>
    <to id="6">admin</to>
    <time>12/8/2014</time>
    <text>7 to 6</text>
  </massage>
  <massage>
    <from id="8">user1</from>
    <to id="7">blabla</to>
    <time>12/8/2014</time>
    <text>8 to 7</text>
  </massage>
</conversation>

I am sure that the element has been added to the XML file because I checked how many massages elements are exist after I have added the element and the answer was 4 instead of 3 which I actually have in the XML file.

A: See here for saving document:
XmlDocument doc = new XmlDocument();
 doc.AppendChild(doc.CreateElement("item","urn:1"));
 doc.Save(Console.Out);

http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.save(v=vs.110).aspx


text:
Q: Integration by parts between two functions of two variables and one integration variable Is it possible to do integration by parts on this?
I'm trying to manipulate the 2nd term in equation (3.109) at https://farside.ph.utexas.edu/teaching/plasma/Plasma/node38.html to look more like the 1st and 3rd terms, where the derivative is on "w". I think a simpler version of the problem looks like this:
$$ \int g(x,y) \frac{\partial}{\partial x} f(x,y) dy $$
From what I can tell, the answer is supposed to be
$$ \int g(x,y) \frac{\partial}{\partial x} f(x,y) dy = \int  f(x,y) \frac{\partial}{\partial x} g(x,y) dy $$
Note that $f$ and $g$ quickly fall to 0 at infinity, and the integral is over the infinite domain (surface terms are zero).
It might be useful to know that there is also some function $u=u(x,y) = x-y$ and $g$ is a function of $u$.
Attempt:
In single variable calculus, integration by parts usually looks like
$$\int udv = uv - \int vdu$$
In this case, we can consider
$$ df(x,y) = \frac{\partial f}{\partial x}dx + \frac{\partial f}{\partial y}dy $$


text:
Q: java imap, performance issues, fetching all mails I will use java mail api to handle mails like thunderbird etc. I have to fetch mails having 1000 messages. My design will be: When user performs a synch on a folder, i will get all uids of the messages in the folder:
Message[] msgs = ufolder.getMessagesByUID(1, UIDFolder.LASTUID);
// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);

I wil then compare the list of uids with the list stored in my db.
For the deleted ones, for example a message is not in the folder but in the db, i will mark it as deleted.
For the new ones, for example a message is in the folder but not in the db, i will mark as possible new. But, because messageuids are not safe (can be changed by the mail server on some cases), for the new mails, i will use additioanlly a custom hash value build from message id in the header + subject + receivedate and build a md5 hash. Only for the possible new mails i will use this hash and catch new mails.
For the moved messages, because their uids will be changed in the new folder, it will be flagged as deleted in the first and will be a new message in new folder, but the message will have same custom hash value becaue message id in the header and other properties will remain same duing the movement.
Question about performance issue: On each click on folder (folder synch) i will do the compare operation of all uids in the folder with the local uid list stored in the db to learn the deleted ones. I could not find another better way to accomplish this. As you know, thunderbird catches immediately a deleted message without relogin, even if the folder is large and the deleted message is very old (5 years). I think thunderbird also compares all message uids in that folder with a list stored locally.
How can i implement a better mechanism for the synch for a better performance? Does thunderbird apply a different approach? How can thunderbird
accomplish it so quickly?
If we were interested only for the new messages, i could have kept last stored uid and only compare the new messages later than that, but for the deleted ones, i already have to compare full folder. Additionally, UIDNEXT value is always -1 in my mail server, if it were set correctly, it will not help to get deleted ones again, a full compare is a must i think, am I wrong?
Note: I canot not use or add message listeners because the appliaction is server-client based and the mail handling task is on the server side and we do not support threads listeners etc. The events should be triggered from the client and the request is being processed on ther server and a response is returned and client handles the response on the gui.

A: What you want is called condstore or quick resync, RFC7162 in both cases. That's what Thunderbird uses.
That's a pair of extensions support commands like "give me all the UIDs that have changed since last time I connected", "tell me what's been deleted" and so on.

A: If you can't use threads to listen for these events from the mail server, your options are very limited.  Probably the best thing you can do is limit the resynchronization to the messages that are visible to the client.


text:
Q: _dl_open in ld-2.13.so invoked I would like to call _dl_open function from ld-2.13.so. I get the offset of this function from objdump and then I add it to library beginning address in order to get function address. Then I attach to the process by ptrace and inject my own binary code in which:

*

*I put into eax register address of the library's path.

*I put into ebx RLTD_LAZY

*I put into ecx NULL (it's a caller, but I don't get what's really is).

Then I call the function (which address is correctly calculated) and I get... nothing :) The library is not injected and I have no output. I found in ld-2.13.so also _dl_open_worker function which when I call I get:
./process: error while loading shared libraries: dlopen: invalid caller
What am I doing wrong?
Everything what I've done was based on: http://nologin.org/Downloads/Papers/remote-library-injection.pdf
Thanks in advance for any help.

A: Linux uses address space layout randomization (ASLR) to thwart remote buffer overflow attacks that do exactly what you're talking about.
When asking questions like this, I seriously recommend that you describe your legitimate need for the information. SO users aren't going to provide much assistance with apparently illicit activities.

A: You can do this using "hotpatch" from https://github.com/vikasnkumar/hotpatch
The code does everything you need to do. It handles the relative addressing. Still need to figure out the _dl_open part but should get that done in a couple of days.
Works for 64-bit well.

A: (I know this is an old question, but I am recording the answer here for future developers)
The problem was trying to put the mode/flags value into ebx when it should have been placed into edx. The following article describes how to invoke _dl_open manually in the context of library injection:
http://www.ars-informatica.com/Root/Code/2010_04_18/LinuxPTrace.aspx
They define _dl_open as:
void *
internal_function
_dl_open(const char *file, int mode, const void *caller);

Although the symbol is exported by libc it is still defined as an internal function, meaning its parameters are passed via registers in the following manner:
EAX = const char *file
ECX = const void *caller
EDX = int mode


text:
Q: How to check an Ajax request in cakephp? How to check an Ajax request in cakephp?

A: Depends on the version of cake.
1.3.x:
$this->RequestHandler->isAjax();

2.x || 3.x
$this->request->is('ajax');

A: Without the use of components you can use something like this:

$this->params['isAjax'];

This will return a bool.

A: this is the way whisch is described is doc.I have been using since i started using cakephp
if($this->RequestHandler->isAjax()){
//
}

A: *

*You need to enable the RequestHandler component

var $components = array('RequestHandler');

*

*Then you check if its an ajax request in your controllers with:

$this->RequestHandler->isAjax()
You can find more information about the RequestHandler component here

A: this question is an older one but just in case anyone comes across this like me and uses CakePHP 2:
RequestHandler::isAjax() is deprecated, use the Request Object's $this->request->is('ajax');
More info here

A: If you simply want to check the function of the php side, try:
$this->log('some debug',LOG_DEBUG);

then check app/tmp/logs/debug.log.


text:
Q: searching for a word in all triggers in a schema - oracle I'm having problems running my application - Oracle is raising an
ORA-04092: cannot COMMIT in a trigger issue.

Now I am trying to find the trigger which contains commit statement. Is it possible to find the trigger which has the commit statement in all `dba_triggers'?
select * from dba_triggers statement

gives me all dba triggers. Now I have to search these triggers with the word commit.

A: If you get the full error stack, you should be able to see what line of what trigger is throwing the error.  That's the most efficient approach.  For example, if you create a trigger that commits and run an INSERT, the stack trace will show you what line of what trigger caused the error.
SQL> create table t (
  2    col1 number
  3  );

Table created.

SQL> ed
Wrote file afiedt.buf

  1  create trigger trg_t
  2    before insert on t
  3    for each row
  4  begin
  5    commit;
  6* end;
SQL> /

Trigger created.

SQL> begin
  2    insert into t values( 1 );
  3  end;
  4  /
begin
*
ERROR at line 1:
ORA-04092: cannot COMMIT in a trigger
ORA-06512: at "SCOTT.TRG_T", line 2
ORA-04088: error during execution of trigger 'SCOTT.TRG_T'
ORA-06512: at line 2

You can search the source for all triggers looking for a particular string.  Something like this will look for the literal "COMMIT" in any trigger in whatever schemas you specify.
SELECT name, text, line
  FROM dba_source
 WHERE owner IN (<<schemas you want to search>>)
   AND upper(text) like '%COMMIT%';

On the other hand, there is a strong probability that the trigger that is failing is calling a stored procedure and it is the stored procedure that is committing.  So searching the source of your triggers may not be beneficial.
You could potentially mitigate that by doing a recursive query on DBA_DEPENDENCIES (or ALL_DEPENDENCIES or USER_DEPENDENCIES depending on your privilege level and the scope of what you want to search for) to find all of the procedures that are potentially called from any trigger and to search the source of all of those procedures from DBA_SOURCE.  But that's going to be much more complex than simply examining the full error stack.


text:
Q: Migrate from 2010 to 2019or 2016 We are looking at moving a site from 2010 to 2016 or 2019.
Since this is not a supported upgrade path using DB Attach, we are looking at recompiling the WSP'S and deploying them to the new world, and then move the content using Sharegate or something similar. The content does include MySites as well.
Does anyone know if the above approach has worked or should work.

A: It will work, but I would suggest the DB attach method over ShareGate or other third party tools.  Setup a SP2013 single server, attach content DBs to it, then migrate them to 2016, then 2019.  I know it is more work upfront, but you will get a cleaner migration with less issues in the end.

A: Agree with Josh, for upgrade, it is recommended to do DB attach approach and upgrade step by step (2010-2013,2013-2016)  You can test the DB before mount to see if the WSP's have issues.


text:
Q: jQuery Validation based on Next Prev values I have ran into this problem where I am specifying a Quanitity by both Units and Price. If Units is given, price must also be supplied and if price is given, Units must also be supplied. But they are both blank, then it is ok.
+----------+-------+
| Quantity | Units |
+----------+-------+
|          |       |
+----------+-------+

I have used the following code to check this condition and it does work for the first instance of the classes but not the proceeding ones.
$(".Quantity").rules("add",{
        required:function(element){
        return $(".Quantity").next('input').val() > 0;

    },
});

$(".Units").rules("add",{
        required:function(element){
        return $(".Units").prev('input').val() > 0;

    },
});

So basically it check only the first value of occurance and not the rest. What I want is it go through complete page and compare prev next value of each occurance. In my case, data is arranged in table and each cell contains Quantity and Price input boxes which I want to retrieve by prev next. but it is not working.
Here is codepen demo. Note that I am using bootstrap dialog as well in the example which shows total number of errors and again it stops at the first instances of the class, not showing all errors because I am using class based rules. Any help would be appreciated.

A: With this plugin's methods, when using a selector that targets more than one element, you must enclose the method within a jQuery .each()...
$(".Quantity").each(function() {
    $(this).rules("add",{
        required: function(element) {
            return $(".Quantity").next('input').val() > 0;
        },
    });
});

Otherwise, when you don't use an each(), only the first matching element is considered.

A: Answering it myself. I had to use the following code to fix my issue
$('.Units').each(function () {
    $(this).rules("add", {
        onkeyup: false,
        required: function (element) {
            return element.nextElementSibling.nextElementSibling.value > 0 ? true : false;
        },
    })
});

$('.Cost').each(function () {
    $(this).rules("add", {
        required: function (element) {
            return element.previousElementSibling.previousElementSibling.value > 0 ? true : false;
        },
    })
});

The actual code I used is more complicated where prev and next values were dependent on each other.


text:
Q: FFMPEG zoompan filter examples I need to create a video with ffmpeg with various pans and zooms using the zoompan filter. I have to be able to create zoom in, zoom out, pan to, and pan from effects to all areas of the video such as: top-left, top-middle, top-right, right, bottom-right, bottom-middle, bottom-left, left, and middle. So far, I have only been able to figure out how to zoom in to a few areas, such as:
Zoom in top-left:
-vf "zoompan=z='zoom+0.001':x='if(gte(zoom,1.5),x,x-1)':y='y':d=125"

Zoom in top-right:
-vf "zoompan=z='zoom+0.001':x='if(gte(zoom,1.5),x,x+1)':y='y':d=125"

Zoom in bottom-left:
-vf "zoompan=z='min(zoom+0.0005,1.5)':y='if(gte(zoom,1.5),y,y+1)':x='x':d=125"

I have not been able to find a good resource to explain how these numbers work and how I can figure out the specific zoompan filters for all these variations.
Help????

A: The zoompan filter expressions are evaluated each frame. The variables referenced in the expressions contain the last calculated value, or the default if it's the first frame.
The value of the evaluated zoom expression represents the ratio of the resulting dimensions to the original dimensions i.e. zoom = 3 means the zoom window has a third of the width and height of the input.
x and y represent where the top-left corner of the zoom window is placed within the input image.
d is the duration in frames that the zoom is evaluated and applied.
You should, as a matter of course, specify the output framerate fps and size s of the filter (see its documentation), else the filter will apply its defaults of 25 fps and 1280x720, which may not be what you want.
For smooth zooms, you may need to upscale the image beforehand.


text:
Q: Apple Mac image on Amazon EC2? I found that to start with apple app development you need to have some sort of Mac.
I wonder if one may load an image of an Mac OSx on an Amazon EC2 instance for this purpose.

A: Not going to work.  EC2 uses Xen for its virtualization technology, and the chance of a Mac Xen port is pretty much nil, due to Apple's famously tight control over their operating system.  Your best bet is probably to pony up for a Mac Mini; they're relatively cheap and could make a good starter dev box.
You want a local one anyway.  You'll be running IDEs and a bunch of interactive utilities; latency from using a remote desktop will make everything just that much more difficult.


text:
Q: How do I reverse my "slide to unlock" style text? I've been able to use code from another stack overflow question (iPhone "slide to unlock" animation) to make some text pulse in the "slide to unlock" style. At the moment, the mask moves from the left to the right. I'd like to reverse it so that instead of having it pulse from left to right, it pulses from right to left.
I've fiddled around with the code, trying to figure out how to reverse it but nothing I've done has got it to work properly! Everything I thought would work, hasn't.
Any help would be greatly appreciated.
self.view.layer.backgroundColor = [[UIColor blackColor] CGColor];

CGFloat textWidth = 320;
CGFloat textHeight = 76;

CALayer *textLayer = [CALayer layer];
textLayer.contents = (id)[self.MYSLIDEIMAGE.image CGImage];
textLayer.frame = CGRectMake(-69.0f, 350.0f, textWidth, textHeight);

CALayer *maskLayer = [CALayer layer];

// Mask image ends with 0.15 opacity on both sides. Set the background color of the layer
// to the same value so the layer can extend the mask image.
maskLayer.backgroundColor = [[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.1f] CGColor];
maskLayer.contents = (id)[[UIImage imageNamed:@"Mask.png"] CGImage];

// Center the mask image on twice the width of the text layer, so it starts to the left
// of the text layer and moves to its right when we translate it by width.
maskLayer.contentsGravity = kCAGravityCenter;
maskLayer.frame = CGRectMake(-textWidth +50, 0.0f, textWidth * 2, textHeight);

// Animate the mask layer's horizontal position
CABasicAnimation *maskAnim = [CABasicAnimation animationWithKeyPath:@"position.x"];
maskAnim.byValue = [NSNumber numberWithFloat:textWidth -50];
maskAnim.repeatCount = HUGE_VALF;
maskAnim.duration = 2.8f;
[maskLayer addAnimation:maskAnim forKey:@"slideAnim"];
textLayer.mask = maskLayer;
[self.view.layer addSublayer:textLayer];

A: Currently you're using byValue on the animation which means "start from where you are (zero) and go to this position". Instead, you can use fromValue and toValue to specify exactly where the animation should start and end. In this way you can control the direction.


text:
Q: Can anyone solve this error in my code to do with calling subs in userform? Error: array or user define expected I want to call different sub depending on what button the user clicks.
Private Sub CommandButton1_Click()
If OptionButton1 = True Then
    Sort A, B, n
    Exit Sub
ElseIf OptionButton2 = True Then
    Reverse A, B, n
    Exit Sub
End If

End Sub

The error comes up as "array or user define expected" but i have checked that I have defined the arrays A, B the same throughout my code.
Any ideas?

A: You should be using the property value of the your option buttons. Currently, you're trying to compare if the button itself (the actual physical control) is true.
For example, if you have a Car and want to check whether or not there is a driver, you would specifically check the driver seat and not just look at the entire car or any seat (hopefully this analogy doesn't confuse you).
So with a quick review of your code, it should look like so:
Private Sub CommandButton1_Click()
    If OptionButton1.Value = True Then
        Sort A, B, n
    Else
        Reverse A, B, n
    End If
End Sub

Also just to help you become a better programmer, use VBA naming conventions for your controls. It helps a lot if someone else has to ever use your code, whether it's a week or a year from now!


text:
Q: Go equivalent to std::set? What would be the equivalent in Go to a std::set? Note that only uniqueness is important, I don't care about ordering.
I've considered using dummy type, such as map[string]bool (where bool is the dummy), however often I find in Go I need to provide a type where one is not required, such as a channel used as a semaphore, and this case. Am I missing something idiomatic to Go?

A: Using a map with dummy values as a set is common practice in languages like Perl, which do not have sets. I think it is an acceptable way to get sets in Go, unless you want to implement it yourself or use some third-party implementation. Of course, your datatype has to be one that is allowed as the key in a map, i.e. not struct, array, or slice.

A: Using map[string]bool is perfectly fine.
There are also some more fancy libraries to handle sets, see for example: https://github.com/pwil3058/gosets
But I would still stick with a simple map, it is more idiomatic and simpler, which is always good.

A: Using map[string]bool (with true as the dummy value) or map[string]struct{} as a set is considered idiomatic Go. Each of them has its own pros and cons.
Assume:
b := make(map[string]bool)
s := make(map[string]struct{})

*

*Checking whether a set has an element is easier with b:
if b["x"] {
    // b has "x"
}

if _, ok := s["x"]; ok {
    // s has "x"
}

*Unless you can guarantee that b does not have any false values, iterating over the elements is easier with s:
for e, v := range b {
    if v {
        // e is an element of b
    }
}

for e := range s {
    // e is an element of s
}

*s is more memory-efficient than b.
As an alternative, you can use an open-source library. For instance:

*

*github.com/soroushj/menge implements sets of all basic types.

*k8s.io/apimachinery/pkg/util/sets implements sets of integers (byte, int, int32, int64) and strings.

Of course, currently, it's not possible to implement generic sets in Go. But with the planned addition of generics to Go, it will be possible in a later version (no earlier than 1.17).

A: If anyone need a set of int, you can use this:
package main
import "golang.org/x/tools/container/intsets"

func main() {
   var (
      a intsets.Sparse
      b bool
   )
   b = a.Insert(9)
   println(b) // true
   b = a.Insert(9)
   println(b) // false
}

https://pkg.go.dev/golang.org/x/tools/container/intsets


text:
Q: Runtime error 438 when InvokeMember clicking on VB6 In VB6, I am unable to click skip_ad_button. I get  the Runtime error:

runtime error 438 :object does not support this property error

What is the alternative to
WebBrowser1.Document.GetElementById("skip_ad_button").InvokeMember ("Click")

in VB6?

A: The runtime error is telling you that one of the objects you are using does not have the method you are calling. The possibilities are:

*

*WebBrowser1 does not have a Document property

*Document does not have a GetElementById property

*The object returned by GetElementById("skip_ad_button") does not have an InvokeMember property

Without knowing your exact object structure it would be very difficult to give a definitively correct answer. Reading this page may give you a starting point but you need to do some research.


text:
Q: Android : how to play music and record from the mic at the same time? I'm trying to make application can record my voice from mic built-in and music from android device at the same time. But my implementation make sound quality is too bad. Music sound from android device is too loud and i can't hear my voice. My code here :
            try
            {
            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(commonHeader.getOutputFilePath());
            recorder.setOnErrorListener(errorListener);
            recorder.setOnInfoListener(infoListener);
                recorder.prepare();
                recorder.start(); // Recording is now started
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

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

            }

            mplayer = new MediaPlayer();
            try {
                mplayer.setDataSource((String)downloadedData.get(1));

            } catch (IllegalArgumentException e) {

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

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

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

            }

            try {
                mplayer.prepare();
                mplayer.start();

            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                recFailed=true;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                recFailed=true;
            }
            if(recFailed==true)
            {
                stopRec();
                showErrorMsg();
            }

Anyone can show me how to make sound quality better ?


text:
Q: Subtracting value to file name suffix and bulk rename silly question, is there a UNIX command to rename files from the format:

"particles_00090.png" "particles_00091.png" .... "particles_00131.png"

to

"particles-00000.png" "particles-00001.png" .... "particles-00041.png"

Basically, I'd like to subtract the value 90 to the file suffix whilst keeping the number of numeric values (in the case above we have 5 zeroes) and convert underscore to dashes.

A: No, but you can script the algorithm:
for fn_orig in particles_*
do
    # split the file name up into 3 parts
    extension="${fn_orig##*.}"
    filename="${fn_orig%.*}"
    number="${filename#particles_}"

    # do the desired math
    subtract=$(expr $number + 0 - 90 )

    # reassemble to the desired format
    fn_new=$(printf "particles-%05d.%s" $subtract $extension)

    # output the command, in case tweaking is wanted
    # just remove the echo to actually do it
    echo mv "$fn_orig" "$fn_new"
done

Sample run:
$ ls
particles_00090.png  particles_00091.png  particles_00131.png  command.sh

$ ./command.sh
mv particles_00090.png particles-00000.png
mv particles_00091.png particles-00001.png
mv particles_00131.png particles-00041.png

A: Here's something not very nice and scalable, but that works in bash (it does it in 2 steps: files that require last 2 digits to be replaced and the ones that require last 3 digits):
for f in {90..99}; do mv particles_000$f particles_000$((f-90)) ; done
for f in {100..131}; do mv particles_00$f particles_00$((f-90)) ; done


text:
Q: SQL query get course number for certain student grades I'm working through some problems and I can't seem to get the expected results for this one. The question is below with what is in my code right now and also the expected results. If anyone help that would be great. I'm just trying to get a understanding on this and can't seem to get my head around what exactly this is asking as you can see my code I have now isn't close to what the expected result is as of right now. Also I added the schema this will show whats in what table if needed for your guys help.
Question:
List the course number of courses wherein students have received grades for every one of the possible defined grade types. Order by course number.
My code so far:
SELECT g.Student_id, g.Grade_type_code
FROM Grade g LEFT OUTER JOIN Section s
ON g.Section_id = s.Section_id
GROUP BY g.Student_id, g.Grade_type_code
ORDER BY g.Student_id;

Any help would be great, also here is the Schema.
DBMS: I'm using Oracle SQL Developer
Here is the Expected Result
COURSE_NO
----------
20
25
100
120
122
125
130
135

Note: The Chapter for this problem is based off using
LEFT OUTER JOIN

My Current results
STUDENT_ID GRADE_TYPE_CODE
---------- ---------------
   102 FI
   102 HM
   102 MT
   102 PA
   102 QZ
   103 FI
   103 HM
   103 MT
   103 PA
   103 QZ
   104 FI
   104 HM

A: Based on your ER diagram I believe this query should return a list of courses whose enrolled students have collectively received all of the grade types listed in the GRADE_TYPE table.
select s.course_no,
       c.descr,
       count(distinct g.grade_type_code) as num_grade_types
  from grade g
  join enrollment e
    on g.student_id = e.student_id
   and g.section_id = e.section_id
  join section s
    on e.section_id = s.section_id
  join course c
    on s.course_no = c.course_no
 group by s.course_no, c.descr
having count(distinct g.grade_type_code) = (select count(grade_type_code)
                                              from grade_type)

I didn't notice your expected result was only the course # (you can just get rid of the columns you don't want from the select list). Also the join to the COURSE table is only there to get the course description, so if you don't want the course description selected, you do not need that join.

A: You need to select COURSE_NO instead. And also use JOIN and not LEFT JOUTER JOIN.
Something like this:
select COURSE_NO from
(
SELECT distinct (s.COURSE_NO)
FROM Grade g JOIN Section s
ON g.Section_id = s.Section_id
)
ORDER BY s.COURSE_NO;


text:
Q: Does the API provide scroll buttons for ListView I have a client who wants a conventional scrollbar for ListViews in their application. The reason why is because this application will be used exclusively with their devices which happen to feature resistive screens. The screens don't track gestures very well without a stylus and a stylus will not always be available to the user. Hence the conventional scrollbar as a fallback UI control. A fast scroll thumb will not be a useful solution to this problem.
What I have found in the API that is of some use are xml attributes which allow me to approximate the behaviour of the track and thumb such as:
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="insideInset"
android:fadeScrollbars="false"

But I haven't found anything in the API that would take care of including scroll buttons at the top and bottom of the track.
Am I correct in concluding that the API does not provide this functionality?
If so, my only option would be to use a couple of buttons that change the list position. This is a doable solution of course but I wanted to make sure that I wasn't reinventing yet another wheel.
I have to support as far back as 2.2.
Scrollbar Example:

A:
Am I correct in concluding that the API does not provide this functionality?

Yes, you are. The API does not support buttons for ListView scrolling. You'll have to implement this functionality yourself.
Edit: A quick example based on the comments below, extending ListView to support adding of buttons.
private void init() { // Call this after the ListView is in your existing layout, perhaps in onLayout?
    // The following two lines create a new LinearLayout. If you want to design the layout in XML, you'll have to use LayoutInflater.
    LinearLayout newLayout = new LinearLayout(getContext());
    newLayout.setOrientation(LinearLayout.HORIZONTAL);
    newLayout.setLayoutParams(getLayoutParams());

    ViewGroup parent = (ViewGroup) getParent();
    int index = parent.indexOfChild(this);
    parent.removeView(this);
    newLayout.addView(this);
    parent.addView(newLayout, index);

    // Now, you can customize your LinearLayout.
    newLayout.addView(...); // Maybe add a vertical LinearLayout to contain your two buttons stacked upon each other?
}

This is just a rough concept, but it should get you going.

A: Paul answer is the right answer
There is a thing called Fast Scroll which kind of does what you want.
You can enable it via XML:
android:fastScrollEnabled="true"
Or in code:
getListView().setFastScrollEnabled(true);
It's as close as it can get to what you want (without using custom views).
EDIT:
I forgot to mention that this will only work when there is enough elements on the list. It has to be around 4 times the length of what is currently visible on screen.

A: Eric is right... almost.
There is a thing called Fast Scroll which kind of does what you want.
You can enable it via XML:
android:fastScrollEnabled="true"

Or in code:
getListView().setFastScrollEnabled(true);

It's as close as it can get to what you want (without using custom views).
EDIT:
I forgot to mention that this will only work when there is enough elements on the list. It has to be around 4 times the length of what is currently visible on screen.


text:
Q: Oracle SQL: select from different tables from the result of a variable Hi,
I need to create a select with a condition for the from clause: if the variable is equal to POS the select must be done with table tb_a and if the variable is equal to PRE the selected will be done with the table tb_b.
I tried both ways below, but neither worked. The number of columns in the tables is different.
SELECT * FROM tb_a WHERE '&prod' = 'POS'
UNION ALL
SELECT * FROM tb_b WHERE '&prod' = 'PRE';

SELECT *
  FROM
 (CASE '&prod'
  WHEN 'prod' = 'POS' THEN tb_a
  WHEN 'prod' = 'PRE' THEN tb_b
  END);

Can you help me please?

A: Of course it works.
SQL> create table tb_a as select * from dept where deptno in (10, 20);  --> for POS

Table created.

SQL> create table tb_b as select * from dept where deptno in (30, 40);  --> for PRE

Table created.

SQL> select * from tb_a where '&&prod' = 'POS'
  2  union all
  3  select * from tb_b where '&&prod' = 'PRE';
Enter value for prod: POS

    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS

SQL> undefine prod
SQL> /
Enter value for prod: PRE

    DEPTNO DNAME          LOC
---------- -------------- -------------
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON

SQL>

A: You can create a function (or a procedure) which returns a record set of SYS_REFCURSOR type parameter after accepting one of your parameters (POS,PRE) no matter what structure has your tables(tb_a or tb_b) such as
CREATE OR REPLACE FUNCTION Get_tab_ab( i_prod VARCHAR2 ) RETURN SYS_REFCURSOR IS
  v_recordset  SYS_REFCURSOR;
  v_sql        VARCHAR2(32767);
BEGIN
  v_sql := 'SELECT * FROM '||CASE
                             WHEN i_prod = 'POS' THEN
                                  'tb_a'
                             WHEN i_prod = 'PRE' THEN
                                  'tb_b'
                              END;
  OPEN v_recordset FOR v_sql;
  RETURN v_recordset;
END;
/

and then call from SQL Developer's console like this
SQL> DECLARE
    res SYS_REFCURSOR;
BEGIN
   :res := Get_tab_ab('POS');
END;
/

SQL> PRINT res;

or you can use a common ROWTYPE variable because the structures of the tables(tb_a or tb_b) are identical considering you are combining them with a UNION ALL operator along with FETCH..INTO clause. This time you'll directly print out the desired columns without creating a stored object such as a function or procedure, just switching the value of the variable v_prod
DECLARE
  v_recordset  SYS_REFCURSOR;
  v_rec        tb_a%ROWTYPE;
  v_sql        VARCHAR2(32767);
  v_prod       VARCHAR2(3) := 'POS';
BEGIN

  v_sql := 'SELECT * FROM '||CASE
                             WHEN v_prod = 'POS' THEN
                                  'tb_a'
                             WHEN v_prod = 'PRE' THEN
                                  'tb_b'
                              END;
  OPEN v_recordset FOR v_sql;
  LOOP
     FETCH v_recordset INTO v_rec;
    EXIT WHEN v_recordset%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(v_rec.col1||' '||v_rec.col2||' '||v_rec.col3);
  END LOOP;
  CLOSE v_recordset;

END;
/

A: If the logic of choosing the table must be done in the SQL script, you need to pass in the PRE or POS to the script, use a bind variable to determine the table name, convert the bind variable into a substitution variable, and then select from the substitution variable. (It seems like there ought to be a simpler way to do this.)
--Pass in either "PRE" or "POS" to this script, and it will select from the appropriate table.

--AVoid the "old" and "new" lines when variables are substituted.
set verify off;

--Create a bind variable and a substitution variable.
variable table_name_bind varchar2(128);
column table_name_column new_value table_name_substitution_variable noprint

--Assign the bind variable based on the input argument.
begin
    if '&1' = 'POS' then
        :table_name_bind := 'tb_a';
    elsif '&1' = 'PRE' then
        :table_name_bind := 'tb_b';
    else
        raise_application_error(-20000, 'Unexpected input value &1');
    end if;
end;
/

--Convert the bind variable into the substitution variable through a SQL statement.
select :table_name_bind table_name_column from dual;

--Select from the substitution variable:
select * from &table_name_substitution_variable;

exit;


text:
Q: How to avoid designing classes whose member functions depend on each other? Let's say I have a class called Adder:
class adder(object):
  def __init__(self, a, b):
     self.a=a
     self.b=b
     self.result = None

  def perform_addition(self):
     self.result = self.a + self.b
     return self.result

If I instantiate this class:
myAdder = adder(1,2)

Then the value of myAdder.result depends on calling perform_addition() first, otherwise it'll always remain None. It other words, there's a dependency on perform_addition() for the value of self.result. And if we extrapolate, a more complex class can have a chain of dependencies: ie, you have to call functions A, B, and C before D, because they in turn populate the necessary variables that the next function needs.
Is this bad class design? What is the remedy for it?
I think the above is a example of: https://en.wikipedia.org/wiki/Sequential_coupling

A: I think it all depends on what you want to do and how you want to go about it. the code you have is not necessarily bad, if you want a static dependency on 'perform_addition()' for the value of 'self.result' . But if you want a dynamic dependency, then the code below will be a good and simple approach. this way when an object is created by instantiating the class with values 'a' and 'b', 'self.result' will be automatically computed. you could also use more advanced tools like properties, decorators, descriptors etc. like i said, it all depends on what you want.
Class adder(object):
    def __init__(self, a, b):
        self.a=a
        self.b=b
        self.result = self.perform_addition()

    def perform_addition(self):
        self.result = self.a + self.b
        return self.result

A: This would be a good case to make result a property instead, so that the addition is only performed when the result attribute is accessed:
class adder(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @property
    def result(self):
        return self.a + self.b

myAdder = adder(1,2)
print(myAdder.result)

This outputs: 3
In case the result attribute is expected to be accessed multiple times and that the calculation involved is expensive, you can save the result in an instance variable to avoid re-calculations:
class adder(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self._result = None

    @property
    def result(self):
        if self._result is None:
            self._result = self.a + self.b
        return self._result


text:
Q: AJAX Callback not being called This is my ajax function:
function ajax_call(call_method,data_to_send) {
    logger("function ajax_call. var data_to_send: ");
    logger(data_to_send);
    $('.clickable save_button').hide()
    $.ajax({
      type: 'POST',
      url: call_method,
      data: data_to_send,
      success: function(data){
            logger("data returned to page after ajax call: ");
            logger(data);
            $('.error_msg').html("Successfully saved record to database.");
            $('.error_msg').fadeIn('slow');
            setTimeout("$('.error_msg').fadeOut('slow');",5000); // 5 secs to give user enough time to read
            $('.clickable save_button').show()
            response_dispatcher(data); // This should contain object type at least
      },
      failure: function(){
            $('.error_msg').html("There was an error while saving this information. Please try again. " +
                                    "If the error persists, please contact us using the contact form.");
            $('.error_msg').show;
            $('.clickable save_button').show()
      },
      dataType: 'json'
    });
}

And, this is the data sent to my method on the backend:
    {
    'display_order':"3",
    'goal':"dummy goal",
    'id':-1,
    'object_type':"goal"
    }
I've verified within my application that this same data is received.
Here is my Django view method:
@login_required
def update_goal_view(request):

    if request.method == 'POST' and request.is_ajax:
        # Example data sent from AJAX Request
        #qd = {u'display_order': [u'23'], u'object_type': [u'goal'], u'goal': [u'dummy goal'], u'id': [u'-1']}
        qd = request.POST
        goal = qd.get('goal','')
        display_order = qd.get('display_order',99999)
        id = int(qd.get('id',''))
        object_type = qd.get('object_type','')

    # For now, just return something to test populating data to the page
    id = '100'
    goal = 'goal returned'
    object_type = object_type
    data = {'id':id,'goal':goal,'object_type':object_type}
    return HttpResponse(data,mimetype="application/json")

In Firebug, I see this after the ajax call:
POST http://127.0.0.1/xml/update_goal 200 OK 12ms

The issue is, when that it appears that my success callback is never called... I say that because as you can see from above, I there should be a message written to my logger but there isn't one. I know my logger works because of all the other messages outside of the callback that do get written to my logger.

A: I don't think Django does automatic serialization for dictionaries. You'll have to serialize them to JSON by hand.
import simplejson

# ...

return HttpResponse(simplejson.dumps(data), mimetype="application/json")

A: You don't show the code that triggers the ajax_call function. If it's as part of the onclick event for a submit button, or the onsubmit event for a form, the usual cause is that you've forgotten to prevent the form from submitting normally - so the page refreshes and the Ajax call is lost.
Use event.preventDefault() in your event handler to fix this.


text:
Q: Responsive Bootstrap Design I am trying to make responsive card design.
Bootstrap Card
I want the cards to appear on the phones in a single row and one below the other.

Like this
Should I try css @media queries? I am actually trying to learning flexbox so if you can tell me with flexbox it would be good for me i guess. I tried some css codes but didn't work.Thanks.

<!DOCTYPE html>

  <title>asdas</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="still.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

1 Card title

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

2 Card title

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

3 Card title

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

4 Card title

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

A: Try changing all your
 for
!
Bootstrap 4 documentation


text:
Q: How to send email using cakephp framework? No clue how to send an email as soon as an order has been saved.  The purchaser will enter in an email in the order form and a confirmation email is sent using CakePHP 2.0.  I've tried so many different ways but I'm a noob and need direction.  Please direct me!
  <?
    class OrdersController extends AppController
    {
       var $name = 'Orders';
       var $scaffold;
       function add()
       {
          if ($this->request->is('post'))
          {
               if ($this->Order->save($this->request->data))
               {
                   $this->Session->setFlash('Order has been saved');
                   $this->redirect(array('action' => 'index'));
               }
               else
               {
                   $this->Session->setFlash('Unable to add order');
               }
          }
       }
    }
  ?>

A: CakePHP provides a CakeEmail class for this purpose: http://book.cakephp.org/2.0/en/core-utility-libraries/email.html


text:
Q: C# insert method inside derived collection - binding stops working, but outside works firstly sorry for maybe not the best title, I didn't know how to express it better. This also means I could've missed similar answered questions. Feel free to suggest a better one title for the others :)
My question is pretty simple.
I have derived collection limited to my object, it looks like this:
public sealed class TrajectoryCollection<T> : ObservableCollection<T> where T : TrajectoryPoint
{
    public string FileName { get; set; }

    public void AddPointUnder(T selectedPoint)
    {
        var newPoint = (TrajectoryPoint)selectedPoint.Clone();
        var nextIndex = Items.IndexOf(selectedPoint) + 1;

        newPoint.SetPosition(PositionBetween(selectedPoint, Items.ElementAt(nextIndex)));

        Items.Insert(nextIndex, (T)newPoint);
        RecalculatePointIndexes();
    }

    public void RemovePoint(T item)
    {
        Remove(item);
        RecalculatePointIndexes();
    }

    private void RecalculatePointIndexes()
    {
        for (int i = 0; i < Count; i++)
        {
            Items.ElementAt(i).Number = i + 1;
        }
    }

    private Point3D PositionBetween(Point3D first, Point3D second)
    {
        return new Point3D(Math.Round((first.X + second.X) / 2, 3), Math.Round((first.Y + second.Y) / 2, 3), Math.Round((first.Z + second.Z) / 2, 3));
    }
}

and in my ViewModel I have this (Trajectory is bound to ListView itemsource):
public TrajectoryCollection<TrajectoryPoint> Trajectory
{
    get => _trajectory;
    set => SetProperty(ref _trajectory, value);
}
public TrajectoryPoint SelectedPoint
{
    get => _selectedPoint;
    set => SetProperty(ref _selectedPoint, value);
}

private void RemovePointFromTrajectoryExecute()
{
    var selectedIndex = Trajectory.IndexOf(SelectedPoint);
    Trajectory.RemovePoint(SelectedPoint);
    SelectedPoint = Trajectory.ElementAt(selectedIndex);
    RefreshViewport();
}

private void AddPointToTrajectoryExecute()
{
    var selectedIndex = Trajectory.IndexOf(SelectedPoint);
    Trajectory.AddPointUnder(SelectedPoint);
    SelectedPoint = Trajectory.ElementAt(selectedIndex + 1);
    RefreshViewport();
}

private void RefreshViewport()
{
    RaisePropertyChanged("Trajectory");
    RaisePropertyChanged("SelectedPoint");
}

Removing point works but adding doesn't. After adding one point, it IS added to that collection (I have verified it), but ListView won't show it - it behaves like it skips that added line (so it shows for example items 1,2,3,5,6...) and when I scroll down, it throws an exception

System.InvalidOperationException: 'An ItemsControl is inconsistent with its items source.

BUT. When I move that code from derived collection to my ViewModel, so it looks like this:
private void AddPointToTrajectoryExecute()
{
    var newPoint = (TrajectoryPointModel)SelectedPoint.Clone();
    var nextIndex = Trajectory.IndexOf(SelectedPoint) + 1;
    //new Point3D is PositionBetween
    newPoint.SetPosition(new Point3D(Math.Round((SelectedPoint.X + Trajectory.ElementAt(nextIndex).X) / 2, 3), Math.Round((SelectedPoint.Y + Trajectory.ElementAt(nextIndex).Y) / 2, 3), Math.Round((SelectedPoint.Z + Trajectory.ElementAt(nextIndex).Z) / 2, 3)));

    Trajectory.Insert(nextIndex, newPoint);
    RefreshViewport();
}

it works as it is supposed to and without any exceptions!
Could please anyone explain why this is happening? And what can I do to make working my Collection.AddPointUnder() method?
Thank you in advance!

A: I think the problem is as follows: In your add you are inserting in the underlying Items collection. While the remove happens directly on the ObservableCollection. Use Insert or InsertItem on the ObservableCollection and it should update your view just fine. This is because the Items collection of the ObservableCollection is not observable.


text:
Q: Efficient way of taking Logarithm function in a sparse matrix I have a big sparse matrix. I want to take log4 for all element in that sparse matrix.
I try to use numpy.log() but it doesn't work with matrices.
I can also take logarithm row by row. Then I crush old row with a new one.
# Assume A is a sparse matrix (Linked List Format) with float values as data
# It is only for one row

import numpy as np
c = np.log(A.getrow(0)) / numpy.log(4)
A[0, :] = c

This was not as quick as I'd expected. Is there a faster way to do this?

A: You can modify the data attribute directly:
>>> a = np.array([[5,0,0,0,0,0,0],[0,0,0,0,2,0,0]])
>>> coo = coo_matrix(a)
>>> coo.data
array([5, 2])
>>> coo.data = np.log(coo.data)
>>> coo.data
array([ 1.60943791,  0.69314718])
>>> coo.todense()
matrix([[ 1.60943791,  0.        ,  0.        ,  0.        ,  0.        ,
          0.        ,  0.        ],
        [ 0.        ,  0.        ,  0.        ,  0.        ,  0.69314718,
          0.        ,  0.        ]])

Note that this doesn't work properly if the sparse format has repeated elements (which is valid in the COO format); it'll take the logs individually, and log(a) + log(b) != log(a + b). You probably want to convert to CSR or CSC first (which is fast) to avoid this problem.
You'll also have to add checks if the sparse matrix is in a different format, of course. And if you don't want to modify the matrix in-place, just construct a new sparse matrix as you did in your answer, but without adding 3 because that's completely unnecessary here.

A: I think I solve it with very easy way. It is very strange that no one could answer immediately.
# Let A be a COO_matrix
import numpy as np
from scipy.sparse import coo_matrix
new_data = np.log(A.data+3)/np.log(4) #3 is not so important. It can be 1 too.
A = coo_matrix((new_data, (A.row, A.col)), shape=A.shape)


text:
Q: Find all integer solutions: $x^4+x^3+x^2+x=y^2$ Find all integer solutions of the following equation:
$$x^4+x^3+x^2+x=y^2$$

A: The equation
$$y^2 = x^4 + x^3 + x^2 + x = x(x+1)(x^2+1)\tag{*1}$$
has four trivial solutions over $\mathbb{Z}\times\mathbb{Z}$:
$$(x,y) = (-1,0), (0, 0),(1,\pm 2)$$
To determine whether there are other non-trivial solutions, let's look at an equivalent problem:
$$y^2 = \begin{cases}
z(z + 1)(z^2 + 1), &\text{ for } z = x \ge 2\\
z(z - 1)(z^2 + 1), &\text{ for } z = -x \ge 2\tag{*2}
\end{cases}$$
Notice
$$\gcd(z(z\pm 1),z^2+1) = \gcd( \pm z - 1, z^2 + 1) = \gcd(\pm z - 1,2) = 1 \text{ or } 2$$
Any solution of $(*2)$ must have one of the following two factorizations:
$$\begin{cases}
z(z\pm 1) &= p^2,\\
z^2 + 1   &= q^2,\\
y &= \pm pq;\end{cases}
\quad\text{ or }\quad
\begin{cases}
z(z\pm 1) &= 2p^2,\\
z^2 + 1   &= 2q^2,\\
y &= \pm 2pq.\end{cases}\quad\text{ with } \gcd(p,q) = 1.$$
We can rule out the factorization on the left because for $z \ge 2$, $z^2 + 1$ is never a square. For the factorization on the right, we can rewrite the $x$ part as
$$\left\{\begin{array}{ccrl}
(2 z \pm 1 )^2 &-& 8p^2 &= 1\\
z^2 &-& 2q^2 &= -1
\end{array}\right.\tag{*3}$$
Define $A, B : \mathbb{Z} \to \mathbb{Z}$ by
$$A(k) + B(k) \sqrt{2} = (1+\sqrt{2})^k$$
It is known the positive integer solutions of Diophantine equations like those in $(*3)$
has the form
$$\left\{\begin{array}{ccl}
2 z\pm 1 &=& A(2m)\\
2p &=& B(2m)\\
z &=& A(2n-1)\\
q &=& B(2n-1)\\
\end{array}\right.
\quad\quad\text{ for } m , n \in \mathbb{Z}_{+}.
$$
It is clear $2 z \pm 1 \ge z \implies 2m \ge 2n-1$.
Notice $\frac{A(k+1)}{A(k)} \to 1+\sqrt{2} > 2$ as $k \to \infty$.
For any $n$ large enough such that $A(2n) > 2 A(2n-1) + 1$, there are no way to find
a $m$ to satisfy $(*3)$. A brute force computation shows that this
happens as early as $n \ge 2$.
This leaves us the cases $n = 1$. It is easy to check
for $n = 1$, one can choose $m = 1$ to make $(*3)$ works. However,
$$
m = n = 1 \quad\implies\quad
\left\{\begin{array}{ccl}
2 z\pm 1 &=& A(2) = 3 \\
2p &=& B(2) = 2\\
z &=& A(1)  = 1\\
q &=& B(1)  = 1\\
\end{array}\right.
\quad\iff\quad
(x,y) = (1,\pm 2)
$$
corresponds to a pair of trivial solutions we have covered before. The conclusion is aside from the four trivial solutions, $(*1)$ doesn't have any non-trivial solution.

A: The following shows that the only solutions are
$$(0,0),(-1,0),(1,2),(1,-2)$$
by using a birational transformation to an Elliptic curve.

1. Birational transformation to an Elliptic curve
Denote
$$C: v^2-u^4-u^3-u^2-u=0$$
It is clear that if $u=0$, then $v=0$. For the other case, $u\neq 0$, we can divide by $u^4$:
$$\dfrac{v^2}{u^4}-1-\dfrac{1}{u}-\dfrac{1}{u^2}-\dfrac{1}{u^3}=0$$
Rearranging:
$$\left(\dfrac{v}{u^2}\right)^2=\left(\dfrac{1}{u}\right)^3+\left(\dfrac{1}{u}\right)^2+\left(\dfrac{1}{u}\right)+1$$
Which is in fact an Elliptic curve:
$$E: Y^2=X^3+X^2+X+1$$
In other words, we have a birational transformation $\phi$:
\begin{align*}
\phi: C &\to E\\
(u,v) &\mapsto \left(\dfrac{1}{u},\dfrac{v}{u^2}\right) = (x,y)
\end{align*}
(We know this type of transformation exists since we can compute genus of $C$ to be 1.)
If $(u,v)\in \Bbb Z^2$ is an integer solution for $C$, then $\left(\dfrac{1}{u},\dfrac{v}{u^2}\right)$ is a rational point on $E$.

In other words, it suffices to find all rational points of the form $\left(\dfrac{1}{u},\dfrac{v}{u^2}\right)$ on $E$.

In particular, notice that $\dfrac{1}{u}$ has numerator $1$ which is very restrictive. We shall make use of this constraint to make our main deduction.

2. Rational points on $E$
Using Sage, we find that the Mordell-Weil group over $\Bbb Q$ has the structure
$$E(\Bbb Q)\cong \Bbb Z_2\times \Bbb Z$$
Where the order two torsion is $P=(-1,0)$ and the free group generator is $Q=(0,1)$.
In other words all rational points are written as:
$$E(\Bbb Q)=[a]P\oplus [b]Q, \;\;\;\; (a,b)\in [0,1]\times \Bbb Z$$
Clearly $Q$ does not correspond to a solution. On the other hand, $P=(-1,0)$ has $x$-numerator 1. Hence we let $u=-1$:
$$v^2=(-1)^4+(-1)^3+(-1)^2+(-1)=0,$$
and we find a solution in $C$:
$$(u,v)=(-1,0)$$

3. A useful lemma
We shall be using this later:

If $(X,Y)\in E(\Bbb Q)$, then:
  $$(X,Y)=\left(\dfrac{m}{e^2},\dfrac{n}{e^3}\right)$$
  for some
  $$m,n,e\in \Bbb Z,\;\;\;\;\gcd(m,e)=\gcd(n,e)=1$$
  (This can be shown using $p$-adic valuations.)

4. Solving the main problem
We have seen that $Q=(0,1)$ does not correspond to a solution. Similarly,
$$[2]Q=\left(\dfrac{-3}{4}, \dfrac{-5}{8}\right)$$
so that $[2]Q$ also does not correspond to a solution.
Now let $R=P$ or $R=[a]Q, a\geq 2$. We want to show that $R\oplus Q$ cannot correspond to a solution. Then by induction
$$\{P\oplus [a]Q,[a]Q\;|\;a\geq 1\}$$
cannot be a solution and we would have covered $[r]P\oplus [s]Q, (r,s)\in [0,1]\times \Bbb N$.
Since $R\neq Q$, we can derive a formula for point addition with $Q$:
$$R\oplus Q=\left(\dfrac{2+x-2y}{x^2},\dfrac{4 + 3 x + 2 x^2 + x^3 - 4 y - x y}{x^3}\right)$$
Recall that if indeed some $(u,v)$ maps to a rational point in $E$, then the $x$-coordinate satisfies:
$$x(R\oplus Q)=\dfrac{2+x-2y}{x^2}=\dfrac{1}{u}$$
Now using our lemma in (3):
$$\dfrac{2+x-2y}{x^2}=\dfrac{2+(m/e^2)-2(n/e^3)}{(m/e^2)^2}=\dfrac{1}{u}$$
$$\dfrac{(2e^3+me-2n)e}{m^2}=\dfrac{1}{u}$$
From which we draw the conclusion that
$$e|m^2$$
Since $\gcd(m,e)=1$, this can only happen if $e=\pm 1$.
Either way, this implies that $(x,y)=(m/e^2,n/e^3)$ are integral points.
(Perhaps can be solved without needing this information, but quite tedious.)
Sage tells us that the only integral points are
$$(-1, 0), (0,\pm 1), (1,\pm 2), (7,\pm 20)$$
of which $(0,\pm 1)=\pm Q$ is not possible by construction of $R$.
Individual checking of the rest tells us that only $(-1,\pm 0),(1,\pm 2)$ results in $u=\pm 1$. We have seen the case $u=-1$ in section (2). For $u=1$::
$$v^2=1^4+1^3+1^2+1=4$$
From which we deduce $v=\pm 2$. Thus far we have the points
$$(u,v)\in \{(0,0),(-1,0),(1,2),(1,-2)\}$$
From the induction, we conclude that there are no other possible candidates corresponding to
\begin{align*}
R &=P\oplus [a]Q, a\geq 1\\
R &= [a]Q, a\geq 1
\end{align*}
It remains to cover the rest of the cases. Since $P$ is order two, $[-1]P=P$. Then immediately
$$P\oplus [a]Q = [-1]P\oplus [a]Q, a\geq 0$$
so that these are also not solutions.
The inverse of a point does not change the $x$-coordinates:
$$-(x,y)=(x,-y)$$
Therefore if $R$ is not a solution, then $-R$ is also not a solution. This shows that
$$-(P\oplus [a]Q)=[-1]P\oplus [-a]Q=P\oplus [-a]Q$$
$$-([a]Q)=[-a]Q, a\geq 1$$
are not solutions.
Therefore we have covered all the cases and we are done.

5. Sage codes for reference

E = EllipticCurve([0,1,0,1,1]);
  tor = E.torsion_points();
  rank = E.rank();
  gens = E.gens();
  integralPoints = E.integral_points();

A: When $|x|>1$ we have
$$(2x^2+x)^2<4(x+x^2+x^3+x^4)<(2x^2+x+1)^2.$$

A: EDIT : The case (1) in my answer has a big mistake. The case (2) is true.
$(x,y)=(0,0)$ is one of the solutions. In the following, suppose that $(x,y)\not=(0,0).$
We have
$$x(x+1)(x^2+1)=y^2.$$
First, we know that $x$ and $x+1$ are coprime, and that $x$ and $x^2+1$ are coprime, too. This leads that there is an integer $k$ such that $x=k^2.$ (see the right hand side)
In the following, we break up the answer into two cases.
(1) The case that $x+1$ and $x^2+1$ are not coprime.
Letting $$x+1=ps,x^2+1=pt\ \ (\text{$p$ is a prime number, $s,t\in\mathbb Z$})$$
we have
$$(ps-1)^2+1=pt\iff p(t-ps^2+2s)=2\Rightarrow p=2.$$
So, we know we only have the following possibilities :
$$x+1=0,\pm1, \pm2^k\Rightarrow x=-1,0,-2,-1\pm2^k.$$
However, we have $x\not=-1, x\not=0, x\not=-2$, because $x$ has to be a square of an integer (and $x\not=0$). So, we have $$x=-1\pm2^k.$$ In the same argument, we have $$x^2=-1\pm2^l.$$ Note that $k,l\ge1\in\mathbb Z.$
Hence, we have
$$(-1\pm2^k)^2=-1\pm2^l\iff 2^{2k}\mp2^k+2=\pm2^l\iff 2^{2k-1}\mp2^{k-1}+1=\pm2^{l^1}.$$
Now, if $k-1\ge1$ and $l-1\ge1$, then we know that the left hand side is odd, and the right hand side is even, which is a contradiction.
So, we have "$k=1$ or $l=1$".
This leads $x=\pm2^k-1=\pm2^1-1\Rightarrow x=1,-3\Rightarrow x=1.$ ($x^2$ has to be a square.) Also, this leads $x^2=\pm2^l-1=\pm2^l-1\Rightarrow x^2=1,-3\Rightarrow x=1.$
So, this case leads $(x,y)=(1,\pm 2).$
(2) The case that $x+1$ and $x^2+1$ are coprime.
In this case, we know any two of $x,x+1,x^2+1$ are coprime. So, this leads that each of $x, x+1,x^2+1$ has to be a square number of an integer. However, it is impossible that $x$ and $x+1$ are both square numbers except $x=0$. However, we suppose that $x\not=0$ at the top. Hence, this case has no solution.
Now we reach a conclusion that the solutions of the given equation is only the followings:
$$(x,y)=(0,0),(1,2),(1,-2).$$


text:
Q: Slit Slider not working Although someone had the same issue I see those solutions don't work for me. This works 100% on my local server and when applied online it shows this. The coding taken from the tutorial for slit slider.
http://www.designelite.co.za/PARTY/index.html
Anyone telling me what the problem could be. If it works 100% on my server shouldn't it work online.
Any help will do.

A: you have permission error on your console Failed to load resource: the server responded with a status of 403 (Forbidden)
grant access rights to the web server account and this should fix it.
as Armen Asriyan said


text:
Q: Missing NamedQueries annotation in WAS Liberty environment I'm using WAS Liberty 8.5.5.5 under Java 7 (tried under Oracle java 7-8 and IBM java 7 as well).
When I create one NamedQuery, the code compiles, deployes, and runs fine.
However, If I try to use the NamedQueries annotation I get the following excpetion:
java.lang.ArrayStoreException: com.sun.proxy.$Proxy29
                  at sun.reflect.annotation.AnnotationParser.parseAnnotationArray(AnnotationParser.java:765)
                  at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:537)
                  at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:355)
                  at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286)
                  at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
                  at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
                  at java.lang.Class.createAnnotationData(Class.java:3521)
                  at java.lang.Class.annotationData(Class.java:3510)
                  at java.lang.Class.getAnnotation(Class.java:3415)

After some investigation, I found the following two bugs:

*

*ArrayStoreException in Jboss: https://issues.jboss.org/browse/JBAS-9392

*ArrayStoreException when annotation declaring class missing: http://bugs.java.com/view_bug.do?bug_id=7183985
It seems that the javax.persistence.NamedQueries inteface is missing in the enviroment (stangely the javax.persinstence.NameQuery is present ...)
I use Eclipse Kepler for development, the deployment is also handled by the IDE.
On more thing; other developers using the same code base can successfully deploy and run the application with the afformentioned settings - so I suspect the deployment might be responsible for this issue.
Is there a way to "tell" the WAS to include the missing class runtime?

A: It took some time, but I found the solution.
We are using Ecliselink as a JPA provider, and load it accordingly:
<classloader commonLibraryRef="EclipseLinkLib" delegation="parentLast"/>

It seems that Eclipselink (version 2.5.2) contains the javax.persistence.NamedQuery interface, but not the javax.persistence.NamedQueries interface - this way WAS does not load the missing interface.
By changing delegation="parentFirst" the app works fine.


text:
Q: How can I delete certain row/rows from sqlite table using Python3? Here is the code I wrote. But when compiling, it says that LIMIT and OFFSET is not defined.
def sql_delete(user_id, task_number):
    cur = connection.cursor()
    cur.execute('DELETE FROM tasks WHERE user_id = (SELECT user_id FROM tasks WHERE user_id = ? LIMIT 1 OFFSET ?)', (user_id, task_number, ))
    connection.commit()

A: UPDATE
Just now I understood what you did want to manage. Just give a try this:
def sql_delete(user_id, task_number):
    cur = connection.cursor()
    cur.execute('DELETE FROM tasks WHERE user_id = (SELECT user_id FROM tasks WHERE user_id = ? LIMIT 1 OFFSET ?)', (user_id, int(task_number)))
    connection.commit()


text:
Q: Get key for a map> how can i get keys for such a map map<string,vector<string>>mymap assuming that mymap["index"]={"val1","val2"}? I have found the solution here for a normal map like map<string,string> but for this i don't know how to do it.

A: You can iterate through all the values in the map (which are pairs) and refer their first and second element to obtain, respectively, the key and the mapped value:
#include <map>
#include <vector>
#include <string>

int main()
{
    std::map<std::string, std::vector<std::string>> m;
    // ...
    for (auto& p : m)
    {
        std::string const& key = p.first;
        // ...

        std::vector<std::string>& value = p.second;
        // ...
    }
}

Of course, you could achieve the same using std::for_each instead:
#include <map>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
    std::map<std::string, std::vector<std::string>> m;
    // ...
    std::for_each(begin(m), end(m), [] (
        std::pair<std::string const, std::vector<std::string>>& p
        //                    ^^^^^
        //                    Mind this: the key is constant. Omitting this would
        //                    cause the creation of a temporary for each pair
        )
    {
        std::string const& key = p.first;
        // ...

        std::vector<std::string>& value = p.second;
        // ...
    });
}

Finally, you may also roll your own manual for loop, although I personally consider this less idiomatic:
#include <map>
#include <vector>
#include <string>

int main()
{
    std::map<std::string, std::vector<std::string>> m;
    // ...
    for (auto i = begin(m); i != end(m); ++i)
    {
        std::string const& key = i->first;
        // ...

        std::vector<std::string>& value = i->second;
        // ...
    }
}

This is how the last example above would look like in C++03, where type deduction through auto is not supported:
#include <map>
#include <vector>
#include <string>

int main()
{
    typedef std::map<std::string, std::vector<std::string>> my_map;
    my_map m;

    // ...
    for (my_map::iterator i = m.begin(); i != m.end(); ++i)
    {
        std::string const& key = i->first;
        // ...

        std::vector<std::string>& value = i->second;
        // ...
    }
}

A: The map holds std::pair<key_type, mapped_type> internally, so iterating over the map gives you access to the keys via it->first, where it is the iterator.
std::map<std::string, std::vector<string>> m;

for (auto it = m.cbegin(), it != m.cend(); ++it)
  std::cout << "key " << it->first << std::endl;

The range based loop version is
for (const auto& stuff : m)
  std::cout << "key " << stuff.first << std::endl;


text:
Q: Hooking Up Unit Tests to Local IIS Web Instance I'm trying to run unit tests for a project which is reliant on the web instance as it uses integrated windows authentication to verify the current user. When I run the tests it doesn't fire up the web instance, which is expected, but I need it to in order for any tests to succeed really.  Anyone have any idea of how to do this?

A: Okay, I got this working in the end.  You have to mock HttpContextBase (which is preferential over HttpContext I hear) and then set up your IPrincipal which is returned from the mock object.  I'll give the full code listing so you get the idea:
[TestInitialize]
public void SetUp()
{
    userRepositoryMock = new Mock<IUserRepository>();
    controller = new AccountController(userRepositoryMock.Object);

    httpContextMock = new Mock<HttpContextBase>();
    IPrincipal fakeUser = new GenericPrincipal(new GenericIdentity("johnsmith@johns4232mith.com", "Forms"), null);
    httpContextMock.Setup(x => x.User).Returns(fakeUser);

    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    var response = new Mock<HttpResponseBase>();
    var session = new Mock<HttpSessionStateBase>();
    var server = new Mock<HttpServerUtilityBase>();
    var identity = new Mock<IIdentity>();

    request.Setup(req => req.ApplicationPath).Returns("~/");
    request.Setup(req => req.AppRelativeCurrentExecutionFilePath).Returns("~/");
    request.Setup(req => req.PathInfo).Returns(string.Empty);
    response.Setup(res => res.ApplyAppPathModifier(It.IsAny<string>()))
        .Returns((string virtualPath) => virtualPath);
    identity.SetupGet(ident => ident.IsAuthenticated).Returns(true);
    context.Setup(ctx => ctx.Request).Returns(request.Object);
    context.Setup(ctx => ctx.Response).Returns(response.Object);
    context.Setup(ctx => ctx.Session).Returns(session.Object);
    context.Setup(ctx => ctx.Server).Returns(server.Object);
    context.Setup(ctx => ctx.User).Returns(fakeUser);

    controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
}


text:
Q: Conflict between Pandas and Unittest? Consider the following block of code (developed inside a Jupyter notebook), for which it is expected that an AssertionError is raised because a UserWarning is not triggered:
%%writefile Game/tests/tests.py
import unittest
import pandas as pd

class TestGame(unittest.TestCase):
    def test_getters(self):
        print('Just before the critical line.')
        with self.assertWarns(UserWarning):
            print('Just testing...')

suite = unittest.TestLoader().loadTestsFromTestCase(TestGame)
unittest.TextTestRunner().run(suite)

For those unfamiliar with jupyter notebooks, the first line simply exports all following lines into the specified file.
Now if I execute the command:
python3 tests.py

from the terminal (I am using Python 3.5.1 on Ubuntu 14.04), I get a Runtime Error - the stack trace follows:
Just before the critical line:
E
======================================================================
ERROR: test_getters (__main__.TestGame)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests.py", line 8, in test_getters
    with self.assertWarns(UserWarning):
  File "/opt/anaconda3/lib/python3.5/unittest/case.py", line 225, in __enter__
    for v in sys.modules.values():
RuntimeError: dictionary changed size during iteration

----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (errors=1)

Obviously the results are not as expected. However, I notice that either of the following options gets the expected results.

*

*Commenting out the first line with %%writefile ... and running the code snippet with the Jupyter notebook (which uses the same python interpreter).

*Commenting out the import pandas as pd line and running from terminal with the previously given command.

Does anyone understand what's going on here?
For reference, the relevant lines in case.py in the unittest module are
for v in sys.modules.values():
    if getattr(v, '__warningregistry__', None):
        v.__warningregistry__ = {}

which would seem to be benign code (which I would also presume is tested enough to say that it's not the source of the problem).

A: This bug has been filed on Python's bug tracker.

The problem is in the iteration over sys.modules in unittest.case._AssertWarnsContext.__enter__() and accessing every module's __warningregistry__ attribute. On this access, the module-like objects may perform arbitrary actions including importing of further modules which extends sys.modules.

sys.modules is a dict mapping module names to loaded modules.
This problem is difficult to reproduce because there's "something platform dependent" about how the test runner orders the tests.


text:
Q: z3 timeout on nonlinear constraints I have a timeout problem when using z3 for nonlinear real arithmetics. The following code is to check if the 4-dimensional hyper-rectangle has a volume greater than 50000 and also satisfies some constraints. But the z3 cannot give an answer within 1 minute. How to make it faster?
a0min = Real('a0min')
a0max = Real('a0max')
a1min = Real('a1min')
a1max = Real('a1max')
a2min = Real('a2min')
a2max = Real('a2max')
a3min = Real('a3min')
a3max = Real('a3max')
volume = Real('volume')

s = Tactic('qfnra-nlsat').solver()

s.add(-a0min * (1.0 - a1max) + a2max * a3max <= -95000.0,
a0min >  0.0,
a0min < a0max,
a0max < 1000000.0,
a1min > 0.0,
a1min < a1max,
a1max < 1.0,
a2min > 1.0,
a2min < a2max,
a2max < 1000.0,
a3min > 1.0,
a3min < a3max,
a3max < 50.0,
(a0max - a0min) * (a1max -  a1min) * (a2max -  a2min) * (a3max - a3min) > 50000.0,
volume == (a0max - a0min) * (a1max -  a1min) * (a2max -  a2min) * (a3max - a3min))
print s.check()

And there is an interesting thing: if replacing some of the ">" and "<" with "<=" and ">=", the z3 solver can return the answer in two seconds. The corresponding code is as follows. Anyone knows why this happens?
a0min = Real('a0min')
a0max = Real('a0max')
a1min = Real('a1min')
a1max = Real('a1max')
a2min = Real('a2min')
a2max = Real('a2max')
a3min = Real('a3min')
a3max = Real('a3max')
volume = Real('volume')

s = Tactic('qfnra-nlsat').solver()

s.add(-a0min * (1.0 - a1max) + a2max * a3max <= -95000.0,
a0min >=  0.0,
a0min <= a0max,
a0max <= 1000000.0,
a1min >= 0.0,
a1min <= a1max,
a1max <= 1.0,
a2min >= 1.0,
a2min <= a2max,
a2max <= 1000.0,
a3min >= 1.0,
a3min <= a3max,
a3max <= 50.0,

(a0max - a0min) * (a1max -  a1min) * (a2max -  a2min) * (a3max - a3min) > 50000.0,
volume == (a0max - a0min) * (a1max -  a1min) * (a2max -  a2min) * (a3max - a3min))
print s.check()

A: In the first case, Z3 got "stuck" computing with real algebraic numbers. If we execute your script with
 valgrind --tool=callgrind python nl.py

Interrupt after several minutes, and run
 kcachegrind

We will see that Z3 is stuck inside algebraic_numbers::isolate_roots.
The current real algebraic number package used by the nlsat solver is very inefficient.
We have a new package for computing with algebraic numbers, but it is not integrated with nlsat yet.
One trick to avoid algebraic number computations is to use only strict inequalities. The equality volume == ... is harmless since it is eliminated during pre-processing time.
If we replace the first constraint with -a0min * (1.0 - a1max) + a2max * a3max < -95000.0, then Z3 also terminates quickly (also available online here).
a0min = Real('a0min')
a0max = Real('a0max')
a1min = Real('a1min')
a1max = Real('a1max')
a2min = Real('a2min')
a2max = Real('a2max')
a3min = Real('a3min')
a3max = Real('a3max')
volume = Real('volume')

s = Tactic('qfnra-nlsat').solver()

s.add(-a0min * (1.0 - a1max) + a2max * a3max < -95000.0,
a0min >  0.0,
a0min < a0max,
a0max < 1000000.0,
a1min > 0.0,
a1min < a1max,
a1max < 1.0,
a2min > 1.0,
a2min < a2max,
a2max < 1000.0,
a3min > 1.0,
a3min < a3max,
a3max < 50.0,
(a0max - a0min) * (a1max -  a1min) * (a2max -  a2min) * (a3max - a3min) > 50000.0,
volume == (a0max - a0min) * (a1max -  a1min) * (a2max -  a2min) * (a3max - a3min))
print s.check()
print s.model()

BTW, when you replace everything with <=, nlsat still has to use real algebraic computations, but the change influences the nlsat search-tree, and it manages to find the solution before it gets stuck in a real algebraic number computation.
Here are the three places where nlsat gets "stuck" in the examples we tried/examined

*

*Real algebraic number computations (like your example). This will be fixed when we replace the current package with the new one.

*Polynomial factorization. The current algorithm implemented in Z3 is very inefficient. This can also be fixed.

*Subresultant computations. This one is tricky since as far as I know Z3 uses a very efficient implementation. The performance is similar to the implementation in state-of-the-art systems like Mathematica. This operation is used when Z3 is backtracking the search. The nice property is that we can prove that Z3 will always terminate using this approach. One alternative is to consider approximate methods that do not guarantee termination but are cheaper. Unfortunately, this is not a minor change like the previous two.