text:
Q: Coordinates in Coq I apologize if this is obviously posted somewhere, but I have been trying Google search and SO search and found nothing on this yet.
Part A.
Is there a standard library for defining coordinates/vectors and points in R^2 and R^3 in Coq? I pretty much want to do standard stuff, like adding vectors, cross products, scaling, etc.
If not, how is this for a start:
Require Import Coq.Reals.Reals.

Inductive Coordinate2 : Type := Point2: R -> R -> Coordinate2.

Definition R2plus (u:Coordinate2) (v:Coordinate2) : Coordinate2 :=
match u, v with
 | (Point2 ux uy),(Point2 vx vy)=>(Point2 ((ux+vx)%R) ((uy+vy)%R))
end.

(* etc. *)

Notation "x + y" := (R2plus x y).

Also, why when I run:
Eval compute in ((2%R) < (3%R))%R.

Do I get
= (2 < 3)%R
: Prop

rather than
 True

or something?
Part B.
Is this even a good idea? I want to build an algorithm which computes some things using real numbers, and prove the algorithm correct in Coq. Is Coq.Reals.Reals the right thing to be using, or is it really too abstract?

A: Instead of defining Coordinate2 you could also use (R * R)%type, list R, or t R 2, where t A n, defined in Vector, is a list of size n.
You might want to give your notations a scope and a delimiting key to avoid clashes with other notations.
Notation "x + y" := (R2plus x y) : r2_scope.
Delimit Scope r2_scope with R2.
Eval compute in ((Point2 0 1) + (Point2 2 3))%R2.

Prop, Set, and Type are sorts, which means something of type Prop might be defined inductively.
For example, for the nats, le is defined as
Inductive le : nat -> nat -> Prop :=
  | le_n : forall n, le n n
  | le_S : forall n m : nat, le n m -> le n (S m).

*

*2 <= 2 is true because it's inhabited by le_n 2

*2 <= 3 is true because it's inhabited by le_S 2 2 (le_n 2)

*2 <= 4 is true because it's inhabited by le_S 2 3 (le_S 2 2 (le_n 2))

*3 <= 2 is false because it's not inhabited

For 2 <= 3 to reduce to True, le would have to be defined like, for example,
Fixpoint le (n m : nat) : Prop :=
  match n with
  | 0 => True
  | S n =>
    match m with
    | 0 => False
    | S m => le n m
    end
  end.

Coq's definition of Rplus and Rlt are actually axioms. To check the definition of something use the Print command.
To answer part B, I guess it depends on how well you understand mathematical analysis and the various ways of defining the reals. If you're more familiar with numerical methods, you might want to use the rationals instead.


text:
Q: Why do the coefficients of cross-sectional fixed effects and time fixed effects become zero? I currently have a panel data set that contains the quarterly increment of loans initiated from more than 300 cities in China over the period from 2011Q1 to 2020Q2. I want to examine the impact of COVID-19 on lending activities. I believe that both time fixed effects and city fixed effects exist—both the F test for poolability and Hausman Test support a fixed-effect model.
I use the panel procedure of SAS to analyze it. I also set a dummy variable, "event", to indicate whether the pandemic has occurred. The dummy variable "event" equals to 1 if the period is 2020Q1 or 2020Q2. Currently, I have not added any interactive terms. If I specify a one-way model using fixone option that only allows cross-section fixed effects, I found that some coefficients of these fixed effects are significant while some are not. The coefficients of the dummy variable "event" and other control variables are also significant. By now, it is acceptable.

However, if I specify a one-way fixed effects model using fixonetime option that only allows time fixed effects, it will be a mess. Although the coefficients of all time fixed effects are significant, the coefficient of the dummy variable "event" becomes zero. I am wondering whether it is caused by perfect multicollinearity. After all, in my setting, event = 1 means the same thing as the fixed effects of 2020Q1 and 2020Q2. My guess is that the impact of the dummy variable "event" has already been absorbed by time fixed effects. Is that right? If it is correct, does it mean that you can never use the time fixed effects and some dummy variables indicating certain event happens at the same time? However, several papers are studying the impact of COVID-19 using them simultaneously in their model. They did not mention any problems of such a setting. So I feel confused.

In a branched setting, instead of using the dummy variable "event", I use two dummy variables, "event_level1" and "event_level2", which equals to 1 if the period is 2020Q1 and 2020Q2 respectively, to visualize the dynamics of COVID-19 impact. The result is getting worse because the coefficients of all fixed effects and interested dummy variables "event_level1" and "event_level2" become zero this time. It looks caused by other reasons instead of multicollinearity this time. Are there any generous and smart friends who know the reason? Thank you so much!

A: Collinearity appears to be the problem.

I currently have a panel data set that contains the quarterly increment of loans initiated from more than 300 cities in China over the period from 2011Q1 to 2020Q2. I want to examine the impact of COVID-19 on lending activities.

SARS-Cov-2 is assumed to affect the lending practices of all cities within China at precisely the same time. Your event dummy 'turns on' in all cities in the first and second quarters of 2020. Note, your event dummy has the same 'within-city' pattern. Your first model should look something like this:
$$
\text{Lending}_{cq} = \beta_{0} + \beta_{1}\text{Event}_{q} + \alpha_{c} + \epsilon_{cq}
$$
where you observe the lending activities in city $c$ across quarters $q$. $\text{Event}_{q}$ is $q$-subscripted. The dummy exhibits no variation across cities. Demeaning your equation (or estimating dummies for all cities) 'sweeps out' $a_c$ (i.e., the 'city' effect). This model is estimable.
However, adding time (quarter) fixed effects introduces collinearity concerns. Suppose you have quarterly data on 300 cities from 2011 onward; I assume your panel ends in the second quarter of 2020. Now say you wish to estimate a two-way fixed effects estimator using the least-squares dummy variables (LSDV) approach; this is algebraically equivalent to estimation in deviations from means. This should result in 300 separate city effects and 42 separate quarter effects. The quarter fixed effects represent the common shocks, absent the pandemic, affecting all cities. By construction, your event dummy is collinear with your last two quarter effects.

My guess is that the impact of the dummy variable "event" has already been absorbed by time fixed effects. Is that right?

Precisely. Again, $\text{Event}_{q}$ is equal to 1 in all cities in the first and second quarter of 2020. If you include a model with quarter fixed effects, then you have a unique 2020-Q1 dummy and a unique 2020-Q2 dummy specific to all cities. In other words, $\text{Event}_{q}$ is the sum of the last two quarter effects. To break the collinearity, SAS dropped your event dummy. In most software packages, the order of your variables matters inside of a regression function call. If you want an estimate for your event dummy, then I recommend dropping the last quarter. In R/Stata, for example, if you specified your event indicator before the city and quarter effects, it will default to removing your last quarter dummy (i.e., 2020-Q2). You could do this manually in SAS to obtain an estimate for your event (i.e., exposure/intervention) dummy.

In a branched setting, instead of using the dummy variable "event", I use two dummy variable, "event_level1" and "event_level2", which equals to 1 if the period is 2020Q1 and 2020Q2 respectively, to visualize the dynamic of COVID-19 impact.

As already shown, you cannot estimate the dynamics of exposure with city and quarter fixed effects. Such a model is inestimable. Your event dummies are perfectly collinear with your last two quarter effects. Thus, a two-way fixed effects estimator will fail in this setting. Your event indicators must vary over time and across units to use this estimator.
In order to estimate city and quarter fixed effects, you require either a 'staggered' exposure (i.e., different cities become exposed at different times) or a setting where a subset of cities were never treated. Because SARS-Cov-2 is a population-level exposure affecting all cities/provinces in precisely the same time periods, then quarter fixed effects will completely absorb your event dummy.
You can safely estimate your model using one-way city-level fixed effects or pooled ordinary least squares.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why isn't this list populating with data? I am using angular and the data is coming back from my api call. The problem is my list is not populating.
first partial:

    <select ng-model="customerKey" ng-options="customer.Key as customer.Value for customer in customers"></select>

second partial:

                <input type="radio" id="{{customerOption.Value}}" name="customer" ng-change="getCustomers(customerType)" ng-model="customerType" ng-value="customerOption.Key" ng-checked="customerOption.Checked" />{{customerOption.Value}}

Controller:
var customer = angular.module('customer', []);

customer.controller('CustomerController', [
    "$scope", "customerService",
    function($scope, customerService) {
        $scope.customerOptions = CustomerOptions;

        $scope.getCustomers = function(customerType) {
            $scope.showContent = false;
            customerService.get(customerType).then(function (data) {
                $scope.customers = data;
            });
        };

        $scope.init = function() {
            $scope.getCustomers("1");
        }
    }
]);

service:
app.service('customerService', [
"$http", function ($http) {
    this.get = function(customerType) {
        var customers;
        if (customerType == "1") {
            getProduction().then(function(result) { customers = result.data; });
        } else if (customerType == "2") {
            getTest().then(function(result) { customers = result.data; });
        } else {
            getAll().then(function(result) { customers = result.data; });
        }
        return customers;
    };

    var getTest = function () {
        return $http({
            method: "GET",
            url: "api/Customer/GetTest",
        })
         .success(function (data) {
             return data;
         });
    };

    var getProduction = function () {
        return $http({
            method: "GET",
            url: "api/Customer/GetProduction",
        })
         .success(function (data) {
             return data;
         });
    };

    var getAll = function () {
        return $http({
            method: "GET",
            url: "api/Customer/GetAll",
        })
         .success(function (data) {
             return data;
         });
    };
    }
]);

If you click on any of the radio buttons, they return the appropriate list to the service function; however, I cannot get the select list to populate with that data

A: The problem is that the service is returning customers object instead of promise, which the controller method is looking for.
It should work if you return the promise from the service and leave the success/error handling to the controller.
app.service('customerService', [
  "$http", function ($http) {
   this.get = function(customerType) {
    var customers;
    if (customerType == "1") {
        return getProduction();
    } else if (customerType == "2") {
       return getTest();
    } else {
       return getAll();
    }
};

Controller:
  $scope.getCustomers = function(customerType) {
        $scope.showContent = false;
        customerService.get(customerType).then(function (results) {
            $scope.customers = results.data;
        });
    };

A: The then handlers in your customerService get() method are assigning the results of the HTTP call to a local customers variable, but this accomplishes nothing. By the time that happens, customers has already been returned to the caller as undefined, and you are most likely getting an error when you call then() on that value.
You need to return a promise from get() and the then() handlers inside get() need to have return statements in them:
this.get = function(customerType) {
    if (customerType == "1") {
        return getProduction().then(function(result) { return result.data; });
    } else if (customerType == "2") {
        return getTest().then(function(result) { return result.data; });
    } else {
        return getAll().then(function(result) { return result.data; });
    }
};

There is quite a bit of duplication here, and this can be consolidated:
this.get = function(customerType) {
    var customerPromise =
        (customerType === "1") ? getProduction()
        : (customerType === "2") ? getTest() : getAll();

    return customerPromise.then(function (result) { return result.data; });
};


text:
Q: MySQL Query Error with Node Js I am using MySQL with Node JS and I am detecting whether an existing user is already in the database. This code below is what I have been using:
var username = "RandomUsername";
var email = "RandomEmail@gmail.com";
var sql = "SELECT * FROM users WHERE user_name = " + username + " OR user_email = " + email;
connection.query(sql, function(err, rows, fields) {
          if (err) throw err;
          if (rows.length !== 0) {
            errors.push("Sorry, that email or username already being used.");
}

This is the error message I am getting:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'cameroncjones4'' OR user_email = ''cameroncjones4''' at line 1
at Query.Sequence._packetToError (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/sequences/Sequence.js:48:14)
at Query.ErrorPacket (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/sequences/Query.js:83:18)
at Protocol._parsePacket (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/Protocol.js:271:23)
at Parser.write (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/Parser.js:77:12)
at Protocol.write (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/Protocol.js:39:16)
at Socket.<anonymous> (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/Connection.js:96:28)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
--------------------
at Protocol._enqueue (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Connection.query (/Users/CameronJones/Desktop/NodeJS/LoginSystem/node_modules/mysql/lib/Connection.js:201:25)
at IncomingMessage.<anonymous> (/Users/CameronJones/Desktop/NodeJS/LoginSystem/app.js:86:20)
at IncomingMessage.emit (events.js:107:17)
at IncomingMessage.Readable.read (_stream_readable.js:373:10)
at flow (_stream_readable.js:750:26)
at resume_ (_stream_readable.js:730:3)
at _stream_readable.js:717:7
at process._tickCallback (node.js:355:11)

Help with solving this problem appreciated.

A: You need to add ' and ; to your SQL query.
Try this:
var username = "RandomUsername";
var email = "RandomEmail@gmail.com";
var sql = "SELECT * FROM users WHERE user_name = '" + username + "' OR user_email = '" + email + "';";

And don't forget the ; at the end of each query.
EDITED:
I create a database in order to reproduce your error and your error is definitely the quotes '.
Try copy/paste my code into your code and let me know the result of it. Off course you will need a connection object but I think you are already using one.
var username = "RandomUsername";
var email = "RandomEmail@gmail.com";
var sql = "SELECT * FROM users WHERE user_name = '" + username + "' OR user_email = '" + email+ "'";

connection.connect();

connection.query(sql, function(err, rows, fields) {
    if (err) throw err;
    if (rows.length !== 0) {
      console.log(rows);
      connection.end();
    }else{
      console.log('Nothing match');
    }
});

My guess is when you try to put the single quotes you put double single quotes because your editor (atom? sublimeText?).


text:
Q: extconf.rb how to define the sources files to use I have a little projet of a ruby extension which was organized like this :
./
  Rakefile
  ext/
    mymodule/
      extconf.rb
      mymodule.rb
      mymodule.cpp
      source1.h
      source1.cpp
      source2.h
      source2.cpp

Everything worked but I needed to put some of the source files in a directory (I create/modify/test all those source files in a git repos in order to just have to update this directory when my C++ code is tested). So the new organization looks like this :
./
  Rakefile
  ext/
    mymodule/
      extconf.rb
      mymodule.rb
      mymodule.cpp
      somesourcesfiles/
          source1.h
          source1.cpp
          source2.h
          source2.cpp

My problem now is how to specify to extconf.rb where to find the source files (extconf.rb use source files in current directory by default).
I have tested this in the extconf.rb whitout success:
myfiles = %w{somesourcefiles/source1 somesourcefiles/source2 mymodule}
$srcs = myfiles.map{|i| i + ".cpp"}

I have had an error message saying that the linker couldn't find some ".o" files so I added this:
myfiles = %w{somesourcefiles/source1 somesourcefiles/source2 mymodule}
$srcs = myfiles.map{|i| i + ".cpp"}
$objs = myfiles.map{|i| i + ".o"}

But this didn't work.

A: See mkmf ignores files in sub-folders when it compiles the C extension
$INCFLAGS << " -I$(srcdir)/somesourcesfiles"
$VPATH << "$(srcdir)/somesourcesfiles"


text:
Q: Robotium fails in the second test I've created simple test in my android program using robotium 3.5.1 with the following code:
protected void setUp() throws Exception {
    solo = new Solo(getInstrumentation(), getActivity());
}

protected void tearDown() throws Exception {
    solo.finishOpenedActivities();
}

public void testAddTabs() throws Exception {

    addTab("TAB1");
    addPreset("TAB1");
    addTab("TAB2");
    addPreset("TAB2");

}

public void addTab(String tabName) throws Exception {

    solo.assertCurrentActivity("Checking current Activity",
            MainActivity.class);
    Log.d("MyTag", solo.getCurrentActivity().getLocalClassName() );
    solo.clickOnView(solo.getView(com.sm.scam.R.id.menu_new_tab));
    solo.enterText(0, tabName);
    solo.clickOnText("OK");

}

public void addPreset(String name) throws Exception {
    Log.d("MyTag", solo.getCurrentActivity().getLocalClassName() );
    solo.goBackToActivity("MainActivity");
    Log.d("MyTag", solo.getCurrentActivity().getLocalClassName() );
    solo.clickOnText(name);
    solo.clickOnText("New Preset");
    Log.d("MyTag", solo.getCurrentActivity().getLocalClassName() );
    solo.assertCurrentActivity("Checking current Activity",
            PresetActivity.class);

    String presetName = "Moti" + 1;
    solo.enterText(0, presetName);
    solo.pressSpinnerItem(0, 1);
    solo.clickOnText("Darkened");
    solo.clickOnText("GPS Tag");
    solo.clickOnView(solo.getView(com.sm.scam.R.id.menu_save_preset));
}

it simply add new tab, and in the tab pressing on button, changes edittext,spinner and 2 switch buttons and save.
everything is OK in the first tab but in the second tab the following code:
solo.clickOnText("New Preset");

just don't do nothing!
when clicking this button nothing happens and it should forward to PresetActivity as it forwarding correctly in the first tab.
the error code:
junit.framework.ComparisonFailure: Checking current Activity expected:<...Preset...>            but was:<...Main...>
at com.jayway.android.robotium.solo.Asserter.assertCurrentActivity(Asserter.java:57)
at com.jayway.android.robotium.solo.Solo.assertCurrentActivity(Solo.java:570)
at com.sm.scam.test.ScamTest.addPreset(ScamTest.java:55)
at com.sm.scam.test.ScamTest.testAddTabs(ScamTest.java:32)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at                                                                                android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java   :186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:537)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1574)

I've also tried to force it by calling to:
solo.goBackToActivity("MainActivity");

but still nothing.
would appreciate if someone help me. thanks

A: TabHost? if so that is probably your problem. TabHosts involve having multiple activities open and this really confuses robotium. That is because robotium only knows about the last activity that it saw, this means in a scenario where multiple activities are open then the one it sees last might not be the one you are expecting it to be.
You can see this is happening because it isn't failing to click on anything it is in fact just on the wrong activity and thats the assertion that fails.

A: This is because sometimes assert executes before your activity was loaded. So try to use before assertActivity something like:
solo.waitForActivity(getCurrentActivity().getClass().getSimpleName());
solo.assertCurrentActivity(PresetActivity.class);


text:
Q: Grabbing a part of the List by start and end indices Is this possible?
For example, if I have
List<Item> myList = new List<Item>;

//added 100 of Items to myList

//then I want to grab items at indices 50 - 60

List<Item> myNewList = myList.?

How do I do that w/o looping through myList?
Thank you.

A: var myNewList  = myList.Skip(50).Take(10);

A: There is a method that retrieves these items, List.GetRange.
http://msdn.microsoft.com/en-us/library/21k0e39c.aspx
List<Item> myList = new List<Item>;
myList.GetRange(50, 10); // Retrieves 10 items starting with index #50

A: http://msdn.microsoft.com/en-us/library/bb503062.aspx
http://msdn.microsoft.com/en-us/library/bb357513.aspx
myList.Skip(50).Take(10)

A: What about:
        List<string> myList = new List<string>();

        //added 100 of Items to myList
        for (int i=0; i<100; ++i)
        {
            myList.Add("blablabla");
        }

        //then I want to grab items at indices 50 - 60
        // Note: 50 - 60 inclusivly are actually 11 items
        List<string> myNewList = myList.GetRange(50, 11);


text:
Q: JTA Transaction with weblogic doesn't work as expected My application has locked the database table because JTA haven`t complete your operation with the commands of rollback or commit.
The application is running over weblogic 10.3 in cluster with two managed servers.
The method with access on database is syncronized where the first part inside of method execute a query and the second one call another method to execute the merge. This method has the annotation @Transaction(read-only=false).
The JTA transaction is executed by weblogic.
My question is, based on scenario described, what could be generating a lock in database?

A: Looks to me a threading issue, where lock is not getting acquired.

The method with access on database is syncronized where the first part
  inside of method execute a query and the second one call another
  method to execute the merge.

Check if two methods require two different locks, if yes then it can lead to deadlock, if thread in method1 keeps on waiting for lock to access method2.


text:
Q: How to Join Conditionally to Different Tables I'm trying to play around with tableau server's data and I'm trying to join the tasks table with datasources table and workbooks table. The tasks table has two important fields do this:

*

*Obj_id and

*Obj_type.

If Obj_type = "Datasource" I'd join on datasources.id = tasks.obj_id. If Obj_type = "Workbook", I'd join on workbook.id = tasks.obj_id.
I tried something like this but I can't get it to work, what is the correct way to write this without retrieving nulls in my results.
select * from datasources d
left join workbooks w on d.parent_workbook_id = w.id
left join tasks t on (if t.obj_type = "Datasource" then d.id else w.id end) = t.obj_id

Sample expected output: Basically, tasks fields will always be populated because if the datasource resides in a workbook, the task table already knows that from obj_id and will join to the workbooks_id. If datasource is published separately on server, the tasks table will join to the datasources table. So there will always be a match.

d.Name
w.Name
t.obj_type
other tasks fields

SampleData0
Null
Datasource
other tasks values

Sampledata1
Wkbk1
Workbook
other tasks values

A: I think you want something like this:
select *
from tasks t left join
     datasources d
     on t.obj_id = d.id and
        t.obj_type = 'Datasource' left join
     workbooks w
     on t.obj_id = w.id and
        t.obj_type = 'Workbook';

This is based on your description.  Your code has other columns.


text:
Q: Why is there a continous increase in cycle time when using GEKKO with linux APM solving server? I am using GEKKO to study the effect of MPC and MHE on building energy use. To get a performance increase i now switched to a dedicated solving server by setting  m.GEKKO(remote=True, server='http://10.0.0.10'). This server is a freshly installed Ubuntu 20.04.1 machine hosting just the linux APmonitor server. Everything works fine so far except that my control and also estimation cycle times increase linearly with every additional solve for the remote solving option. I use my building model with IMODE=6 for MPC and IMODE=5 for MHE and both show the same behaviour.
In the following figure you can see the cycle times and solve times for local and remote solve. These tests were conducted with the IPOPT MA57 Solver, but others show the same behavior. My program does not change except for switching from remote=False to my solving server remote=True, server='http://10.0.0.10'.

In addition, I have added the timing diagnosis output of the solver after a few steps (left) and after a few hundred steps (right). It clearly shows a much higher system time but very similar solving time but I could not find the culprit here either. Except for this test I have always set DIAGLEVEL=0 and m.solve(disp=False) to reduce the console output.

However, re-initializing the GEKKO model and starting again immediately drops the cycle times. This shows that it is not a problem with the server's compute capacity reducing over time.  For me this looks like some file the process reads and/or writes bloats with the number of iterations but I could not find anything significant in the current model directory. Maybe someone knows the problem and can help me with this one.
Edit 1:
Trying the example script provided by John Hedengren in his answer showed a different result for me. The following picture again shows the same linearly increasing behavior. I ran this test with a different physical machine, also using a different physical network adapter at the solving server. Previously i even switched the physical machine of the solving server. Tested with Python Versions 2.7.16, 3.7.7 and 3.8.5.

For me this leads to the conclusion that this situation is not caused by my MPC application. It also doesn't seem to be related to a hardware problem at the client, the network , or the server. IMHO it looks like a server software problem.
A few specs here:

*

*Ubuntu 20.04.1

*Apache 2.4.41

*PHP 7.4.3

*APMonitor, Version 0.9.2

Edit 2:
After using John Hedengrens sample problem to test multiple solving servers i came to the conclusion that the behavior of rising cycle times is not unique to my Ubuntu linux setup. Here a few examples:

*

*Custom APMonitor server on CentOS7 with MA97Solver (LAN)

*APMonitor server on Windows 10 (LAN)

*Official APMonitor solving server (Web)

to make it make it more obvious i removed the oulierers in the next
picture
In my case a cycle time increase of about 1 second per 1000 cycles (for this sample problem) happens regardless of the used remote solver (local solve is always fine). The effect of this steady cycle time increase is not as prominent if the solve/cycle times are longer anyway or the number of cycles is not high enough. For my application however this is very problematic as i  have to run about 40k cycles as fast as possible.
Edit 3:
Implementing the changes to gekko.py and apm_line.php John Hedengren suggested in his answer fixed the problem partly but not entirely. There is still an increase in cycle time. Once again, looking closer and longer reveals the issue. The following image shows the output of the usual test script, this time for the updated versions of gekko.py and apm_line.php a linux APM server (Windows shows same behavior) and 5k steps. Looking very closely you can even see this effect in the diagram (1k runs) John posted in his answer edit.

A: Here is an example script that solves for 100 cycles with remote (public server) or local solve. The remote (public server) solve is on a Linux server with solver IPOPT. The local solve is on Windows 10 using apm.exe. Both are solved with Python 3.7.

import numpy as np
from gekko import GEKKO
import matplotlib.pyplot as plt
import time

for ri,r in enumerate([True,False]):
    m = GEKKO(remote=r)
    m.time = np.linspace(0,10,21)
    mass = 500; b = m.Param(value=50); K = m.Param(value=0.8)
    p = m.MV(value=0, lb=0, ub=100); v = m.CV(value=0)
    m.Equation(mass*v.dt() == -v*b + K*b*p)
    m.options.IMODE = 6 #control
    p.STATUS = 1; p.DCOST = 0.1; p.DMAX = 20
    v.STATUS = 1; m.options.CV_TYPE = 2
    v.SP = 40; v.TR_INIT = 1; v.TAU = 5

    s=time.time(); ct=[]; st=[] # cycle time, solve time
    for i in range(100):
        m.solve(disp=False)
        e=time.time(); ct.append(e-s); s=e
        st.append(m.options.SOLVETIME)

    plt.subplot(2,1,1+ri)
    plt.plot(ct,label='clock time')
    plt.plot(st,label='solve time')
    plt.legend()
    if r:
        plt.title('Remote Solve')
    else:
        plt.title('Local Solve')
        plt.xlabel('cycle');
    plt.ylabel('time (sec)')
plt.show()

There is no linear increase in solve time with this example. There may be something else happening in the solve loop of your application that is giving a linear increase in time for remote=True. It may also be something with the network.
Information from gekko.py
The gekko library has different methods for solving remotely versus locally. When solving remotely, the files are created and sent to the server. Results are then generated and passed back to the local temporary directory m.path or m._path that can be viewed with m.open_folder(). One thing to try is to time the steps in the gekko.py file. Another thing to observe is the size of the files that are passed to the server.
def send_if_exists(extension):
    path = os.path.join(self._path,self._model_name + '.' + extension)
    if os.path.isfile(path):
        with open(path) as f:
            file = f.read()
        cmd(self._server, self._model_name, extension+' '+file)

#clear apm and csv files already on the server
cmd(self._server,self._model_name,'clear apm')
cmd(self._server,self._model_name,'clear csv')

#send model file
with open(os.path.join(self._path,self._model_name + '.apm')) as f:
    model = f.read()
cmd(self._server, self._model_name, ' '+model)
#send csv file
send_if_exists('csv')
#send info file
send_if_exists('info')
#send dbs file
with open(os.path.join(self._path,'measurements.dbs')) as f:
    dbs = f.read()
cmd(self._server, self._model_name, 'option '+dbs)
#solver options
if self.solver_options:
    opt_file=self._write_solver_options()
    cmd(self._server,self._model_name, ' '+opt_file)

#extra files (eg solver.opt, cspline.data)
for f_name in self._extra_files:
    with open(os.path.join(self._path,f_name)) as f:
        extra_file_data = f.read() #read data
        extra_file_data = 'File ' + f_name + '\n' + extra_file_data + 'End File \n'
    cmd(self._server,self._model_name, ' '+extra_file_data)

#solve remotely
response = cmd(self._server, self._model_name, 'solve', disp, debug)

#print APM error message and die
if (debug >= 1) and ('@error' in response):
    raise Exception(response)

#load results
def byte2str(byte):
    if type(byte) is bytes:
        return byte.decode().replace('\r','')
    else:
        return byte

try:
    results = byte2str(get_file(self._server,self._model_name,'results.json'))
    f = open(os.path.join(self._path,'results.json'), 'w')
    f.write(str(results))
    f.close()
    options = byte2str(get_file(self._server,self._model_name,'options.json'))
    f = open(os.path.join(self._path,'options.json'), 'w')
    f.write(str(options))
    f.close()
    if self.options.CSV_WRITE >= 1:
        results = byte2str(get_file(self._server,self._model_name,'results.csv'))
        with open(os.path.join(self._path,'results.csv'), 'w') as f:
            f.write(str(results))
        if self.options.CSV_WRITE >1:
            results_all = byte2str(get_file(self._server,self._model_name,'results_all.csv'))
            with open(os.path.join(self._path,'results_all.csv'), 'w') as f:
                f.write(str(results_all))
except:
    raise ImportError('No solution or server unreachable.\n'+\
                      '  Show errors with m.solve(disp=True).\n'+\
                      '  Try local solve with m=GEKKO(remote=False).')

If a variable such as response is growing in size then some of the string operations may be taking longer.
Edit: Tried the script with 1000 cycles and there is an increase in cycle time for the remote server.

I checked the server directory and the problem is with the file overrides.dbs that grows each cycle when using remote=True.
-rw-r--r--. 1 apache apache  76911 Jan 26 07:43 overrides.dbs
-rw-r--r--. 1 apache apache 119305 Jan 26 07:43 overrides.dbs
-rw-r--r--. 1 apache apache 219745 Jan 26 07:44 overrides.dbs

As this file grows, it takes longer to interpret the longer list of options. To resolve this problem, I made changes to Gekko gekko.py and to the server file apm_line.php.
Changes to gekko.py to appear in Gekko next release beyond 0.2.8) or in GitHub:
            cmd(self._server,self._model_name,'clear meas')

            cmd(self._server, self._model_name, 'meas '+dbs)

Changes to apm_line.php also found on GitHub.
        } elseif (strtolower(substr($add, 0, 5))=="meas ") {
                $option = trim(substr($add,5)); // starting at 5th position - extract option
                $fn_opt = $d . "/measurements.dbs";
                if ( !file_exists($fn_opt)) {
                    $meas = fopen ($fn_opt, 'w');
                } else {
                    $meas = fopen ($fn_opt, 'a');
                }
                fwrite ($meas, "\n".$option);
                fclose($meas);
                echo "Successfully added meas: " . $meas;
                fclose($handle);

        } elseif  (strtolower($add)=="clear meas") {
                // clear file contents by opening in write mode
                $fn_csv = $d . "/measurements.dbs";
                $meas_file = fopen ($fn_csv, 'w');
                // write a space to the file to clear contents
                fwrite ($meas_file, " ");
                fclose ($meas_file);

                //$clear = "! Cleared measurements.dbs file contents";
                //fwrite ($handle, "\n".$clear);
                fclose($handle);
                echo "Cleared measurements.dbs file";

This gives the improved results with no increase in time.

Thanks for your help in finding this bug!


text:
Q: Lock cells depending on value in other cell I would like to lock a cell depending on the value in another cell.
Example:
Lock A2 if B2 has any value with a minimum of 10 letters in it and unlock A2 if B2 has a value with more than 10 letters.
I would like to have this in column A and B, so the VBA-macro will look at the value in column B and lock/unlock the value in column A accordingly.

A: Set all of your sheet to unlock state first.
Then use to lock a specific cell according to a value in another cell
If Worksheets("Sheet1").Range("B1").Value = <something> then: _
Worksheets("Sheet1").Range("A1").Locked = True

Put that into a loop and you have what you want.
In the end to make the lock effective and still allow your VBA code to modify the cells is:
Worksheets("Sheet1").Protect UserInterfaceOnly:=True

It will lock only the cells you marked above with lock and leave all others unlocked.


text:
Q: How to get rss img src? I want to get [img src] value from xml of a wordpress site. This code comes with all the values of the tag.
Xml Adress : https://yususm.com/feed/
XmlDocument doc = new XmlDocument();
            doc.Load("http://yususm.com/feed/");

            var nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");

            foreach (XmlNode node in doc.SelectNodes(@"//content:encoded", nsmgr))

            {
                    description = node.InnerText;
                    richTextBox1.Text=description;
            }

output :

I just want the src value. how can I do that ?

A: Since you are trying to read HTML, you need to use a tool that is specifically designed to do that. I'd suggest HtmlAgilityPack.
Try this code:
var xdoc = XDocument.Load(@"http://yususm.com/feed/");
var nsContent = XNamespace.Get("http://purl.org/rss/1.0/modules/content/");

string[] srcs =
    xdoc
        .Root
        .Descendants(nsContent + "encoded")
        .SelectMany(x =>
        {
            var hdoc = new HtmlAgilityPack.HtmlDocument();
            hdoc.LoadHtml(x.Value);
            return
                hdoc
                    .DocumentNode
                    .SelectNodes("//img[@src]")
                    .Select(n => n.Attributes["src"].Value);
        })
        .ToArray();

I get the following string[]:
https://i.pinimg.com/originals/90/c4/dc/90c4dce57531675d187bab111c2b67ba.jpg
https://i.pinimg.com/originals/8e/4d/cd/8e4dcd5a78c8e96f05e31f2c13886f50.jpg
https://i.pinimg.com/originals/5d/4f/65/5d4f656450e2307bc413d0a6b12a8539.jpg
https://i.pinimg.com/originals/78/29/80/782980fe5802844669412bfd4b91e523.jpg


text:
Q: Attributing a version number to a child theme's main stylesheet In header.php, I like to attribute a version number to the stylesheet so that the browser gets forced to refresh it. But when working with a child theme, its stylesheet is not explicitely called, rather WordPress automatically seeks it. So how or where to attribute a version number to the child theme's stylesheet?

A: You can update the version in the child themes style sheet itself...
/*
 Theme Name:   Twenty Fourteen Child
 Theme URI:    http://example.com/twenty-fourteen-child/
 Description:  Twenty Fourteen Child Theme
 Author:       John Doe
 Author URI:   http://example.com
 Template:     twentyfourteen
 Version:      1.1.2 <---- Update here
*/

A: The current top answer is theme dependent, as it requires the theme developer to have made that child theme version number into a variable and then appended it to the child style.css when enqueuing it. I've seen this on some themes, but not many. The following works on any theme that registers the child styles in functions.php - won't work with the old @import rule, which I haven't seen much any more.
In functions.php of the child theme, you should have something similar to this:
// enqueue the child theme stylesheet

function wp_schools_enqueue_scripts() {
  wp_register_style( 'childstyle', get_stylesheet_directory_uri() . '/style.css'  );
  wp_enqueue_style( 'childstyle' );
}
add_action( 'wp_enqueue_scripts', 'wp_schools_enqueue_scripts', 11);

If you change it to the following, it will append a timestamp as a version number each time the file is saved, allowing each change of the stylesheet to bust through local cache:
 // enqueue the child theme stylesheet

 function wp_schools_enqueue_scripts() {
   wp_register_style(
     'childstyle',
     get_stylesheet_directory_uri() . '/style.css',
     array(),
     filemtime( get_stylesheet_directory() . '/style.css' )
   );
   wp_enqueue_style( 'childstyle' );
 }
 add_action( 'wp_enqueue_scripts', 'wp_schools_enqueue_scripts', 11);

Hope this helps someone. I use this on every site that I actively manage.

A: I think the best way to do this is to leave the child theme stylesheet (style.css) empty with only the necessary comments (like theme name, description etc, so can wordpress recognize your theme) and then make another css file in your-theme-name-folder/css/main.css
After that on function.php you can have a new "version" every time you change your file :
function my_scripts_and_styles(){

$cache_buster = date("YmdHi", filemtime( get_stylesheet_directory() . '/css/main.css'));
wp_enqueue_style( 'main', get_stylesheet_directory_uri() . '/css/main.css', array(), $cache_buster, 'all' );

}

add_action( 'wp_enqueue_scripts', 'my_scripts_and_styles', 1);

The logic:
Every time you save the file the modified time of the file is being changed. The new time is being passed to date function to convert the time(filemtime returns an integer representing the time) to date format to make it a string in the format you desire. In our example the time is being formatted with accuracy of minutes. You can change it to track even second ie "YmdHis".After that the new modified time of the file is being passed as a new version to wp_enqueue_style.
Reference :
http://www.php.net/filemtime
http://php.net/manual/en/function.date.php

A: What you need to do is de-register the main style by handle and then re-register with your version number. In this case the handle is style-css.
You can determine the handle that you need to use by looking at the rendered stylesheet link:
<link rel='stylesheet' id='style-css-css'  href='http://site-url/wp-content/themes/child-theme/style.css?ver=4.6.1' type='text/css' media='all' />

Here the id is style-css-css which means our handle is style-css
Put this in the function.php of your child-theme:
function wpse_145141_change_style_version(){
    // First de-register the main stylesheet
    wp_deregister_style( 'style-css' );
    // Then add it again, using your custom version number
    wp_register_style( 'style-css', get_stylesheet_uri(), array(), "VERSION_NUMBER" );
    //finally enqueue it again
    wp_enqueue_style( 'style-css');
}

add_action( 'wp_enqueue_scripts', 'wpse_145141_change_style_version');

A: Instead of using the default style.css I typically use wp_enqueue_style in the child theme's functions.php or another included php file. So, you'd still have the style.css in the child theme with all the child theme details but then you can have a separate css file in the child theme for the actual child theme styling (I usually put this in an assets/css directory within the child theme). This would also allow you to set the CSS version with the 4th parameter. For example:
function theme_name_child_scripts() {
    wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/assets/css/child-style.css', array(), '1.0.0', 'screen');
}

add_action( 'wp_enqueue_scripts', 'theme_name_child_scripts' );

You can add a priority to the action if it's not loading in the correct order or work with the dependency parameter in wp_enqueue_style above:
add_action( 'wp_enqueue_scripts', 'theme_name_child_scripts', 20 );

A: Use filemtime to version by file change. Deregister and enque style.

*

*Look in the source (ctrl + U) and find child's css id without "-css". Here it's voyager-default

<link rel='stylesheet' id='voyager-default-css'  href='/wp-content/themes/voyager-child-theme/style.css?1606484598' type='text/css' media='all' />

*Use this code (source) but replace 'style' by the found string (here 'voyager-default')

Child theme's functions.php
function add_timestamp_to_childtheme_stylesheet() {
    wp_dequeue_style( 'style' );
    wp_deregister_style( 'style' );
    wp_enqueue_style('style', get_stylesheet_uri().'?'.filemtime(get_stylesheet_directory().'/style.css'), array(), null);
}
add_action( 'wp_print_styles', 'add_timestamp_to_childtheme_stylesheet' );

A: I believe that if you use the Wordpress theme editor to edit your child theme's stylesheet that it automatically appends a new version number each time you save the file.


text:
Q: How do i move partial changes (hunks) between commits? if i have two commits with a distance of many commits between them, with many files committed in both of them, how is it best to move a hunk from one to the other, for example:
in commit 100:
i have many files changes and many changes in a file "aa.txt" and also this one:

- aaaa
- bbbb
+ cccc

10 commits later i have another commit changing a lot of files and also "aa.txt":

+dddd

I want to move the line change -aaaa from the former to the later.
Is there any CLI/UI tool that helps you to easily do it? (i obviously have no problem with history rewriting)

A: It's possible that an interactive rebase would work.  But a lot of factors could complicate this.  So you've described this much:
x -- x -- A -- B -- C -- D -- x -- x <--(master)

Some line was changed in A, and therefore also is different in B, C, D, etc.  But you want a new history where it isn't changed until D.  So you could say
git rebase --interactive A^ master

(where A is the SHA ID for the commit that previously had the change, and note the ^ that goes at the end of said ID).  In the text editor that comes up, you'll see a "todo" list.  The first line says to pick commit A; change that to edit.  Then find the line for D (which in this example is 3 commits later, but in your stated example might be 10 commits later).  Mark it, as well, for edit.
The rebase will start, but after tentatively re-applying A it will pause so you can edit the commit.
Now, if reversing the change in question isn't something you can easily do by hand / from memory, then you can unstage the changes to that file
git reset HEAD^ -- aa.txt

And then stage them again in "patch mode".
git add --patch -- aa.txt

You'll be prompted how to handle each change hunk.  If the change you want to remove appears in the same hunk as other changes, you can answer the prompt with e and edit the change hunk (and then replace the - that's before the line you no longer want to delete with a ).
Now get your (staged) edits into the commit
git commit --amend

The change you reverted from the index is still in the work tree; get it out of the way, and tell rebase to get back to work.
git stash
git rebase --continue

As rebase continues working toward commit D, intervening commits could get conflicts (if they edited aa.txt too close to the change you reverted).  These conflicts should be easy to resolve.  (The HEAD side of the conflict will include the line you no longer deleted; other than that line, you likely want the "other" side of the conflict.)
Commit D might come up as a conflict, too.  If so your job is easy: just resolve that one by keeping the "other" side of the conflict (including removal of the line in question, since this is where you finally want to do this).  Then when separately prompted to edit D (because you marked it edit in the TODO list) you can just immediately tell rebase to --continue.
If D doesn't conflict, no big deal.  You'll be prompted to edit it.  Pop the stash you created earlier to re-apply the change you deferred from the A commit; add; commit --amend
Now the problems with this approach:  If there are multiple refs that can reach A, this only updates the one (master in the above example).  So for example
x -- A -- B -- C -- D -- x <--(master)
           \
            x -- x <--(branch)

In this case, branch still sees the old history.  You end up with
x -- A' -- B' -- C' -- D' -- x <--(master)
 \
  A -- B -- x -- x <--(branch)

You could address this by doing something like
rebase --onto B' B branch

This will get old fast if there are a lot of branches to deal with.
Another problem would be if the rebase will encounter merge commits.  To some extent you can use --preserve-merges to mitigate this, but it will still cause problems (possibly silently corrupting history) if the merges are "evil" (i.e. could be resolved automatically using the default merge strategy, but were edited in some way).  In that case, the closest thing you could do would be to rebase in segments and reproduce the merges carefully at each step of the way.

A: Export your changes with the git format-patch
than edit the desired patch and apply it using the apply or am
$ git format-patch HEAD~10
$ git am ...

If you want to create a single file you can use the --stdout and print it to a file:
$ git format-patch master --stdout > changes.patch


text:
Q: Adding Existing Device Definitions To Android Studio AVD Manager Sorry for the newbie question but I just downloaded and installed Android Studio in an effort to get into Android development.  I've looked around and can't seem to find any information on how to add existing device definitions to the emulator/AVD Manager.  Aren't there just a bunch of device definitions that the manufacturers provide that can be loaded into the IDE via the AVD Manager.  It seems like that would be the logical way to do this.  It seems like the only thing you can do is create a new device based on existing device definitions.  Is it possible to add device definitions?  How is this done?

A: You are free to add your own device definitions to the AVD - the definitions for Nexus devices (and some others) are already provided.
Launch the AVD, switch to the Device Definitions tab, and click the Create Device... button (see screenshot below).
Now fill in the values based on the device you are trying to simulate (lookup the device specs here if needed).
Once you've created a definition, select it from the list and then click the Create AVD... button. Here you can choose the Android version and CPU type (ARM/Intel), and various other emulator specific settings.


text:
Q: PhpMyAdmin shows warning: PHP MySQL library version 5.0.51a differs from your MySQL server version 5.5.24 Installed Mysql on Ubuntu 12.04 Server via

apt-get install mysql-server

from default sources.list. Than uploaded new Phpmyadmin version shows warning:

Your PHP MySQL library version 5.0.51a differs from your MySQL server
  version 5.5.24. This may cause unpredictable behavior.

How I can install new Mysql 5.5 version? Could you please advice?
Cheers

A:
The thing is, the PHP team need to launch an update to the libmysql file, this way, you can use a newer version of the Database.
If you want to update the PHP installation, just update the file libmysql to the version you want (if there is any available yet).
Try executing these commands:
apt-get update
apt-get install php5-mysql
apt-get install php5-mysqli

Here is the official installation guide.


text:
Q: 3D map view in QGIS with .grd format bathemetry data I am attempting to use the 3D map feature available in QGIS3 for viewing bathymetry data. These data are in .grd format, but I've also tried using data in GeoTiFF format with no luck.
The 3D map comes up blank, and no amount of scrolling brings the panel into view. I've checked that this feature does, in fact, work with .hgt (SRTM) elevation data.
I'm not super familiar with the differences between different data formats (.tif, .grd, .hgt, etc...) but my thinking is that these data are either missing some information or need to be converted to .hgt.
I do know that conversion to .hgt is possible, but it has some drawbacks that I'd like to avoid.
Has anyone encountered this problem and know of a possible solution?
EDIT: Here are some data


text:
Q: Given $AX = XD$, where $D$ is a diagonal matrix and $A$ is idempotent, is $D$ idempotent as well? $D$ is a diagonal matrix of eigenvalues and $X$ is a matrix of eigenvectors. Does $AA = A$ make $DD = D$? If so, how can you show that this is true?

A: I am assuming this may be homework, so I'm starting with a (strong) hint.
Hint: $\newcommand{\m}{\mathbf} \m A(\m X \m D) = \m A (\m A\m X) = \m A \m X$, so letting $\m B = \m A \m X$ we have $\m B \m D= \m B$ with $\m D$ being diagonal. Now think about what the relationship between the $i$th column of the left-hand side and the $i$th column of the right-hand side must be. (And, be careful not to arrive at too strong of a conclusion about $\m D$ either.)
Alternatively, and maybe simpler, break down your original matrix relation columnwise. That is, if $\m x_i$ is the $i$th column of $\m X$ and $\lambda_i$ is the corresponding eigenvalue of $\m A$, then
$$
\lambda_i \m x_i = \m A \m x_i = \m A^2 \m x_i = \m A (\m A \m x_i) = \m A (\lambda_i \m x_i) = \lambda_i (\m A \m x_i) \> \ldots
$$
Now, hopefully you can finish the rest.


text:
Q: In R / gwidgets, how to create a new Widget from Scratch - links between boxes / nodes? I want to have an interface that allows to draw links between boxes and save the results (box1 is connected to box2, 3 to 4 and so on) as shown in the picture below:

I do not really know where to start or even if something like this already exists or if it is possible - so I am grateful for any comment on the subject?

A: The HTkIdentify function in the TeachingDemos package allows you to interactively drag labels to new locations (and part of the return is the coordinates of the new locations) with a line between the point and the label.  Visually I think this is similar to what you are asking for.  It uses the tcltk package rather than gwidgets.  You could modify the code to draw your boxes as above (rather than a data based scatterplot), then based on the final locations of the "labels" you would determine which box was connected to.


text:
Q: Using JavaScript, how do I change the CSS style of one element based on the CSS style of another element? I'm trying to change the height of one div depending on the opacity/visibility of another div.  It seems like this should be pretty simple, but nothing I try seems to work.
I was thinking it would go something like this:
var red = document.getElementById("red");
var green = document.getElementById("green");

if(red.style.opacity = "0"){
green.style.height = "200px";
}

But that just changes both the opacity and the height without actually checking what the opacity was to begin with.
Any suggestions as how to achieve the functionality I'm after would be much appreciated!

A: Use getComputedStyle -

The getComputedStyle() method gets all the actual (computed) CSS
  property and values of the specified element.

var red = document.getElementById("red");
var rd = window.getComputedStyle(red).getPropertyValue("opacity");
var green = document.getElementById("green");
if (rd == 0) {
  green.style.height = "200px";
}
#red {
  width: 50px;
  height: 50px;
  background: red;
  opacity: 0;
}

#green {
  width: 50px;
  height: 50px;
  background: green;
}

Red

Green

A: Looks like you're explicitly setting opacity.  The following code should work:
if(red.style.opacity == 0){
   green.style.height = "200px";
}


text:
Q: Simple Modern OpenGL Hello World I want to make a simple modern OpenGL hello world Program. I already have some experience with modern OpenGL. I once even compiled my own shaders and all that. Now i want to use some more modern functions like glVertexAttribPointer. The Code Compiles but all i get is a black screen. No triangle is showing up. Is it some problem with my graphics card or am i doing something wrong?
I was following this tutorial: https://www.youtube.com/watch?v=Dyue3MzJDss&index=5&list=PLRwVmtr-pp06qT6ckboaOhnm9FxmzHpbY
When i look in the comments many people say that all they get is a black screen.
#include <iostream>
#define GL3_PROTOTYPES 1
#include <GL/glew.h>
#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#define BUFFER_OFFSET(i) ((char *)NULL + (i))

GLuint vbo;
GLuint w=0;
float f[]={0.0, 1.0, -1.0, -1.0, 1.0, -1.0};    //vertex array

void init()
{
  glClearColor(0,0,0,1);
  glEnable(GL_DEPTH_TEST);
  glGenBuffers(1,&vbo); //generate an index for the vertexbuffer
  glBindBuffer(GL_ARRAY_BUFFER,vbo);    //use vbo as ARRAY_BUFFER
  glBufferData(GL_ARRAY_BUFFER,sizeof(f),f,GL_STATIC_DRAW);//fill up the array with vertex and color-data
  glEnableVertexAttribArray(w);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
}

void display()
{
  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
  glDrawArrays(GL_TRIANGLES,0,3);       //draw it
}

int main()
{
  SDL_Init(SDL_INIT_EVERYTHING);
  SDL_SetVideoMode(640,480,32,SDL_OPENGL);
  glewInit();
  Uint32 start;
  SDL_Event event;
  bool running=true;
  init();
  bool b=false;
  while(running)
  {
    start=SDL_GetTicks();
    while(SDL_PollEvent(&event))
    {
        switch(event.type)
        {
            case SDL_QUIT:
                running=false;
                break;
            case SDL_KEYDOWN:
                switch(event.key.keysym.sym)
                {
                    case SDLK_ESCAPE:
                        running=false;
                        break;
                }
                break;

        }
    }
    display();
    SDL_GL_SwapBuffers();
    if(1000.0/30>SDL_GetTicks()-start)
        SDL_Delay(1000.0/30-(SDL_GetTicks()-start));
  }
  glDeleteBuffers(1,&vbo);
  SDL_Quit();
}


text:
Q: How to make a field non modifiable on edit page but able to create on add page? I have a scenario given below:
In my models.py
class Room(models.Model):
   pop = models.ForeignKey('Pop', verbose_name="POP",
                           help_text="Pop this room belongs to", null=True,
                           blank=True)
   .... other fields ....

 class Pop(models.Model):
    .... fields ....

In my admin.py
class RoomAdmin(admin.ModelAdmin):
    search_fields = [..some fields...]
    list_diplay = (pop, ....)
    ..... other configuration .....

Since Room has Foreign Key relationship with Pop, it is possible to associate multiple rooms with one Pop. I have to implement something like this.

*

*When the user clicks on the "Add Pop" link from the django admin page, the user should be allowed to associate multiple Room objects to a Pop object. But once Room objects have been associated to a Pop, it can neither be edited nor can it be associated with another Pop from the edit screen. Is it possible to achieve this?

I have these possible solutions but I don't know how to implement these ideas in Django or if these ideas are viable:

*

*CSS magic. I can associate a CSS id to pop field so that it can only be enabled for edit screens. I am not sure how to implement this

*Django's admin.py, If I could exclude pop field from the edit screen, then it might work.

*Modify the templates so that they can support non editable fields.

A: Option 2 is the best. You can override the get_form method in your RoomAdmin class to exclude the pop field when there is an object to edit:
def get_form(self, request, obj=None, **kwargs):
    # if there's an object and it has been previously saved
    if obj is not None and obj.id is not None:
        # add 'pop' to the list of fields to exclude
        exclude = list(kwargs.get('exclude', []))
        exclude.append('pop')
        kwargs['exclude'] = exclude
    return super(RoomAdmin, self).get_form(request, obj, kwargs)


text:
Q: C# Create byte array in code from copied SQL value? I stored a file in SQL server as a byte array. However, I want that file to be a default value when I initialize the database. The initialization is done in code (inserting some fixed values etc). If I look into SQL server I see the file's value, something like 0x89504E4......
How can I set a C# property (byte[]) to this value?
MyObject.filebytes = 0x89504E4...... obviously won't work.
Thanks

A: You can include your default file in project and then set value of your object with it's contents, like
MyObject.filebytes = File.ReadAllBytes("default.bin");

A: If I understand your question correctly, you could create property inside that class that is array of bytes, then you could read the file from wherever you please be it file or database.
public class MyObject
{
    public byte[] File { get; set; }
}

A: Close enough. You can either load it from an embedded resource or a file, or if it's just a short string, you could use the array initializer syntax:
MyObject.FileBytes = new byte[] { 0x89, 0x50, 0x4E, ... };

A: Assuming you are attempting to load byte array off sql server returned result set you can do the following. For example, if you get a SqlDataReader back from ExecuteReader call on sql command "SELECT mybytecolumn from mytable":
public byte[] GetBytes(SqlDataReader reader)
{
 const int MAXBUFFER = 4096;
 byte[] buffer = new byte[MAXBUFFER]
 using(MemoryStream ms = new MemoryStream())
 {
   int start = 0;
   long length;
   do
   {
      // Following is assuming column 0 has the byte data on the returned result set
      length = reader.GetBytes(0, start, buffer, 0, MAXBUFFER);
      ms.Write(buffer, 0, (int)length);
   }
   while(length == MAXBUFFER);
   return ms.ToArray();
 }
}

A: Pass copied value from database to GetBinaryFromHexaString function and it will return the string data.
public static string GetBinaryFromHexaString (string hexa)
{
    byte[] data = null;
    string retData = string.Empty;
    List<byte> bList = new List<byte>();
    try {
        for (int i = 2; i < hexa.Length - 1; i+=2) {
            string hStr = hexa.Substring(i, 2);
            byte b = byte.Parse(hStr, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            bList.Add (b);
        }
        data = bList.ToArray();
        retData = System.Text.Encoding.UTF8.GetString(data);
    }
    catch {}
    return retData;
}

Reference: Convert string to System.Data.SqlTypes.SqlBytes C#


text:
Q: drobo/rsync create weird root folder Running rsync from a drobo to fetch remote files, rsync create a wierdly named folder "_2X68O~Y" which contains the fetched files and folders. Under sh the folder has an empty name.
the commandine, run via a .sh script:

/mnt/DroboNAS/Shares/DroboApps/rsync/rsync -av --delete-during --exclude Recycle\ Bin rsync://192.168.26.2/BATI /mnt/DroboNAS/Shares/Backup/mtl/shares/montreal_bati/

so I'm getting /mnt/DroboNAS/Shares/Backup/mtl/shares/montreal_bati/_2X68O~Y/[files / folders]
rsync  version 3.0.7  protocol version 30

A: I used the same script on a FreeNAS box (written in komodo edit) and I had the same issue. I think it's a charset issue. I deleted it (on the freenas box) and rewrote it using putty/nano and it works.


text:
Q: logging me out? var account;
var users = ["minibluerhino"];
var password = "killer224";
var gameId = 126945035 //Put your game ID here

for (account = 0; account < users.length; account++) {
    window.location.assign('www.roblox.com');
    $(document).ready(function(){
        document.getElementById("LoginUsername").value = users[account];
        document.getElementById("LoginPassword").value = password;
        document.getElementById('LoginButton').click();
        $(document).ready(function(){
            window.location.assign('http://www.roblox.com/---place?id=' + gameId);
        });
   });
};

Whenever I run that code, it brings me to the target location, but I am notlogged in, If I remove the target location, it logs me in perfectly fine.

A: Firstly if i am not mistaken, this should be written more like
var account;
var users = ["minibluerhino"];
var password = "killer224";
var gameId = 126945035 //Put your game ID here

$(document).ready(function(){

    for (account = 0; account < users.length; account++) {
        window.location.assign('www.roblox.com');
        document.getElementById("LoginUsername").value = users[account];
        document.getElementById("LoginPassword").value = password;
        document.getElementById('LoginButton').click();
        window.location.assign('http://www.roblox.com/---place?id=' + gameId);
    };
});

Or This?
var account;
var users = ["minibluerhino"];
var password = "killer224";
var gameId = 126945035 //Put your game ID here

$(document).ready(function(){

    for (account = 0; account < users.length; account++) {
        window.location.assign('www.roblox.com');
        document.getElementById("LoginUsername").value = users[account];
        document.getElementById("LoginPassword").value = password;
        document.getElementById('LoginButton').click();
    };
    window.location.assign('http://www.roblox.com/---place?id=' + gameId);
});

Its hard to know what logic your going for exactly?
But the ready function simply means fun this code when the DOM is ready, as in everything on the page has loaded.
The window.location would be called for each loop which does not make sense?
EDIT:
I think i understand your problem now more so, Your trying to run this as a script against a web page to auto login you.. Say something like a grease monkey/user script..
The problem here is, Your entering the username and password into the boxes and click "login" as such.. But straight afterwards you are redirecting the browser before it even has time to process the login.
Going to guess a successful login on this site does not auto-reload the page, so hence your attempting this or trying to over ride the default page it loads as your home page.
In this case, you want to either use a setTimeout or handle another javascript on the page that they do load.
If their login does not reload, but simply changes some elements.. Listen to their events and trigger your reload when that happens.
SECOND EDIT
Try the following, click did not work on the button.. but because it is a form you can submit it using the form element.
var account;
var users = ["minibluerhino"];
var password = "killer224";
var gameId = 126945035 //Put your game ID here

$(document).ready(function(){

    for (account = 0; account < users.length; account++) {
        window.location.assign('www.roblox.com');
        document.getElementById("LoginUsername").value = users[account];
        document.getElementById("LoginPassword").value = password;
        document.getElementById('LogInForm').submit();
    };
   // window.location.assign('http://www.roblox.com/---place?id=' + gameId);
});

Being this is a bot, without knowing the further details. This might go against the stackoverflow terms and conditions or something. So going to have to limit what more support i can give.
In general i would suggest if your running scripts to help you login to websites or customize and automate them for you. Have a look at user scripts and you will see they have a world of use.
Have one that gives you a custom GUI or additional elements on a website when your logged in or just simple a script that auto logins you to any site in its list and so on.


text:
Q: Android Notification.Builder vs NotificationCompat.Builder Pretty much all the bits of sample code I see for Android notififactions appear to use NotificationCompat.  I have written up my own code using Notification.Builder.  It is not clear to me what benefits, if any, there might be in using NotificationCompat.Builder.  I hope that someone here might be able to explain the differences.

A: depends on what you are trying to do and what OS version's your app is compatible with but in most cases you would want to use NotificationCompat because that provides backwards compatibility where as if you wanted to provide that with the regular Notification.Builder  you would have to check what OS version the device has yourself to use API calls that are not in older versions


text:
Q: Cannot find TLS related ciphers in IBM websphere console I have navigated to SSL certificate and key management > SSL configurations > NodeDefaultSSLSettings > Quality of protection (QoP) settings in the IBM Websphere Console 8.5V and changed the protocol from SSL_TLS to TLS
Then I have clicked on 'Update selected ciphers" still I could not see any TLS related ciphers below in the "Selected ciphers" list. It only shows SSL related ciphers for example SSL_RSA_AES_256 but not something like TLS_RSA_AES_256
Do I have to update to anywhere else to get the TLS related ciphers in websphere?

A: The SSL_ is interchangeable with TLS_ in the cipher names.  The IBMJSSE document notes that in the beginning, https://www.ibm.com/support/knowledgecenter/en/SSYKE2_7.0.0/com.ibm.java.security.component.70.doc/security-component/jsse2Docs/ciphersuites.html
Even thought the string is saying SSL_RSA_AES_256,  TLS_RSA_AES_256 will be applied.


text:
Q: Mathematical Induction with Combinations Let $\gamma_i=(-1)^i\dbinom{2n+1}{i}$ and $a_{n}$ be fixed.
Observe that:
$$\begin{array}{lllll}
a_{n}&=a_{n}\\
a_{n-1}&=-\gamma_1 a_{n}\\
        &=\dbinom{2n+1}{1}a_{n}\\
a_{n-2}&=-\gamma_{1}a_{n-1}-\gamma_{2}a_{n}\\
        &=\dbinom{2n+1}{1}\dbinom{2n+1}{1}a_{n}-\dbinom{2n+1}{2}a_{n}\\
        &=\dbinom{2n+2}{2}a_{n}\\
a_{n-3}&=-\gamma_1a_{n-2}-\gamma_2a_{n-1}-\gamma_{3}a_{n}\\
        &=\dbinom{2n+1}{1}\dbinom{2n+2}{2}a_{n}-\dbinom{2n+1}{2}\dbinom{2n+1}{1}a_{n}+\dbinom{2n+1}{3}a_{n}\\
        &=\dbinom{2n+3}{3}a_{n}
\end{array}$$
My goal is to show that for any $k \in \mathbb{Z}_n$,
$$a_{n-k}=-\sum_{i=1}^k\gamma_i~a_{n-k-i}=\dbinom{2n+k}{k}a_n.$$
Any help will be appreciated. Thank you so much!
(This is actually a form of the entries of a particular matrix I am working on.)


text:
Q: Integrating JIRA Service Desk with PagerDuty I would like to create a PagerDuty incident every time a customer creates an issue of a certain type (Fault) on JIRA Service Desk. So I have created a JIRA user with the email address provided by PagerDuty, an incident was created when JIRA sent the invitation to PagerDuty, which seems to indicate that when JIRA sends an email, PagerDuty gets it. Then I added an automation rule (issue notifications did not work as I didn't find a way to send a notification only when an issue of a certain type is created), to notify my special user every time an issue is created with the Fault type.

But when I create an issue of this type, nothing seems to be sent to PagerDuty. I have tested sending an email directly to the email address of PagerDuty user and it worked. I have tested notifying another user when an issue is created in JIRA Service desk and it worked too. So I don't know what's wrong but I can't get the email to be sent to PagerDuty from JIRA Service Desk. Any idea of what I missed?


text:
Q: How to separate float into an integer and a fractional part? I am willing to cast precise operations and for that purpose I need a way to
seperate a float number into an integer and a fractional part.
Is there any way for this?

A: There is a function included in math.h library called modf
With this function you can do just what are you trying to.
Example:
#include <stdio.h>
#include <math.h>

double ftof ()
{
    double floating = 3.40, fractional, integer;

    fractional = modf(floating, &integer);
    printf ("Floating: %g\nInteger: %g\nFractional: %g", floating, integer, fractional); // when using printf, there are no floats

    return fractional;
}

Output:
Floating: 3.40
Integer: 3
Fractional: 0.40

Note that using double in most of the cases is better than using float, despite that double
consumes twice the memory of float (4:8 bytes) hence the increased range and accuracy. Also in case you need more precise output from
bigger floating numbers when printing, you can try the printf() exponent format specifier %e instead of %g which only uses the
shortest representation of the floating decimal.

A: One other way using type cast.
#include <stdio.h>
#include <math.h>
void main()
{
    float a = 3.4;
    float a_frac = a - (int) a;
    float a_int = a - a_frac;
    printf("Number = %f, Integer = %f, Fraction = %f", a, a_frac, a_int);
}

A: A thought crossed my mind to separate them with some logic :
    #include <iostream>

using namespace std;
int main()
    {
    double fr,i,in,num=12.7;
    for(i=0;i<num;i++)
    {
        fr=num-i;
        }
        cout<<"num: "<<num;
cout<<"\nfraction: "<<fr;
in=num-fr;
cout<<"\nInteger: "<<in;
    }

Hope this was what you were searching for:) .

A: #include <bits/stdc++.h>

using namespace std;

int main()
{
    double n;
    cin>>n;
    double fr = n-((int)n);

    cout<<"int "<<(int) n<<"\n";

    cout<<"fraction "<< fr;

    return 0;
}


text:
Q: How to constrain second NSViewController minimum size in OS X app? I am a novice Mac OS X developer.  I assume this is an easy question, but I haven't been able to find any useful results via searches.
How do I constrain the size of a SECOND view controller?
I started with a simple Mac OS X app, with a single View Controller.  I can select the window that contains the View Controller, then select the "Size Inspector" and check the "Minimum Content Size" box, and specify a minimum x and y for the window.
This allows me to specify the minimum size for this first view controller, as I expect.  All is good.
Then I add a second view controller, with a Modal segue from the first view controller, triggered by a button press.  I add a NSTextView to this second view controller, to display an attributed string.  The text view works fine, displaying the attributed string correctly.  This text view is a separate window, and has no minimum size constraint.
So how do i specify the minimum size for this second view controller view? Is this typically done in Interface Builder, or programmatically? When I step through the view hierarchy using Document Outline, I don't see how I can specify minimum size using the Size Inspector.  Am I missing something??
Here is my simplified code:
file "ViewController.swift"
class ViewController: NSViewController {
...
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
    let secondVC: SecondViewController = segue.destinationController as! SecondViewController
    secondVC.reportAttrString = myReport.reportText
    }
...
}

file "SecondViewController.swift"
class SecondViewController: NSViewController {
    var reportAttrString = NSMutableAttributedString()

    @IBOutlet var ReportTextView: NSTextView!
}

I would appreciate any suggestions, or pointers to any documentation or tutorials that may help me.

A: The simplest way to do this would be:
class SecondViewController: NSViewController, NSWindowDelegate {

override func viewWillAppear() {
    super.viewWillAppear()
    self.view.window?.delegate = self
    self.view.window?.minSize = NSSize(width: 100, height: 100)
    }

}

override func viewDidAppear() {
    super.viewDidAppear()
    var frame = self.view.window!.frame
    var initialSize = NSSize(width: 100, height: 100)
    frame.size = initialSize
    self.view.window?.setFrame(frame, display: true)
}

Although if you were looking for a manual approach then the following would work aswell.
class SecondViewController: NSViewController, NSWindowDelegate {

override func viewWillAppear() {
    super.viewWillAppear()
    self.view.window?.delegate = self
    // Set the initial size
    var frame = self.view.window?.frame
    var initialSize = NSSize(width: 100, height: 100)
    frame.size = initialSize
    self.view.window?.setFrame(frame, display: true)
}

func windowWillResize(_ sender: NSWindow, to frameSize: NSSize) -> NSSize {
    let minimumSize = NSSize(width: 100, height: 100)
    var newSize = NSSize()
    if(frameSize.width < minimumSize.width) {
        newSize.width = minimumSize.width
    } else {
        newSize.width = frameSize.width
    }
    if(frameSize.height < minimumSize.height) {
        newSize.height = minimumSize.height
    } else {
        newSize.height = frameSize.height
    }
    return newSize
}

}

Further reading:
Resize windows event
NSWindow minSize
Resizing the window


text:
Q: Question on finding the value of algebraic identity if $a+b+c=0$ If $a,b,c\in \Bbb{R}$ and $a+b+c=0$, then evaluate
$$\left(\frac{a}{b-c}+\frac{b}{c-a}+\frac{c}{a-b}\right)\left(\frac{b-c}{a}+\frac{c-a}{b}+\frac{a-b}{c}\right)$$
I tried using the identity, $$\frac{b-c}{b+c}+\frac{a-c}{a+c}+\frac{a-b}{a+b}=-\frac{b-c}{b+c}\cdot\frac{a-c}{a+c}\cdot\frac{a-b}{a+b}$$However, I couldn't get anywhere. I also tried using normal algebraic methods but I couldn't get anywhere.
 Please help me out. Thanks a lot :)

A: $$X=\left(\frac{c-a}{b}+\frac{b-c}{a}+\frac{a-b}{c}\right) \left(\frac{a}{b-c}+\frac{b}{c-a}+\frac{c}{a-b}\right)=$$
$$=\frac{a^3-a^2 (b+c)-a \left(b^2-3 b c+c^2\right)+(b-c)^2 (b+c)}{a b c}=$$
$$=\frac{a^3-a^2 b-a^2 c-a b^2+3 a b c-a c^2+b^3-b^2 c-b c^2+c^3}{a b c}=$$
$$=\frac{(a+b+c)^3-4 (a b+a c+b c) (a+b+c)+9 a b c}{abc}$$
as $a+b+c=0$ we have $X=9$


text:
Q: My c drive shows less size then it should be
Possible Duplicate:
Best program to visualize file system usage on Windows?

I have  2 partition on 80 gb hdd. C drive is of 29gb. The property shows that used space is 28.5gb. But when I select all the folders in c drive it shows property of 16gb. So there is a more then 10gb space which is not freed on my drive. Kindly help for the problem.

A: The missing space is most likely in the Recycle Bin or in other hidden folders.  Depending on your OS version, it may also be in other user folders if you have UAC enabled.
Whenever I need to figure out where disk space has gone, I typically use WinDirStat.  It makes it pretty easy to see what's using disk space.  I also typically use CCleaner to clean the disk of unnecessary garbage in the form of temp files and such.  Be careful with the latter, however, as you are deleting files with it.

A: Also, dependent on the OS, your file system may need checking using something like chkdisk to find file and table entries that don't match, etc


text:
Q: Getting a list of videos from a YouTube channel using JSON I am attempting to list the 5 most recent videos (title, updated, thumbnail (hqDefault)) from a channel. I have the data in JSON format, but despite looking at several guides I can not seem to parse it. Any ideas? Can use Javascript or jQuery.
Here's the URL: https://gdata.youtube.com/feeds/api/videos?q=googledevelopers&max-results=5&v=2&alt=jsonc&orderby=published
FWIW here is what I have so far (Disregard HTML formatting)
    $.getJSON('https://gdata.youtube.com/feeds/api/videos?q=googledevelopers&max-results=5&v=2&alt=jsonc&orderby=published', function(data) {
    var output="<ul>";
    for (var i in data.data.items) {
        output+="<li>" + data.data.items[i].title + "</li>";
    }
    document.getElementById("videos").innerHTML=output;

A: Once you get the parsed object, you can iterate through it like:
$.getJSON('https://gdata.youtube.com/feeds/api/videos?q=googledevelopers&max-results=5&v=2&alt=jsonc&orderby=published', function(data) {
    console.log(data);
    for(var i=0; i<data.data.items.length; i++) {
       console.log(data.data.items[i].title); // title
       console.log(data.data.items[i].description); // description
    }
});


text:
Q: converting column item into its own column python i have a data frame that looks like this
column1  column2

rabbit   fluffy
dog      cute
cat      tabby

i would like to make each value in column1 into its own column, with values in column2 as the observation for that column.
So the end result desired is:
rabbit dog  cat

fluffy cute tabby

What is the proper syntax in python to accomplish this task?

A: Use DataFrame contructor:
df1 = pd.DataFrame([df['column2'].tolist()], columns=df['column1'].tolist())

If more columns:
cols = df.pop('column1').tolist()
data = df.values.reshape(len(df.columns), -1)
df1 = pd.DataFrame(data, columns=cols)

Or set_index with transpose by T with data cleaning - reset_index and rename_axis:
df1 = df.set_index('column1').T.reset_index(drop=True).rename_axis(None, axis=1)

print (df1)
   rabbit   dog    cat
0  fluffy  cute  tabby


text:
Q: Django invalid form when using modelchoicefield I am new to Django and I have been struggling to get the selected value of the forms.ModelChoiceField in my views. My form (post) is not valid and I noticed that the request.POST returns all the possible values in the ModelChoiceField. How do I get only model the selected by the user? Thank you in advance for any help.
Model
I have a sensor model as well as a measurements model...
class Sensor(models.Model):
    # This contains information about a sensor, type, location, and other
    type = models.CharField(max_length=16)
    ...

class Measurement(models.Model):
    #This contains the measurements of the sensors at a given date
    sensor = models.ForeignKey('Sensor')
    date = models.DateField()
    temperature = models.FloatField()
    pressure = models.FloatField()
    ...
    class Meta:
        unique_together = ('sensor', 'date')

Form
... and a form that allows the user to choose the sensor and date:
class MeasurementForm(forms.ModelForm):
    #the user is allowed to choose any sensor that is related to the measurement table
    sensor = forms.ModelChoiceField(queryset=Sensor.objects.exclude(measurement=None))
    date =  forms.DateField(widget=DateInput(attrs={'format':'%Y-%m-%d'}), initial=datetime.today)

So far so good, this gets rendered by the get method and the user is able to select both sensor and date. However, the following view fails at the post, after submitting:
Views
class MeasurementView(View):
    form_class = MeasurementForm
    my_template = "measurement.html"

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.my_template, {'form': form, 'data':None})

    def post(self, request, *args, **kwargs):
        print(request.POST)
        print(new_form.errors)
        new_form = self.form_class(data=request.POST)
        if new_form.is_valid():
            print('form is valid')
            data = get_data_for_sensor_date(
                        new_form.cleaned_data['sensor'],
                        new_form.cleaned_data['date']))
            return render(request, self.my_template, {'form':new_form, 'data':data})
        else:
            return render(request, self.my_template, {'form':new_form, 'data':None})

Console output
<QueryDict: {'sensor': ['', '1'],
             'csrfmiddlewaretoken': ['YUPfrdhdbQdAa7EyNx2sJeHdbxmQXTTW'],
             'date': ['2016-11-07']}>

__all__

Measurement with this Sensor and Date already exists.

A: I found this link Django formview returns object already exists error with a modelform
To which I quote:
"Ok. I found a solution for my error. What caused the model already exists error was my ModelForm CheckProductForm. Codename attribute is unique, so my validation always returned False. What I did was to change my orginal ModelForm to a Form. This solved my whole issue. And for the form_invalid in form_valid issue. I've overwritten my form's clean_codename function to raise ValidationError if product doesnt exist."
I still do not understand why I had the error in the first place. However, changing the form to the code below made the trick.
Form
class MeasurementForm(forms.Form):
    #the user is allowed to choose any sensor that is related to the measurement table
    sensor = forms.ModelChoiceField(queryset=Sensor.objects.exclude(measurement=None))
    date =  forms.DateField(widget=DateInput(attrs={'format':'%Y-%m-%d'}), initial=datetime.today)


text:
Q: replace words in pandas one dataframe with words in other dataframe I have below two dataframes
(Pdb) df
                msg
0               the
1               wi
2               fi
3              **a/c**

(Pdb) dictionary

           old_msg    new_msg
0              a/c    account
1             extend  extend
2             bal     balance

I want first dataframe to become like below (replace words with 2nd dataframe)
(Pdb) df
          msg
0              the
1               wi
2               fi
3              **account**

A: You can use replace by Series or by dict:
df['msg'] = df['msg'].replace(dictionary.set_index('old_msg')['new_msg'])
print (df)
       msg
0      the
1       wi
2       fi
3  account

Or:
df['msg'] = df['msg'].replace(dictionary.set_index('old_msg')['new_msg'].to_dict())
print (df)
       msg
0      the
1       wi
2       fi
3  account


text:
Q: How does Windows 10 guess physical dimensions of a 1080p display? I'm running Windows 10 1803 on a laptop, attached to a desktop display. Laptop's display resolution is same as the attached display, 1920x1080 pixel (namely "Full HD").
However the screen sizes differ, the laptop has a 13" display and the desktop display is 27"...
By the settings option: start->system->display I can adjust scaling for each (!) display to the lowest scaling factor "100%" and a highest resolution of FullHD (1080p).
This setting is fine for the laptop display.
However, with the same setting for the 27" everything appears double sized ...
Q1: How does Windows 10 guess the (physical) dimensions of a screen display to get dpi be calculated "per inch"?
Q2: Is there any option to let Windows 10 to render a "virtual" screen resolution higher than the physical maximum on the 27" display - compare Is there a registry hack to set virtual display resolution in Windows 10 1803?
Q3: Why does Windows 10 ignore the registry dword HKEY_CURRENT_USER\Control Panel\Desktop\LogPixels, when I set the value from initial 96ppi to a higher resolution - compare Can I (programmatically) freeze Windows 10 scaling factor to 100% with Win8DpiScaling=1
Remark: Since I do not work on a stationary desktop, buying a 4k display is definitely no option and no answer to this topic.
However, using 2k+ displays would solve the problem since Windows will then calculate a reasonable dpi resolution for the attached displays.
Remark: This is still an open topic using win2004.

A: I can't really claim to have seen any Windows or driver internals.. Anyway, I know physical display size is at least being advertised in the EDID.
https://en.wikipedia.org/wiki/Extended_Display_Identification_Data


text:
Q: html form, submit and stay at same place on page I have a long form for our learners to complete. When they click the Save Progress button to submit their work so far, the page automatically jumps back to the top and they have to scroll down to find their last answer submitted.
I'd like them to be able to save their progress at any point and stay at that point on the page.
I've tried the following, the alert appears and the page stays still but the learners work isn't saved.
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
  $(function () {

    $('#form1').on('submit', function (e) {

      e.preventDefault();

      $.ajax({
        type: 'post',
        url: 'Ext1SUp.php',
        data: $('#form1').serialize(),
        success: function () {
          alert('form was submitted');
        }
      });

    });

  });
</script>

Form action:
<form action=  "Ext1SUp.php" method="post" id="form1">

Save Progress button:
<button type="Submit" name="Save" class="save-progress" form="form1" value="Submit" >Save Progress</button>

PHP:
<?php
require_once 'login.php';
$connection = new mysqli($hn, $un, $pw, $db);
if ($connection -> connect_error) {
echo "Failed to connect to MySQL: " . $connection -> connect_error;
}
if(isset($_POST['Submit'])) {
$sql =  "UPDATE unit1 SET
         U1Q1 = '{$_POST['U1Q1']}'
        ,U1Q2 = '{$_POST['U1Q2']}'
        ,U1Q3 = '{$_POST['U1Q3']}'
        ,U1Q4 = '{$_POST['U1Q4']}'
        ,U1Q5 = '{$_POST['U1Q5']}'
        ,U1Q6 = '{$_POST['U1Q6']}'
        ,U1Q7 = '{$_POST['U1Q7']}'
        ,U1Q8 = '{$_POST['U1Q8']}'
        ,U1Q9a = '{$_POST['U1Q9a']}',U1Q9b = '{$_POST['U1Q9b']}',U1Q9c = '{$_POST['U1Q9c']}',U1Q9d = '{$_POST['U1Q9d']}'
        ,U1Q10 = '{$_POST['U1Q10']}'
        ,U1Q11a = '{$_POST['U1Q11a']}',U1Q11b = '{$_POST['U1Q11b']}',U1Q11c = '{$_POST['U1Q11c']}',U1Q11d = '{$_POST['U1Q11d']}'
        ,U1Q12 = '{$_POST['U1Q12']}'
        ,U1Q13 = '{$_POST['U1Q13']}'
        ,U1Q14 = '{$_POST['U1Q14']}'
        ,U1Q15a = '{$_POST['U1Q15a']}',U1Q15b = '{$_POST['U1Q15b']}',U1Q15c = '{$_POST['U1Q15c']}',U1Q15d = '{$_POST['U1Q15d']}',U1Q15e = '{$_POST['U1Q15e']}'
        ,U1Q16a = '{$_POST['U1Q16a']}',U1Q16b = '{$_POST['U1Q16b']}',U1Q16c = '{$_POST['U1Q16c']}',U1Q16d = '{$_POST['U1Q16d']}'
        ,U1Q17 = '{$_POST['U1Q17']}'
        ,U1Q18a = '{$_POST['U1Q18a']}',U1Q18b = '{$_POST['U1Q18b']}',U1Q18c = '{$_POST['U1Q18c']}'
        ,U1Q19 = '{$_POST['U1Q19']}'
        ,U1Q20a = '{$_POST['U1Q20a']}',U1Q20b = '{$_POST['U1Q20b']}',U1Q20c = '{$_POST['U1Q20c']}',U1Q20d = '{$_POST['U1Q20d']}'
        ,U1Q21 = '{$_POST['U1Q21']}'
        ,U1Q22 = '{$_POST['U1Q22']}'
        ,U1Q23 = '{$_POST['U1Q23']}'
        ,U1Q24a = '{$_POST['U1Q24a']}',U1Q24b = '{$_POST['U1Q24b']}',U1Q24c = '{$_POST['U1Q24c']}'
        ,U1Q25 = '{$_POST['U1Q25']}'
        ,U1Q26 = '{$_POST['U1Q26']}'
        ,U1Q27 = '{$_POST['U1Q27']}'
        WHERE id = '{$_POST['id']}'";

$result = mysqli_query($connection, $sql);
    }
    header('Location: Ext1S.php');
?>

The process works fine, it only stops saving after adding the script to prevent the page from scrolling.
I hope someone can offer me some advice,
Thank you
Lisa

A: Change button type to "button" instead of "submit" to prevent executing form. You are storing data using ajax so it's not needed to submitting form using button.

A: Button Type should be a "button". Remove "form" attribute from button, and change your $().on('submit') to for ex. function submitForm () {}. Then as the button attribute add onclick="submitForm()". And you can remove your preventDefault(); and action attribute from form, because you sending data by Ajax, not with a classic form. Classic forms has to refresh page after submit, but with ajax you even don't need to submit anything. Just send async request in separated function. Something like this:

function submitForm(){
  $.ajax({
        type: 'post',
        url: 'Ext1SUp.php',
        data: $('#form1').serialize(),
        success: function () {
          alert('form was submitted');
        }
      });
}
<form id="form1">
  <!-- Yours form -->
  <button type="button" onclick="submitForm();">Submit</button>
</form>

OH! And I almost forget. You have to remove yours if(isset($_POST['Submit'])) {} from PHP in this case. And stop using mysqli for connection :) try out PDO


text:
Q: cyclic dependency error when importing service into another service I'm trying to set default headers for my http requests using the DefaultRequestOptions class provided by Angular 2. Documentation can be found here: https://angular.io/docs/ts/latest/guide/server-communication.html#!#override-default-request-options
I want to add a default bearer token, which gets set in one of my services, but doing so gives me the following error in my browser console:

Unhandled Promise rejection: Provider parse errors: Cannot instantiate
  cyclic dependency! Http: in NgModule AppModule in ./AppModule ; Zone:
   ; Task: Promise.then ; Value:

Here is my default-request-options.service.ts file:
import { Injectable }                         from '@angular/core';
import { BaseRequestOptions, RequestOptions } from '@angular/http';
import { UserService }                        from './user.service';

@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {

  constructor(private userService: UserService) {
    super();

    // Set the default 'Content-Type' header
    this.headers.set('Content-Type', 'application/json');
    this.headers.set('Accept', 'application/json');
    this.headers.set('Authorization', 'Bearer ' + this.userService.idToken);
  }
}

export const requestOptionsProvider = { provide: RequestOptions, useClass: DefaultRequestOptions };

Here is the relevant code in my app.module.ts file:
import { requestOptionsProvider }         from './default-request-options.service';
import { UserService }                    from './user.service';

@NgModule({
    imports: [
        ...
    ],
    declarations: [
        ...
    ],
    providers: [
        ...
        requestOptionsProvider,
        UserService
    ],
    bootstrap: [ AppComponent ]
})

What am I doing wrong?

A: Imagine 3 services ..
Service1, Service2, Service3

*

*Service1 imports Service2

*Service2 imports Service3

*Service3 imports Service1

Service1 tries to import 2, 2 tries to import 3, 3 tries to import 1 and this continues forever. This is a cyclic dependency.
Break the loop to fix it.