text:
Q: Why won't eclipse allow me to parse JSON? I want to parse the JSON file at this link:  http://maps.googleapis.com/maps/api/directions/json?origin=33.7489,-84.3881&destination=33.7514,-84.7478&sensor=false
I want to parse the "html_instructions" string, from the "steps" array as such:
String googledirectionsapi = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination0 + "&sensor=false";
                    try {
                        JSONObject googleObject = Directions.getJSONfromURL(googledirectionsapi);
                        JSONArray parsedGoogleDirections = googleObject.getJSONArray("routes").getJSONArray("steps");
                        thing.setText(googledirectionsapi);
                        if(parsedGoogleDirections.equals("") ){
                            Toast.makeText(FindDealer.this, "Cannot find suitable route", Toast.LENGTH_LONG).show();
                        }else{
                             for (int i = 0; i < parsedGoogleDirections.length(); i++) {
                                    JSONObject instructions = parsedGoogleDirections.getJSONObject(i);
                                    if (i == 0){
                                        String step1 = parsedGoogleDirections.getString("html_instructions");

                             }
                             }
                             }
                    }catch (JSONException e) {
                              Log.d("log_tag","JSON parsing error - Google Directions Api:" + e.getMessage());
                        }

However, eclipse is giving me errors at:
.getJSONArray("steps");  //<-- The method getJSONArray(int) in the type JSONArray is not applicable for the arguments (String).

and and also giving me errors at:
.getString("html_instructions"); //<--he method getString(int) in the type JSONArray is not applicable for the arguments (String)

Why is eclipse showing these errors? I've never had this issue before.  THank you in advance.

A: There is a similar question:JSON parsing of Google Maps API in Android App
I think you should firstly get an Object from JsonArray using index. Then you should get legs as array.Then you should get an object from leg array. then you can get steps array.
https://stackoverflow.com/a/7237305/538408


text:
Q: PHP String to JS Array I have two files. The first is my front page that gets information via an ajax function and the second one is a PHP file that gets the data from a database.
The data returned is a string, formatted as an array (example : ['0','0','0','0','0','0','0','0','0','0'] ).
I need the PHP data to be interpreted as a JS array so I can use it easily.
I tried to return a PHP array, but the result in JS is undefined.
Here is my code :
PHP data retriever :
$g = new Game();
$top1 = ($g->getMatchKills($lobby)[0]['p1c1kills']);
$top2 = ($g->getMatchKills($lobby)[0]['p2c1kills']);
$jgl1 = ($g->getMatchKills($lobby)[0]['p1c2kills']);
$jgl2 = ($g->getMatchKills($lobby)[0]['p2c2kills']);
$mid1 = ($g->getMatchKills($lobby)[0]['p1c3kills']);
$mid2 = ($g->getMatchKills($lobby)[0]['p2c3kills']);
$adc1 = ($g->getMatchKills($lobby)[0]['p1c4kills']);
$adc2 = ($g->getMatchKills($lobby)[0]['p2c4kills']);
$sup1 = ($g->getMatchKills($lobby)[0]['p1c5kills']);
$sup2 = ($g->getMatchKills($lobby)[0]['p2c5kills']);

echo "['" . $top1 ."','" .$top2. "','" . $jgl1 . "','" . $jgl2 . "','" . $mid1 . "','" . $mid2 . "','" . $adc1 . "','" . $adc2 . "','" . $sup1 . "','" . $sup2 . "']";

And my JS script is :
function RefreshKDAs() {
    $.ajax({
        url: 'getKills.php?lobby=<?= $lobby ?>',
        success: function (data) {
            console.log(data)
        }
    })
}

A: Use json_encode to format a PHP array into JSON:
https://www.php.net/manual/en/function.json-encode.php

A: I solved this using
$data = $g->getMatchKills($lobby)[0];
header("Content-Type: applicaton/json");
echo json_encode($data);
on my data retriever PHP file.
Thanks to Chris G.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I re-route Cocoa applications through ssh -X? Is is possible to re-route Cocoa applications through ssh -X? I like being able to route X applications, but I want to route Cocoa applications too. Any ideas?

A: No - Cocoa is not an X windows compatible system. The closest you will get is screen sharing (VNC). See this question for more info. For Lion like background sharing with 10.5 and 10.6 see this question on third party VNC tools.

A: You might be able to connect a VNC server and client tunneled through ssh, and view an app remotely that way.


text:
Q: How to regex multiple text sentences/lines in javascript? I want to be able to regex multiple sentences from one regex if it is possible
/(.*)<FooBar>/s

this only matches one word (I think) I need something that matches words follows by spaces.
this is the regex that I tried but does not seem to work I don't know if it's because of javascript syntax or something else. (I'm new to regex)
^.*(EVENTS\:OB\:\sRECORDS\snot|EVENTS\:OB\:\sRECORDS\sthat|EVENTS\:OB\:\sUnprocessed).(?<!0\.0)$

Uncaught SyntaxError: Unexpected token ^

these are examples of sentences that I want to regex
EVENTS:OB: Records not updated to status
EVENTS:OB: Records that were pending OR to be processed for yester day.
EVENTS:OB: Unprocessed records older than hour.
RENAS:OB:BOX: Unprocessed records older than hour.
RENAS:MOSS Pending
RENAS:TIGNET Pending
RENAS:OB:SI: Unprocessed records older than hour.
RENAS:OB:GC: Unprocessed records older than hour.
RENAS:RENAS:Count of pending message to process.
RENAS:OB:10+2_Status: Unprocessed records older than hour.
RENAS:RENAS_10+2:Unprocessed records in RENAS 10+2
RENAS:RENAS ACH:Count of pending message to process to FV.
RENAS:CheckNow:Count of pending message to process to FV
RENAS:OB:GB: Unprocessed records older than hour.
RENAS:RENAS: UN Processed records by MIXX for RENAS INSTRUCTONS
RENAS:RENAS: UN Processed records by MIXX for RENAS Break Bulk
RENAS:RENAS: UN Processed records by MIXX for RENAS
RENAS:OB:DOM:Unprocessed count of records older than hour.
RENAS:OB:DOM:Failed records in the database for previous date.
RENAS:OB:SI:Records that were pending to be processed for the previous day.

what I have been doing is this
function getLines(text) {
  var lines = [];
  var re = /^.*(EVENTS\:OB\:\sRECORDS\snot|EVENTS\:OB\:\sRECORDS\sthat|EVENTS\:OB\:\sUnprocessed).(?<!0\.0)$/;
  while (m = re.exec(text)) {
    lines.push(m[1]);
  };

  return lines;
}

$(function() {
    $('#printlogs').html(getLines($('textarea').val()).join('
'));
});

A: You need a negative lookahead instead of a non-supported lookbehind:
/^.*(?:EVENTS:OB:\s(?:RECORDS\snot|RECORDS\sthat|Unprocessed))(?!.*0\.0$).*$/gim

See the regex demo.
Details

*

*^ - start of string

*.* - any 0+ chars other than line break chars, as many as possible

*(?:EVENTS:OB:\s(?:RECORDS\snot|RECORDS\sthat|Unprocessed)) - a EVENTS:OB: string followed with 1 whitespace and any of the alternatives:

*

*RECORDS\snot - RECORDS, a whitespace, not

*RECORDS\sthat - RECORDS, a whitespace, that

*Unprocessed - an Unprocessed substring

*(?!.*0\.0$) - there can't be a 0.0 at the end of the line

*.*$ - any 0+ chars other than line break chars, as many as possible, up to the end of the line.

var s = "EVENTS:OB: Records not updated to status\nEVENTS:OB: Records that were pending OR to be processed for yester day.  \nEVENTS:OB: Unprocessed records older than hour.  \nRENAS:OB:BOX: Unprocessed records older than hour.  \nRENAS:MOSS Pending  \nRENAS:TIGNET Pending  \nRENAS:OB:SI: Unprocessed records older than hour.  \nRENAS:OB:GC: Unprocessed records older than hour.  \nRENAS:RENAS:Count of pending message to process. \nRENAS:OB:10+2_Status: Unprocessed records older than hour.\nRENAS:RENAS_10+2:Unprocessed records in RENAS 10+2\nRENAS:RENAS ACH:Count of pending message to process to FV.\nRENAS:CheckNow:Count of pending message to process to FV\nRENAS:OB:GB: Unprocessed records older than hour.\nRENAS:RENAS: UN Processed records by MIXX for RENAS INSTRUCTONS \nRENAS:RENAS: UN Processed records by MIXX for RENAS Break Bulk \nRENAS:RENAS: UN Processed records by MIXX for RENAS \nRENAS:OB:DOM:Unprocessed count of records older than hour.\nRENAS:OB:DOM:Failed records in the database for previous date.\nRENAS:OB:SI:Records that were pending to be processed for the previous day.";
var re = /^.*(?:EVENTS:OB:\s(?:RECORDS\snot|RECORDS\sthat|Unprocessed))(?!.*0\.0$).*$/gim;
document.body.innerHTML = "
" + JSON.stringify(s.match(re), 0, 4) + "
";


text:
Q: Function isn't called with responsed data Hello I got a weird problem... I lost almost 2 hrs and I have no idea why it doesn't work.
It should sum all values for every dept where username = name choosed by select and where date = date choosed by datepicker.
It works great on jsFiddle but when I am trying use it with responsed data it doesn't work and don't have any errors in console.
What am I doing wrong? This is code in my app not the same which is in jsFiddle
HTML:

  <md-datepicker ng-model="myDateUser" md-placeholder="Enter date"></md-datepicker>
           {{myDateUser}}
           <md-input-container flex="50">
                Select user:
               <md-select ng-model="data.model" ng-change="sum(data.model)">
                     <md-option ng-value="logins.name" ng-repeat="logins in chooseLogins">{{logins.name}}</md-option>
               </md-select>
           </md-input-container>

           <tt>{{data.model}}</tt>

  <md-table-container>

          Dept
          Total time

          {{ test.dept }}
          {{ test.total }}

          {{ key }}
          {{ val }}

  </md-table-container>

JS:
function getTotalTime() {
      $http.get('db_files/totalTimeDB.php').then(function(response) {
      $scope.data = response.data;
              $scope.sum = function(name) {

                        let model = $scope.data.filter(function(item) {
                            return (item.username == name && TheDate(item))
                        });

                        let tests = {};
                        model.forEach(function(item) {
                            if (!tests.hasOwnProperty(item.dept)) {
                                tests[item.dept] = 0;
                            }
                            tests[item.dept] += parseFloat(item.task_time);
                        });
                        $scope.data.model = tests;
                    }
                    function TheDate(item){
                      if($scope.myDateUser){
                        var myDateUser = new Date($scope.myDateUser);
                        var itemDate = new Date(item.task_end);
                        console.log("task_end " + item.task_end);
                        console.log("myDate " + $scope.myDateUser);

                        if(myDateUser.getFullYear() != itemDate.getFullYear() || myDateUser.getMonth() != itemDate.getMonth()){
                          return false;
                        }
                      }
                        return true
                    }

Example console.log from $scope.data = response.data;
Object
dept:"Test2"
status:"Closed"
task:"test test test"
task_end:"2016-09-02"
task_start:"2016-09-02"
task_time:"80"
username:"Nelson"
__proto__:Object

It works like show total sum only where username = choosed name and TheDate function is ignored. Also console.log shows nothing ( in example jsFiddle console.log shows selected date and name )
It looks like the function isn't called.


text:
Q: How to write a plot title in more than one line using suptitle? Here is an example:
fig.suptitle('Lorem ipsum dolor sit amet, consectetur adipiscing elit donec nec condimentum libero. Phasellus condimentum porttitor congue morbi eget quam sed justo egestas lobortis aenean et erat metus')

How to make this title in 3 lines?

A: Just insert a newline character \n where you want the new line.
import matplotlib.pyplot as plt
fig = plt.figure()
fig.suptitle('This sentence is\nbeing split\ninto three lines')
plt.show()


text:
Q: How do I copy an array of ANSI strings so that I can get another array of ANSI string I want to know if there is a function that slices an Array of AnsiString and return Array of AnsiString. The Copy function returns Array of String, so I happened to search online for another solution but I couldn't find anything.
Do we have a solution to this?
I'm using Free Pascal.

A: Copy will copy any array of X to another array of X. If X is AnsiString, it will copy (or slice) to an array of AnsiString.
The following proof project shows that the result is an array of AnsiString, as it addresses each individual "character". If the result were a UnicodeString, you would see only the first character (e.g. 'One' would be the single "bytes" 'O'#0'n'#0'e'#0#0#0, so the loop would stop after the 'O').
program Project1;

uses
  SysUtils;

type
  TAnsiStringArray = array of AnsiString;

procedure Main;
var
  A, B: TAnsiStringArray;
  I: Integer;
  P: PAnsiChar;
begin
  A := TAnsiStringArray.Create('Zero', 'One', 'Two', 'Three');

  { Plain Copy, nothing special: }
  B := Copy(A, 1, 2);  { Copies 'One' and 'Two' }

  for I := Low(B) to High(B) do
  begin
    P := PAnsiChar(B[I]);
    while P^ <> #0 do
    begin
      Write(P^, '-');
      Inc(P);
    end;
    Writeln;
  end;
end;

begin
  Main;
  Readln;
end.

Output:
O-n-e-
T-w-o-

So there is no need to do anything special. Just use Copy as it is.

FPC 3.0.0 on Windows.


text:
Q: XML Schema Migration I am working on a project where we need to save data in an XML format.  The problem is, over time we expect the format / schema for our data to change.  What we want to be able to do is to produce scripts to migrate our data across different schema versions.  We distribute our product to thousands of customers so we need to be able to run / apply these scripts at customer sites (so we can't just do the conversions by hand).  I think that what we are looking for is some kind of XML data migration tool.  In my mind the ideal tool could:

*

*Do an "XML diff" of two schema to identify added/deleted/changed nodes.

*Allow us to specify transformation functions.  So, for example, we might add a new element to our schema that is a function of the old elements.  (E.g. a new element C where C = A+B, A + B are old elements).
So I think I am looking for a kind of XML diff and patch tool which can also apply transformation functions.  One tool I am looking at for this is Altova's MapForce .  I'm sure others here have had to deal with XML data format migration.  How did you handle it?
Edit:
One point of clarification.  The "diff" I plan to do is on the schema or .xsd files.  The actual changes will be made to particular data sets that follow a given schema. These data sets will be .xml files.  So its a "diff" of the schema to help figure out what changes need to be made to data sets to migrate them from one scheme to another.

A: "Do an "XML diff" of two schema to identify added/deleted/changed nodes."
XSD's are text, so this is trivial.
However, if you make dramatic structural changes to the XSD's, the automated diff will be largely useless.
If you make small, cosmetic changes to the XSD's, this might be helpful.
"Allow us to specify transformation functions..."
Wouldn't that be nice.  Sadly, the odds of there being some trivial change ("new element C where C = A+B, A + B are old elements") are almost nil.  Why make that kind of trivial change?
No, when you "... distribute our product to thousands of customers", you don't make trivial, cosmetic changes.  You save up the changes so that they are truly epic, and "create significant value."
No, the odds of there being an automated schema migration is nearly zero.
Instead, design for migratability.

*

*Be sure that the version number is prominent in your XSD paths.  Ideally, in the XSD name itself.

*Each XSD change is a Serious Governance Issue (SGI™).  Everyone participates.  And you write the migration scripts right then and there.  Not afterwards.  Not with tools.  But as part of an XSD change.
Schema don't spontaneously change.  Someone changes them for a reason.  That someone can specify the changes so someone else can write (or update) the migration script.
This is far, far too serious to trust to "automated" tools.  This requires real brains of real people really focusing on this as if their jobs depended on it.

A: I ended up writing a tool to do this and released the result as a SourceForge project.
What:
This tool helps create scripts to migrate XML data from one version of an XML schema to a later version of the same schema. The tool creates these scripts by differencing XSD files and emitting XSLT 2.0 to automatically migrate XML data.  This works well for simple data changes and can be used as "starter" code for more complex data changes.
Where:
https://sourceforge.net/projects/xsdevolver/
Background:
The company I work for sells a shrink-wrapped application where we save a workbook in an XML format according to a specified XSD schema.  Over time, we expect the format of this schema to change. We wanted a way to help us diff schema versions as they evolve over time and generate initial XSLT to migrate data from older versions of the schema to newer versions of the schema.
Usage:
XMLSchemaEvolver  SchemaVersion1.xsd SchemaVersion2.xsd
Output:

*

*A schema diff showing what elements have been changed

*XSLT to translate XML data from SchemaVersion1 to SchemaVersion2
How does it work?
The basic idea is this:
1)      Do a diff of two xml schema (xsd) files.
2)      Each change is classified as an INSERT, DELETE, MOVE or RENAME operation.
3)      For each of these operations, emit simple XSLT to carry out the desired data change.
4)      These data change operations are modeled after a set of standard XSLT operations suggested by Jesper Tverskov link text.  A full list of the transformations emitted by our code can be found XSLT Transformations.txt in the documentation folder.

A: As @S.Lott says, the ability to automate transformations is unlikely.  However, XSLT is a fantastic tool for formally defining how to transform XML from one format to another.  It can't be automatically generated (as far as I know), but it's well worth doing things this way.


text:
Q: PyDev/Eclipse/Python not showing all methods of a class Running Eclipse (Galileo) with PyDev.  I am trying to work with the module urllib2 and I've just started experimenting with it.  One of the tutorials I am going through says to call geturl() on my urllib2.urlopen() class.  So I did, and it worked as expected.
However, I was surprised when I tried to browse the class methods by using Eclipses handy-dandy "ctrl+space" shortcut it only gives me the private methods for what I think are a base class:

When I do dir(page), I get all sorts of neat methods I can play with!
['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', 'code', 'fileno', 'fp', 'getcode', 'geturl', 'headers', 'info', 'msg', 'next', 'read', 'readline', 'readlines', 'url']

Is this an Eclipse problem?  Or a user error?  If I put this in IDLE, I can use IDLE's auto-completion feature to see what methods are available, but I can't get the same functionality to work with PyDev; I believe it is working on my work PC, but my home PC (the one I am at now) seems to be "not normal".
I have looked as best I could on Google/Stackoverflow, but I'm not sure which keywords will return the result that might help me understand what's going wrong here.  Any insight you can provide would be great!
(Python 2.6, running in a Debian (#!) virtual environment, windows7 host - if any of that matters)
NB:  I'm only developing on the Debian side, so I don't have eclipse on Win7.
UPDATE1:
To answer, "what does the browser end with if I scroll down?"  It ends with subclasshook.  See the photo below for what the bottom of the list looks like (it's all private , no methods).

UPDATE2:
As previous post suggested, I went into the preferences menu and checked the autocompletion tabs, and the interpreter preference tab, and nothing seems out of place (but then again, after reading the pydev autocompletion document, I'm not seeing anything about a 'firewall' or any indication that there is one.
However, I did another test, see the image below:

The auto-completion feature for wx works just fine.  Perhaps I misunderstood what was being told to me in previous posts, however, I am understanding that the reason I am seeing magic methods for my page class is because PyDev doesn't know what else to populate it with - so it's obviously confused.  I'm just not sure where to go from here.  I'll keep reading PyDev docs to see if I can figure out in the meantime.
And, I almost forgot - when I "hover" my mouse over urllib2.urlopen() in my code, it does show me the doc string.  Not sure if that provides any insight about this supposed broken functionality.
UPDATE3:
As per someones comment regarding "forced builtins" only auto-completing in PyDev, I went and added "urllib2" to the forced builtins under preferences.  Below is the image of what I am getting...

I have some new methods... but not the ones I expected (ie I am NOT seeing the ones I get from __dict__ when I call dir(page), specifically, geturl()).

A: Most of those are Python's "magic methods":
http://www.rafekettler.com/magicmethods.html
They're special methods you can define on any object to give it custom behavior. Most Python IDEs know not to show them, but Eclipse is being especially helpful.

A: The problem you're running into is a fundamental one with a dynamic language like Python: your IDE has no way of knowing what type of object your page variable refers to. To do that, it would have to know what type urlopen() returns. And there's no way to know that without calling it! It may not even return the same type each time you call it, in which case, what class's methods should it show you?
IDEs can make some guesses, but when these guesses fail, you get results like what you're seeing. It knows you have an object, because everything's an object, so it shows you methods of object.

A: If you read the documentation:

It's important to note that your interpreter must be properly configured for the code-completion to work, and for getting the builtins, PyDev spawns a shell, so, having a firewall can prevent the code-completion from working if it's blocking the communication from eclipse to that shell.

In other words, you have to go into the Preferences and set both the "Code Completion" settings and the "Interpreter - Python" settings, and make sure Eclipse can start a subshell and communicate with it over a socket without a firewall or anything else getting in the way.
My guess is that, of those things, your interpreter setup is most likely to be wrong. Even if your Python is in the usual /usr/bin/python location, you may have PyDev set up to look for, say, /usr/bin/python3, or python26, or "don't guess, always use the #! line or a project-specific setting", or you've installed Python in a per-user location instead of system-wide, or who knows what.
See what you have in the "Interpreter - Python" prefs page, and see if you can run Python the way Eclipse expects to run it. If not, it will not be able to do any command-line completion except the basic stuff that's built in. (As I said elsewhere, I believe that means it can guess that page is of some class type, but it can't tell what type, so it will guess all the standard magic methods that nearly any class object has, and nothing else.)


text:
Q: Network related columns (macaddr, cidr etc.) in Oracle? We have used postgres in our application witch has a very nice set of network related column types along with functions package to operate on them.
And those columns, like macaddr, cidr etc. are extremely important, as they're used as a PKs or indexes in many tables.
(App is an cable modems provisioning system)
We're forced to move to the oracle instance, is there any way to force oracle to easily operate on network related column datatypes?
How we can handle with ie. getting mac addresses in different textual representations, from various dependent components?

*

*xx.xx.xx.xx.xx.xx

*xx.xx.x.x.xx.xx

*xxxx.xxxx.xxxx (cisco way)

*xxxxxxxxxxxx

same with cidrs etc.
Till now, postgres was able to handle that cases in very efficient and nice way...
(I'm new in Oracle RDBMS)

A: There are no native datatypes or supplied packages in Oracle for dealing with network structures like this that I am aware of. You'll likely have to create your own TYPE, perhaps using some of Oracle's Object Type functionality. This would seem to be a nice fit for the feature.
Here's an overview.


text:
Q: Binding a decimal value with InvariantCulture I have a TextBox which is bound to a decimal property.
Our requirment is to have a InvariantCulture behaviour.
When a user types 6.30, the value needs to be 6,30
If a user types 6,30, the value needs to be 6,30
Currently the binding sets the value to 630 when a dot is used.
Is this possible?

A: Your requirement is in fact not the behavior of InvariantCulture. You want to allow users to type in both forms of number with decimal point being either . or ,. This kind of dynamic expression of course should need some custom converter. Try this custom converter:
public class MultiCultureNumberConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                          System.Globalization.CultureInfo culture)
    {
        var ci = System.Globalization.CultureInfo.InvariantCulture.Clone()
                 as System.Globalization.CultureInfo;
        ci.NumberFormat.NumberDecimalSeparator = ",";
        return ((decimal)value).ToString(ci);
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                              System.Globalization.CultureInfo culture)
    {
        var ci = System.Globalization.CultureInfo.InvariantCulture.Clone() as
                 System.Globalization.CultureInfo;
        var s = System.Convert.ToString(value);
        decimal d;
        if (decimal.TryParse(s, System.Globalization.NumberStyles.Number
                  ^ System.Globalization.NumberStyles.AllowThousands, ci, out d))
        {
            return d;
        }
        else
        {
            ci.NumberFormat.NumberDecimalSeparator = ",";
            if (decimal.TryParse(s, System.Globalization.NumberStyles.Number
                ^ System.Globalization.NumberStyles.AllowThousands, ci, out d))
              return d;
        }
        return Binding.DoNothing;
    }
}


text:
Q: Do all apps start with a normal priority on the system monitor? I noticed that on my system monitor, one of my processes, titled pulseaudio, had a very high priority, while all of my other running apps had a normal priority. I don't recall ever changing it, so it must have been its default priority, right? Are there any other apps like this?

A: Technically, yes. In Linux — Ubuntu's kernel — all programs start with a priority or "niceness" value of 0. They may, while executing, request a higher or lower priority by making the system call nice(int niceness) from unistd.h.
Normally, programs the user runs only have the permission to lower their priority to positive niceness. This is useful for non-critical janitorial tasks your computer performs from time to time.
However, Ubuntu also uses a framework called AppArmor, which grants specific user programs administrative ("root") level rights. Ubuntu's AppArmor is configured to allow certain important programs to request a high priority (negative niceness), most notably PulseAudio. This prevents breaks in playing audio while your system is under heavy load.
In summary, yes all applications start with a normal priority. However, in practice, many applications request a different priority immediately after launching.
And as a little geeky addendum
You can start (or to be technically accurate, fork) your own programs with low/high priority in a commandline like this:
nice -n 10 my_app                 # this application is low priority, very nice
sudo nice -n -10 my_other_app     # this application is high priority, very mean

No guarantees they'll keep it, of course.

A: Usually there's a pretty good reason why some process have an elevated priority – PulseAudio handles audio mixing, high priority reduces audio drop outs.
However PulseAudio is mostly an exception. You need root permissions to boost process' priority, so you probably won't see any other such processes owned by a regular user.
There are many system processes and threads running with maximum priority (you can see them in System Monitor by switching to View > All Processes), but there's no need to be concerned about those.


text:
Q: How can I stop "Cascade Delete" from being silently removed by Entity Framework? I have a cascade delete set in my database. I have also set a cascade delete for the corresponding relationship in my EDMX model.
However if I delete the tables with the relationship from the EDMX and then add them back in through "Update Model From Database" - the cascade has been removed.
Craig Stuntz in a related question suggests that it is a feature, however if my cascades are being silently removed each time I do an update of the model - that's unworkable.
Perhaps I need to change my workflow and not delete and re-add tables in the EDMX, rather just make all the little individual column changes by hand?

A: If you delete anything from your model you also delete all your changes. Your changes are gone and EDMX doesn't know about them any more. Once you add tables again you must do all your changes again as well.
If you want to keep your changes don't delete your entities and instead run wizard directly. It should just update existing entities without removing most of your changes. I'm aware only about single example where this doesn't work and your changes are lost and that relates to renaming some navigation properties.


text:
Q: Node production build is failing because of missing devDependecies I have a node app that has devDependecies. Some of the devDependecies are needed for the actual build process, but not the application itself. This means when I install for production, those packages are not installed so the build will fail. My current production build script does the following:

*

*Cleans (so removes node_modules)

*yarn install –production

*Copies the app to a dist folder

*Zips the application

Steps 3 and 4 contain node packages from devDependecies to copy and zip. The problem is when you install for production, those packages are not install so the build would fail. The goal for this build is to make it cross-platform (hence the reason for using node modules to copy and zip) and make it so it requires no additional steps to build. Meaning we don't want to require packages to be installed globally for steps 3 and 4 to work.
Is there a common best practice to solve for this or am I missing something in the build process?
I had to install the packages needed for the build process globally, but that is not ideal. It should be self contained.


text:
Q: how to add trigger to count number of rows automatically after inserting in oracle sql developer I want to add trigger to count number of movies after inserting!
This is the table to store the count value:
CREATE TABLE mov_count
  (mcount NUMBER);

and the movie table:
create table movie
  (mov_id number primary key,
   mov_title varchar(20),
   mov_lang varchar(20));

This is the trigger I have created:
create trigger count_movie_trg
after insert on movie
for each row
BEGIN

  UPDATE mov_count
  SET    mcount = (SELECT COUNT(*) FROM movie);

END;
/

After creating this i tried to add movie but its showing mutating trigger/function may not see it error.

A: Why not just maintain the value without referring to the original table?
create trigger count_movie_trg after insert on movie for each row
begin
    update mov_count set mcount = mcount + 1;
end;

To keep the count up-to-date, you'll need a delete trigger as well.

A: It is the FOR EACH ROW that bothers you. It is a table-level trigger, so:
Enter a dummy value for beginning (as you'll update it later):
SQL> insert into mov_count values (0);

1 row created.

Trigger:
SQL> create or replace trigger count_movie_trg
  2    after insert on movie
  3  begin
  4    update mov_count c set
  5      c.mcount = (select count(*) from movie m);
  6  end;
  7  /

Trigger created.

Testing:
SQL> insert into movie
  2    select 1, 'Titanic' from dual union all
  3    select 2, 'Superman' from dual;

2 rows created.

SQL> select count(*) from mov_count;

  COUNT(*)
----------
         1

SQL>

A: Don't use the table at all; use a view instead.
CREATE VIEW mov_count ( mcount ) AS
  SELECT COUNT(*) FROM movie;

db<>fiddle


text:
Q: Changing a container color when container is tapped using gesturedetector in flutter Hello i have been stock here trying to figure out what am doing wrong, the male and female reuseable cards are surpose to change color when tapped but after placing the GestureDetector inside my card Class it stopped working. The color refuse to change when tapped, take a look at the code below.
import 'package:bmi_calculator/card_icon.dart';
import 'package:bmi_calculator/cards.dart';
import 'package:flutter/material.dart';

Color activeCardColor = const Color(0XFF1D1E33);
Color inactiveCardColor = const Color(0XFF111328);
Color buttomContainerColor = const Color(0xffeb1555);
const double buttomContainerHeight = 70.0;

enum Gender {
  male,
  female,
}

class InputPage extends StatefulWidget {
  const InputPage({Key? key}) : super(key: key);

  @override
  _InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {
  Gender? selectedGender;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('BMI CALCULATOR'),
        ),
        body: Column(
          children: [
            Expanded(
              child: Row(
                children: [
                  Expanded(
                    child: ReuseableCard(
                      ontapped: () {
                        setState(() {
                          selectedGender = Gender.male;
                        });
                      },
                      colour: selectedGender == Gender.male
                          ? activeCardColor
                          : inactiveCardColor,
                      cardChild: const CardIcon(Icons.male, 'Male'),
                    ),
                  ),
                  Expanded(
                    child: ReuseableCard(
                      ontapped: () {
                        setState(() {
                          selectedGender = Gender.female;
                        });
                      },
                      colour: selectedGender == Gender.female
                          ? activeCardColor
                          : inactiveCardColor,
                      cardChild: const CardIcon(Icons.male, 'Female'),
                    ),
                  )
                ],
              ),
            ),
            Expanded(
              child: ReuseableCard(
                colour: activeCardColor,
              ),
            ),
            Expanded(
              child: Row(
                children: [
                  Expanded(
                    child: ReuseableCard(
                      colour: activeCardColor,
                    ),
                  ),
                  Expanded(
                    child: ReuseableCard(
                      colour: activeCardColor,
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 10.0),
              color: buttomContainerColor,
              height: buttomContainerHeight,
              width: double.infinity,
            )
          ],
        ));
  }
}

And here is my Card Class
import 'package:flutter/material.dart';

class ReuseableCard extends StatelessWidget {
  final Color? colour;
  final Widget? cardChild;
  final void Function()? ontapped;

  const ReuseableCard({this.colour, this.cardChild, this.ontapped});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        ontapped;
        print('Button Pressed');
      },
      child: Container(
        child: cardChild,
        margin: const EdgeInsets.all(10),
        width: double.infinity,
        decoration: BoxDecoration(
          color: colour,
          borderRadius: BorderRadius.circular(10.0),
        ),
      ),
    );
  }
}

A: add brackets to the function call
onTap: () {
    ontapped(); // here
    print('Button Pressed');
  },

A: The problem is in passing the ontapped function. When you simply place ontapped without Parenthesis () the function will not be called so you need to change that in following ways. When using Lambda function you have options to pass function
For multiple functions
onTap: () {
    ontapped(); // here
  },

For single function
onTap: ontapped, // here


text:
Q: Numpy array using values of an object I have an object -> {0: 0.8, 1: 0.2, 2: 0, 3: 0}
I want to convert it to a numpy array, where the keys are the index, and the values are the values of the array -> [0.8, 0.2, 0, 0]
Whats the fastest and efficient way of doing this?
I am using a for loop, but is there a better way of doing this?

A: Assuming your dictionary is called dict:
numpy_array = np.array([*dict.values()])

A: keys, items and values are the fastest way to get 'things' from a dict.  Otherwise you have to iterate on the keys.  A general approach that allows for skipped indices, and out-of-order ones:
In [81]: adict = {0: 0.8, 1: 0.2, 2: 0, 3: 0}
In [82]: keys = list(adict.keys())
In [83]: arr = np.zeros(max(keys)+1)    # or set your own size
In [84]: arr[keys] = list(adict.values())
In [85]: arr
Out[85]: array([0.8, 0.2, 0. , 0. ])

A: The above answer gives dict_values, but was in the right direction
the correct way to do it is:
d = {0: 0.8, 1: 0.2, 2: 0, 3: 0}
np_array = np.array(list(d.values()))

A: Dictionary is inherently orderless. You would need to sort your values according to your keys (assuming you do not have a missing key in your dictionary):
a = {0: 0.8, 1: 0.2, 2: 0, 3: 0}
np.array([i[1] for i in sorted(a.items(), key=lambda x:x[0])])

Another way of doing it is sorting in numpy:
b = np.array(list(a.items()))
b[b[:,0].argsort()][:,1]

output:
[0.8, 0.2, 0, 0]

A: A solution if input dict is not ordered or has missing values:
d = {1:1.1, 2:2.2, 0: 0.8, 4:4.4}
sz = 1+max(d.keys())   # or len(d) if you are sure there are no missing values
x = np.full(sz, np.nan)
x[list(d.keys())] = list(d.values())
x
#array([0.8, 1.1, 2.2, nan, 4.4])


text:
Q: Lorentz transformation, the one-dimensional wave equation I am struggling with a solution to this question, I don't really understand what it means about the three conditions on the coefficients $A$, $B$, $C$ and $D$.
Question:
The one-dimensional wave equation
$ \frac{\partial^{2}u}{\partial x^{2}} - \frac{\partial^{2}u}{\partial t^{2}} = 0$
is subjected to a change of coordinates $u(x, t) = v(\xi, \tau )$, where new coordinates $\xi, \tau$ are linear functions of the old coordinates,
$\xi = Ax + Bt,$ $\tau = Cx + Dt, $
and $A$, $B$, $C$ and $D$ are positive constants. The transformation is chosen so that the new equation is the same as before, up to the names of the variables, i.e.
$ \frac{\partial^{2}v}{\partial\xi^{2}} - \frac{\partial^{2}v}{\partial\tau^{2}} = 0$
State the three conditions on the coefficients $A$, $B$, $C$ and $D$ that are necessary and sufficient to ensure this property.
Let $A = \cosh \varphi$ where $\varphi > 0$. Find $B$, $C$ and $D$ in terms of $\varphi$.

A: Since $$\partial_x=\partial_x\xi\partial_\xi+\partial_x\tau\partial_\tau=A\partial_\xi+C\partial_\tau,\,\partial_t=B\partial_\xi+D\partial_\tau,$$the wave equation is $$0=(A\partial_\xi+C\partial_\tau)(A\partial_\xi u+C\partial_\tau u)-(B\partial_\xi+D\partial_\tau)(B\partial_\xi u+D\partial_\tau u)\\=((A^2-B^2)\partial_\xi^2+2(AC-BD)\partial_\xi\partial_\tau+(C^2-D^2)\partial_\tau^2)u.$$The desired conditions are $A^2-B^2=1,\,AC-BD=0,\,C^2-D^2=-1$. With $A=\cosh\varphi$ we have $B=\pm\sinh\varphi,\,C=B,\,D=A$.


text:
Q: Update multiple columns with the selected value from multi select dropdown in MVC I have a multi dropdown list in mvc, I need to save the selected value in the same table but a different column in sql server
1.Fruits
    -Fruits A
        *Fruits B

table A
-------------------------
Fruits   |  Fruits 1
-------------------------
Fruits A | Fruits B

A: You can pass the selected values as comma separated like (Fruits1,Fruits2 etc). Then in SQL you can split up the Comma separated string as per your table columns.
Latest version SQL support the split functionality as default.


text:
Q: Autolayout animate x/y position of UIView without changing width/height I'm trying to get used to animation with Autolayout and constraints instead of animation with frames. In my project I have a UIView near the top of the screen that I'm trying to animate straight downward (y position). I understand that I must modify the constraint constant value, but doing so decreases the height of my view instead of "pushing" it downward like I'm wanting. Here's my code:
self.topConstraint.constant = 180;

[UIView animateWithDuration:0.5f animations:^{
    [self.theView layoutIfNeeded];
} completion:^(BOOL finished) {

}];

topConstraint is a vertical space constraint between the top of the ViewController's view and theView.
Other constraints on theView include:

*

*Center X Alignment

*Horizontal Space

*Vertical Space (self.topConstraint)

*Vertical Space (represents the space between theView and the bottom of the ViewController's view)

*Pinned width

*Pinned height
How do I modify the constraint values to simply change the position of theView without affecting its width/height?

A: You should remove the constraint:

Vertical Space (represents the space between theView and the bottom of the ViewController's view)

because you don't want the height to change (you have it pinned) and you are specifying the x (centre constraint) and y (other vert constraint) positions with other constraints so it isn't required.
Your Horizontal Space constraint may also not be required (because you have a Center X Alignment constraint) - the horizontal space could be required, but more likely on the view that this one is centred on.


text:
Q: How can I get reason of Resharper's aborted tests? I'm using Resharper 9.2 and NUnit 2.6.4 and ~120 unit tests. Sometimes when I start run tests resharper stops at random test and set it status to Aborted and skip the others. It is very inconvenient because I have manually run rest of tests.
Are there any ways to get reason of Abortion, some resharper test run logs or something in NUnit to help solve my problem?
I also tried to use native NUnit runner but it sometimes throws exception which doesn't contain any useful info (some remoting exception which tells nothing useful)
I've tried to set "Run up to 1 assemblies in parallel" and "Use separate AppDomain for each assembly with tests" but it doesn't help.
UPD
I've reproduced this in debug mode, debug unit test just shut down and in output window I've found:
The program '[4572] JetBrains.ReSharper.TaskRunner.CLR4.exe: Program Trace' has exited with code 0 (0x0).
The program '[4572] JetBrains.ReSharper.TaskRunner.CLR4.exe: Managed (v4.0.30319)' has exited with code -1073741819 (0xc0000005) 'Access violation'.

It seems that problem is external's library unsafe code.

A: I also ran into a case where Resharper decided to consistently abort a test. It didn't call into unmanaged or anything freaky.
The answer was that it had an inadvertent recursive call resulting in a stackoverflow exception. This was evident when I decided to "debug" instead of "running" them.
So I assume that the general takeaway is that "aborted" tests is symptomatic that something went wrong, but the error did not result in an exception being thrown from the code itself, but from the CLR or something.

A: It seems that resharper has nothing to do in this case. I've got Access Violation error and in this case tester process will be shut down. There is no way in .net to process this error because it is not on managed level. The only thing is to check in output window if error message is like: "The program '[4572] JetBrains.ReSharper.TaskRunner.CLR4.exe: Managed (v4.0.30319)' has exited with code -1073741819 (0xc0000005) 'Access violation'" when your tests are aborted for no reason.
If you have access to native code you can debug.
In my case the problem was in improper use of COM object and Dispose() method. I've fixed it and everything is ok now - no "silent" abortion.

A: I had only one test that basically didn't run any code except set an integer value.  I was just adding my firsts tests getting my unit tests set up so I quickly added a setup() and a create() test.
Every time I ran I got the tests aborted error.

Debug Failed
Debug breakpoint would not even stop inside the [Setup]TestSetup() method.
I removed both the TestSetup() and the [Test] void Create() method and it would run but of course give inconclusive as the result.
I added the [SetUp] TestSetup() method back in and it didn't abort either.  I added the [Test] void Create() method back in again and it started aborting again with no ability to break.
Finally, I saw the problem.  Do you see the problem?
[SetUp]
public void TestSetup()
{
    string test = "this thing";
}

[Test]
void Create()
{
    int x = 5;
    string s1 = "super";
}

Spoiler
Oops, I forgot to set the Create() method to public.


text:
Q: AAD application permissions to enable creating other AAD application What OAuth API and permissions  are required by an AAD application so that I can use it to authorize creating new AAD application as described in this example

A: You can give the app this permission on the Azure AD Graph API:

Manage apps that this app creates or owns

It is an app permission that allows the app to create applications and manage them. It does not allow it to manage other applications.
I created an app with this app permission, granted the permissions, got a token with client credentials flow and was able to create an app in my directory. So can confirm it should work once you get the permission granted.


text:
Q: Django rest how to do pagination with PageNumberPagination I wrote the following codes. But when I go to the url posts?page=1, it still shows all of the Post model objects. What should I do?
settings.py
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

ursl.py
path('posts', views.posts_view, name='posts_view')

views.py
@api_view(['GET'])
def posts_view(request):
    posts = Post.objects.all()
    serializer = PostSerializer(posts, many=True)
    return Response(serializer.data)

A: You are writing an function based view, so that is why you need to do everything manually.  If possible, you should rely on the provided generic base api views instead of attempting to re-write this:
class PostView(generics.ListAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

path('posts', PostView.as_view(), name='posts_view')

To do it manually you are going to need to create and invoke the pagination just like the base classes do:
def my_view(request):
    qs = Post.objects.all()
    pagination = PageNumberPagination()
    page = pagination.paginate_queryset(qs, request)
    serializer = PostSerializer(page, many=True)
    return pagination.get_paginated_response(
        serializer.data
    )


text:
Q: What's the difference between - and -- in a phrase?
Possible Duplicate:
When should I use an em-dash, an en-dash, and a hyphen?

When do I put a - in a sentence? Is it a more powerful comma? With a bigger pause?

A: The dashes you described are known respectively as the en-dash and the em-dash. To describe the difference between their origins, Mental Floss writes:

An en dash (–) is bigger than a hyphen but shorter than an em dash (—). Th e names come from an obscure typographical measurement system, but the dashes have now taken on a life of their own in grammar. The em dash is the spork of English grammar: It ain't particularly pretty, but you can use it for most anything. Em dashes can replace colons or sets of parentheses, or represent a sudden change in thought or tone.

So when do you use an en-dash? Again from Mental Floss:

*

*To show numerical ranges, signifying "up to and including"—of dates, ages, pages, etc. (Example: "I read pages 7–22 last night.")

*The storied "compound adjective hyphen," an event so rare in the English language that proofreaders shiver with excitement whenever they come across it. Basically "pro-American" gets a regular hyphen because "American" is only one word, whereas "pro–Falkland Islands" gets an en dash because "Falkland Islands" is two words. So, too phrases like "Civil War–era."

What about an em-dash? From here:

Similar to an extended hyphen (-), an em dash is used to show a break in thought or a shift of tone.

If you'd like to read more about the differences between a hyphen (-), en-dash (–), and em-dash (—), see the blog post here which summarizes the above.


text:
Q: How to install NumPy and Pandas with my current python setup? I am just starting to learn Python in a big hurry (had a positive job interview, was told 'learn Python, NumPy, and Pandas and be ready to take a test on that stuff in 3 weeks'). After my first online Python course, I now have Python 3.8.3 installed along with the Komodo editor.

*

*What steps do I take to get NumPy and Pandas installed and going ?

*Can I do interactive (shell) work with Komodo ?

No time to hack around. Appreciate all help.

A: Go to terminal.

*

*Type pip install numpy and wait for installation to finish

*Type pip install pandas and wait for installation to finish

*Head over here to get started with using NumPy and Pandas


text:
Q: Difficulty separating ranks in graphviz python package I'm trying to create a neural network graph using the graphviz Python package, and I'm running into issues trying to prevent rank overlap among other things. I'm specifically asking about preventing rank overlap in this post.
This is the code I have so far,
from graphviz import Graph

d = Graph(name="Network Graph",graph_attr={'rankdir':'TD'},engine='dot')

with d.subgraph() as s:
    s.attr(rank='same')
    s.node('density','density')
    s.node('te','Elec. Temp.')
    s.node('tr','Rad. Temp.')
    s.node('alpha','alpha')

layer0 = ['density','te','tr','alpha']
layer1 = []
layer2 = []
layer3 = []
layer4 = []
layer5 = []
allLayers =[ layer0, layer1, layer2, layer3, layer4, layer5 ]

with d.subgraph() as s1:
    s1.attr(rank='same')
    for i in range(1,7):
        layer1.append('a1%i'%i)
        s1.node('a1%i'%i,'',tailclip='true',headclip='true')

with d.subgraph() as s2:
    s2.attr(rank='same')
    for i in range(1,10):
        layer2.append('a1%i'%i)
        s2.node('a1%i'%i,'',tailclip='true',headclip='true')

with d.subgraph() as s3:
    s3.attr(rank='same')
    for i in range(1,3):
        layer3.append('a1%i'%i)
        s3.node('a1%i'%i,'',tailclip='true',headclip='true')

with d.subgraph() as s4:
    s4.attr(rank='same')
    for i in range(1,7):
        layer4.append('a1%i'%i)
        s4.node('a1%i'%i,'',tailclip='true',headclip='true')

with d.subgraph() as s5:
    s5.attr(rank='same')
    for i in range(1,14):
        layer5.append('a1%i'%i)
        s5.node('a1%i'%i,'',tailclip='true',headclip='true')

edges = []
d.attr(rankdir="LR",splines='line',ranksep='2.0',overlap='false')
for n in range(0,len(allLayers)-1):
    # d.attr(rankdir="LR",splines='line',ranksep='2.0',overlap='false')
    for i in allLayers[n]:
        for j in allLayers[n+1]:
            # edges.append((i,j))
            d.edge(i,j,directed="False")

print(d.source)

d.render('network.pdf',view=True)

This produces this is image

I have no idea as to why I'm able to separate ranks/layers 0 and 1 but then all subsequent layers stack on top of layer1. For some reason the line d.attr(rankdir="LR",splines='line',ranksep='2.0',overlap='false') appears to only apply once, but when I place the line inside the for loop, it behaves the same.
The documentation for the graphviz package leaves much to be desired, and there is very little help for Python Graphviz floating around the internet that I could find. Also, one apparently cannot place d.attr(rankdir='LR') immediately after the creation of the Graph() object. It had to be placed after the creation of all of the nodes, so order apparently matters.
FYI: I've also attempted to add the parameter overlap='false' in various places, but that didn't change behavior at all in the ways that I've used it.
How do I separate the ranks? Are there any other general tips with working with Graphviz particularly in terms of how to properly order commands and set attributes?

A: Glad to see that you solved your problem. But you might find the following changes helpful. Have a look at them.

*

*Name each of your subgraphs

*Use different names for your nodes (which you already realized)

*Use a directed graph instead

*You can in fact set all the graph attributes while instantiating

from graphviz import Digraph

d = Digraph(name="Network Graph",
          graph_attr={'rankdir':'LR', 'splines':'line','ranksep':'2.0','overlap':'false'},
          engine='dot')

with d.subgraph(name='s') as s:
    s.node('density','density')
    s.node('te','Elec. Temp.')
    s.node('tr','Rad. Temp.')
    s.node('alpha','alpha')

layer0 = ['density','te','tr','alpha']
layer1 = []
layer2 = []
layer3 = []
layer4 = []
layer5 = []
allLayers =[ layer0, layer1, layer2, layer3, layer4, layer5 ]

with d.subgraph(name='s1') as s1:
    s1.attr(rank='same')
    for i in range(1,7):
        layer1.append('a1%i'%i)
        s1.node('a1%i'%i,'',tailclip='true',headclip='true')

with d.subgraph(name='s2') as s2:
    s2.attr(rank='same')
    for i in range(1,10):
        layer2.append('a2%i'%i)
        s2.node('a2%i'%i,'',tailclip='true',headclip='true')

with d.subgraph(name='s3') as s3:
    s3.attr(rank='same')
    for i in range(1,3):
        layer3.append('a3%i'%i)
        s3.node('a3%i'%i,'',tailclip='true',headclip='true')

with d.subgraph(name='s4') as s4:
    s4.attr(rank='same')
    for i in range(1,7):
        layer4.append('a4%i'%i)
        s4.node('a4%i'%i,'',tailclip='true',headclip='true')

with d.subgraph(name='s5') as s5:
    s5.attr(rank='same')
    for i in range(1,14):
        layer5.append('a5%i'%i)
        s5.node('a5%i'%i,'',tailclip='true',headclip='true')

for n in range(0,len(allLayers)-1):
    for i in allLayers[n]:
        for j in allLayers[n+1]:
            d.edge(i,j,directed="False")

# print(d.source)

# d.render('network.pdf',view=True)

You might also find the following links helpful
https://logicatcore.github.io/scratchpad/machine%20learning/jupyter/graphviz/2020/12/26/Graphviz-Neural-Networks-visualisation.html
https://github.com/martisak/dotnets

A: The issue that I found was that I had failed to change the node names because of copy-pasta. I previously had a1%i'%i for the labels in the generation of each layer. The fix, of course, was to change the 1 in each of the subsequent layers to an integer corresponding the layer number.


text:
Q: OutOfMemoryException while while opening OracleConnection A coworker and I got the task to fix an problem on a SQL-Client.
The error is a System.OutOfMemoryException.
I figured that it could be because of the client has to many connections that doesn't get closed properly.
I tested a bit around but I can't seem to get it working.
Anyone have a suggestion?
This is the code where the error happens:
        public void SQLIntoDataGridView(OracleCommand cmd, int startIndex, int maxIndex, int ersteSpalte, int maxSpalten, DataTable datenTabelle, DataGridView dgv, int sqlNr, DataTable dt)
    {
        OracleConnection test = new OracleConnection();

        int i = 0;
        int j = 0;
        int spalten = ersteSpalte;
        int id;
        int spaltenZaehler = ersteSpalte;
        int maxrows = datenTabelle.Rows.Count;
        int readZeile = 0;
        int writeZeile = 0;
        int startrow = 0;
        int startSpalte = 0;
        int endSpalte = 0;

        Stopwatch watch = new Stopwatch();
        watch.Start();

        test.ConnectionString = "Data Source=; User ID=; Password=";

        using (test)
        {

            if (test.State == ConnectionState.Closed)
                test.Open(); // <-- this is where the error occures

            using (OracleDataReader reader = cmd.ExecuteReader())
            {
                datenTabelle.Load(reader);
                dataGridViewErgebnis.DataSource = dt;
                dataGridViewTest.DataSource = datenTabelle;
                dataGridViewErweitern(sqlNr);
                #region Rechnungsempfänger X
                if (startIndex == 27 || startIndex == 24)
                {
                    while (j < dataGridViewErgebnis.Rows.Count - 1)
                    {
                        id = startIndex;
                        if (dataGridViewErgebnis.Rows[j].Cells[21].Value.ToString() == "")
                        {
                            readZeile++;
                            i = readZeile;
                            j++;
                            writeZeile++;
                        }
                        else if (dataGridView1.Rows[startrow].Cells[0].Value.ToString() == dataGridViewErgebnis.Rows[j].Cells[21].Value.ToString())
                        {
                            if (startIndex == 24)
                            {
                                startSpalte = 7;
                                endSpalte = 9;
                                spaltenZaehler = startSpalte;
                            }
                            else if (startIndex == 27)
                            {
                                startSpalte = 10;
                                endSpalte = 14;
                                spaltenZaehler = startSpalte;
                            }
                            spaltenZaehler = startSpalte;
                            maxSpalten = endSpalte;
                            while (spaltenZaehler <= maxSpalten)
                            {
                                i = startrow;
                                dataGridViewErgebnis.Rows[writeZeile].Cells[id].Value = dgv.Rows[i].Cells[spaltenZaehler].Value.ToString();
                                spaltenZaehler++;
                                id++;
                            }
                            readZeile++;
                            i = readZeile;
                            j++;
                            writeZeile++;
                            spaltenZaehler = startSpalte;
                            startrow = 0;
                        }
                        else
                        {
                            startrow++;
                        }
                        if (i == dt.Rows.Count - 1 && j == datenTabelle.Rows.Count - 1)
                        {
                            id = startIndex;
                            while (id <= maxIndex && spaltenZaehler <= maxSpalten)
                            {
                                dataGridViewErgebnis.Rows[writeZeile].Cells[id].Value = dataGridViewTest.Rows[i].Cells[spaltenZaehler].Value.ToString();
                                id++;
                                spaltenZaehler++;
                            }
                        }
                    }
                }
                #endregion
                else
                {
                    while (i < dt.Rows.Count - 1)
                    {
                        id = startIndex;
                        if (dataGridViewErgebnis.Rows[i].Cells[0].Value.ToString() == dataGridViewTest.Rows[j].Cells[0].Value.ToString())
                        {
                            while (spaltenZaehler <= maxSpalten)
                            {
                                dataGridViewErgebnis.Rows[i].Cells[id].Value = dataGridViewTest.Rows[j].Cells[spaltenZaehler].Value.ToString();
                                spaltenZaehler++;
                                id++;
                            }
                            if (startIndex == 10 && j == datenTabelle.Rows.Count - 1)
                            {
                                j--;
                                j--;
                                i++;
                            }
                            if (j <= datenTabelle.Rows.Count - 1)
                            {
                                j++;
                            }
                            spaltenZaehler = ersteSpalte;
                        }
                        else
                        {
                            i++;
                            while (id <= maxIndex)
                            {
                                dataGridViewErgebnis.Rows[i].Cells[id].Value = "";
                                id++;
                            }
                        }
                        if (i == dt.Rows.Count - 1 && j == datenTabelle.Rows.Count - 1)
                        {
                            id = startIndex;
                            while (id <= maxIndex && spaltenZaehler <= maxSpalten)
                            {
                                dataGridViewErgebnis.Rows[i].Cells[id].Value = dataGridViewTest.Rows[j].Cells[spaltenZaehler].Value.ToString();
                                id++;
                                spaltenZaehler++;
                            }
                        }
                        else if (j == datenTabelle.Rows.Count && startIndex != 10)
                        {
                            j--;
                            if (i <= dt.Rows.Count - 2)
                            {
                                i++;
                            }
                        }
                    }
                }
                watch.Stop();
                StoppUhr(watch);
            }
        }
    }

A: I would rewrite the code like this.
.
.
.
OracleConnection test = new OracleConnection();
.
.
.

        using (OracleConnection test = new OracleConnection("Data Source=; User ID=; Password=")) // <-- SQLconnection here
        {

            test.Open(); // <-- Only Open connection

            using (OracleDataReader reader = cmd.ExecuteReader())
            {
.
.
.
            }
         }


text:
Q: Static libstdc++ when cross-compiling for ARM while using Qt5 I have a ARM platform with an old libstdc++. I'm cross-compiling the application from other platform and I wanted to use more advanced features of C++ language so I'm linking my libstdc++ statically. I'm using Conan for package manager with plenty of other dynamic libraries and everything is running smoothly.
Problem arises when I try to add a totally new component of the application, which has been written in Qt5. Suddenly the stringstream have stopped working - the app doesn't crash, but the operator<<(int) resets the good bit in the stream.
'objdump -TC' on the executable shows that lot of the libstdc++ functions are now imported (linked dynamically) instead of linked statically.
Example:
0000000000000000      DF *UND*  0000000000000000  Qt_5        std::ostream::operator<<(int)

Notice the version "Qt_5".
I have also disassembled my executable to see that all calls to std::ostream::operator<<(int) are indeed calling imported symbol.
When I have tried to resolve libstdc++ symbols manually before g++ linker with
/usr/bin/aarch64-linux-gnu-ld -r -o out.o main.cpp.o /usr/lib/gcc-cross/aarch64-linux-gnu/7/libstdc++.a

it worked as expected and there weren't any imported symbols related to ostream in the executable anymore and the stringstream works.
Any ideas regarding my situation?
Below is the command for linking executed by CLion. With this combination the application doesn't  work.
/usr/bin/aarch64-linux-gnu-g++-7  -fPIC -static-libstdc++ -Wall -Wextra -pedantic -Weffc++ -Wshadow -Wstrict-aliasing -Woverloaded-virtual -Wdelete-non-virtual-dtor -Wno-unused-function -Wno-missing-braces  -g -rdynamic  -L/enviro/rv-linux/lib-target -L/enviro/rv-linux/targetfs/lib/aarch64-linux-gnu -Wl,-rpath,$ORIGIN/lib -Wl,-rpath,/enviro/rv-linux/lib-target  CMakeFiles/wwrk_core.dir/src/main.cpp.o  -o bin/wwrk_core -Wl,-rpath,/usr/local/ukita-1.2/targets/aarch64-Linux/lib:/usr/local/cuda/targets/aarch64-linux/lib:/usr/local/cuda/targets/aarch64-linux/lib/stubs:/home/wwrk/.conan/data/mosquitto/1.4.15/bincrafters/stable/package/239078edbc0e8a96a9afdcfb7771317f2343a587/lib:/home/wwrk/.conan/data/OpenSSL/1.0.2o/conan/stable/package/7dd5184ee7a9467ffac8b88942d33774d1b75240/lib:/home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/07bff7c90a07530ee2d9520bd150b7df4c4bcfd4/lib:/home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib:/usr/local/ukita/samples/3rdparty/linux-aarch64/special_Xlibs/lib: lib/libAnd_driver.a lib/libAndCore-dw.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_dnn.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_ml.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_objdetect.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_shape.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_stitching.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_superres.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_videostab.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/share/OpenCV/3rdparty/lib/liblibprotobuf.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_calib3d.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_features2d.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_flann.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_highgui.a -lgthread-2.0 /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_photo.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_video.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_videoio.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_imgcodecs.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/share/OpenCV/3rdparty/lib/libIlmImf.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_imgproc.a /home/wwrk/.conan/data/OpenCV/3.4.0/wwrkauto/stable/package/2a79b1e5f5284318af316f0a3dad26795379cec1/lib/libopencv_core.a -lgstbase-1.0 -lgstreamer-1.0 -lgobject-2.0 -lglib-2.0 -lgstvideo-1.0 -lgstapp-1.0 -lgstriff-1.0 -lgstpbutils-1.0 /home/wwrk/.conan/data/jasper/2.0.14/conan/stable/package/06e35b3c6107222c50e1c22eae68c58d483cba15/lib/libjasper.a /home/wwrk/.conan/data/libjpeg/9b/bincrafters/stable/package/e6d649ca4bea46777eed92a123bea4d2c1892ea8/lib/libjpeg.a /home/wwrk/.conan/data/libpng/1.6.34/bincrafters/stable/package/42e51281839943ca78313263055e6869dd2d2f9a/lib/libpng16.a /home/wwrk/.conan/data/libwebp/0.6.1/bincrafters/stable/package/b85d569a3b57b77ebc11d00bbbe398c7753b32be/lib/libwebpdemux.a /home/wwrk/.conan/data/libwebp/0.6.1/bincrafters/stable/package/b85d569a3b57b77ebc11d00bbbe398c7753b32be/lib/libwebp.a /home/wwrk/.conan/data/libwebp/0.6.1/bincrafters/stable/package/b85d569a3b57b77ebc11d00bbbe398c7753b32be/lib/libwebpdecoder.a -lusb-1.0 -ludev /usr/local/ukita-1.2/targets/aarch64-Linux/lib/libukita.so /usr/local/cuda/targets/aarch64-linux/lib/libcudart.so /enviro/rv-linux/targetfs/usr/lib/aarch64-linux-gnu/libgstsdp-1.0.so /enviro/rv-linux/targetfs/usr/lib/aarch64-linux-gnu/libgstvideo-1.0.so /enviro/rv-linux/targetfs/usr/lib/aarch64-linux-gnu/libgstapp-1.0.so /enviro/rv-linux/targetfs/usr/lib/aarch64-linux-gnu/libgstbase-1.0.so /enviro/rv-linux/targetfs/usr/lib/aarch64-linux-gnu/libgstnet-1.0.so /enviro/rv-linux/targetfs/usr/lib/aarch64-linux-gnu/libgstreamer-1.0.so /enviro/rv-linux/targetfs/usr/lib/aarch64-linux-gnu/libgio-2.0.so /enviro/rv-linux/targetfs/usr/lib/aarch64-linux-gnu/libgobject-2.0.so /enviro/rv-linux/targetfs/usr/lib/aarch64-linux-gnu/libglib-2.0.so /usr/local/cuda/targets/aarch64-linux/lib/stubs/libcublas.so -lstdc++fs -lcuda lib/libAndCore-core.a -lpthread -lrt /home/wwrk/.conan/data/mosquitto/1.4.15/bincrafters/stable/package/239078edbc0e8a96a9afdcfb7771317f2343a587/lib/libmosquitto.so /home/wwrk/.conan/data/mosquitto/1.4.15/bincrafters/stable/package/239078edbc0e8a96a9afdcfb7771317f2343a587/lib/libmosquittopp.so -ldl /home/wwrk/.conan/data/OpenSSL/1.0.2o/conan/stable/package/7dd5184ee7a9467ffac8b88942d33774d1b75240/lib/libssl.so /home/wwrk/.conan/data/OpenSSL/1.0.2o/conan/stable/package/7dd5184ee7a9467ffac8b88942d33774d1b75240/lib/libcrypto.so /home/wwrk/.conan/data/zlib/1.2.11/conan/stable/package/8fd38d381db52e2495321ce060b9f457656f6c8f/lib/libz.a /home/wwrk/.conan/data/c-ares/1.14.0/conan/stable/package/8fd38d381db52e2495321ce060b9f457656f6c8f/lib/libcares.a -lm /home/wwrk/.conan/data/yaml-cpp/0.6.2/bincrafters/stable/package/08f0f6b54224d0f59c7a23bfbaa25f463db315ae/lib/libyaml-cpp.a -latomic lib/libAndautoDashboard.a /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt5Location.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt5PositioningQuick.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt5Positioning.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt53DQuick.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt5Quick.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt5Qml.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt53DExtras.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt53DInput.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt5Gamepad.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt53DLogic.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt53DAnimation.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt53DRender.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt53DCore.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/07bff7c90a07530ee2d9520bd150b7df4c4bcfd4/lib/libQt5Network.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt5Widgets.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/e7c3abf447189e454cc0dd043a04a91b61a54baf/lib/libQt5Gui.so.5.11.2 /home/wwrk/.conan/data/Qt/5.11.2/bincrafters/stable/package/07bff7c90a07530ee2d9520bd150b7df4c4bcfd4/lib/libQt5Core.so.5.11.2 -Wl,-Bstatic -lstdc++ -Wl,-Bdynamic -lX11 /home/wwrk/workdir/GST/libs/glfw/libglfw3.a -Wl,-Bstatic -lstdc++ -Wl,-Bdynamic -lX11 /home/wwrk/workdir/GST/libs/glfw/libglfw3.a /usr/local/ukita/samples/3rdparty/linux-aarch64/special_Xlibs/lib/libXcursor.so /usr/local/ukita/samples/3rdparty/linux-aarch64/special_Xlibs/lib/libXi.so /usr/local/ukita/samples/3rdparty/linux-aarch64/special_Xlibs/lib/libXrandr.so /usr/local/ukita/samples/3rdparty/linux-aarch64/special_Xlibs/lib/libXinerama.so /enviro/rv-linux/lib-target/libGLESv2.so.2 /enviro/rv-linux/targetfs/usr/lib/aarch64-linux-gnu/libdl.so -lEGL -lGLU

Thank you for answers.

A: I have found a solution to my problem. I needed to explicitly list static version of standard library on the top of the lib list. It's very far from ideal solution, but now the bin got built as I intended.
if(${CMAKE_CXX_COMPILER} MATCHES ".*aarch64.*")
LIST(APPEND SAMPLE_LIBRARIES
     /usr/lib/gcc-cross/aarch64-linux-gnu/7/libstdc++.a
)
endif()
...
#other libraries here


text:
Q: What happens to users who request deletion of their accounts, who both qualify for immediate deletion and for staff to preserve their votes? To provide context:

*

*For a long while, there's been a feature where users who request deletion of their accounts and meet certain criteria for low activity have their account deleted immediately, rather than having to wait 24 hours for the request to be processed.

*Additionally, there's a feature where users who've cast a lot of votes will have their deletion request placed on hold for a staff member to review their voting record and determine if their votes should be preserved, because their votes would be removed otherwise, and this minimizes disruption. Normally, this ties in to the 24-hour timer: after the account is scheduled for deletion, once the timer lapses, it remains "stuck" until a staff member processes the deletion.

Last August, the criteria for having an account deleted immediately on the user requesting it were changed to not allow immediate deletion for users who've made one post on the site.
The previous criteria, however, didn't allow immediate deletion for users who'd cast more than one vote. On the other hand, the new criteria no longer check for number of votes cast, meaning that a user who's never posted but has voted on a lot of posts is now eligible for immediate deletion.
You might think that these cases could never overlap except in exceedingly rare cases: as the comment I linked above says:

You need at least 15 rep to vote, hard to get without posting (yes, you can make 7 suggested edits and get them approved, and then vote a couple of times and then delete your account, but that is a pretty extreme edge case).

However, it's not an extreme edge case, as that comment says. You can also vote using the association bonus, and while the answer there says that only users with "less than 101 rep" are eligible, a community member did some testing and found that accounts with 101 reputation are in fact deleted immediately, meaning that a user with the association bonus and no posts can cast a lot of votes, enough to require a staff review before deletion, but at the same time be eligible for immediate deletion. This wasn't possible with the previous criteria in any way, but is possible with the new criteria.
While such users (who cast a lot of votes but don't post) may be rare, and while the probability that their votes would not survive a staff review is higher, such cases can still exist.
What happens to users who request deletion of their accounts and meet the criteria for immediate deletion, but at the same time qualify for a staff review of their votes? Will the deletion be processed immediately (and all votes invalidated) without a wait or review? Will a timer show up on their profile as it would with the 24-hour timer, but with the date and time of expiration shown at the time of request rather than 24 hours later?

A: As currently designed, the profile would be deleted and all the votes would be lost. Profiles are only ever checked for voting thresholds to be transferred by the hourly script that processes 24-hour scheduled deletions. Immediate self-deletions go directly to being deleted in much the same fashion as moderator deletions would, which also are not ever checked for voting totals.


text:
Q: The trait Serialize is not implemented despite being implemented? I'm using actix-web for creating an app for reclaiming packets, then inserting them into MongoDB database. I have a struct
 #[derive(Serialize, Deserialize, Debug)]
    pub struct Gyro{
        /// GYRO FRONT + MIDDLE
        pub x0x800: [i32; 12],
        //A1X, A1Y, A1Z, A2X, A2Y, A2Z, G1X, G1Y, G1Z, G2X, G2Y, G2Z

        /// GYRO BACK
        pub x0x402: [i32; 4],
        //Motion_GPS_CAN, Vehicle_GPS_CAN, X_Angle_GPS, Y_Angle_GPS

        ///GYRO BACK
        pub x0x403: [i32; 4],
        //Z_Angle_GPS, X_Acceleration, Y_Acceleration, Z_Acceleration
    }

And I didn't have problems while deserializing packets into the struct, yet when I try to serialize them into BSON for insertion into mongoDB I am getting this error
if let Ok(bson::Bson::Document(doc)) = bson::to_bson(&packet) {
                                                   ^^^^^^^ the trait `Serialize` is not implemented for `Json<Gyro>

Despite me correctly implementing Serialize in the struct as well as having
use serde::{Serialize, Deserialize};

in the crate, it simply doesn't work. I even checked my dependencies using crate tree -d
and all of them were using the same serde version. Here's my cargo.toml
[dependencies]
actix-web = "3.1.0"
env_logger = "0.7"
serde = { version = "1.0.117", features = ["derive"] }
mongodb = "1.1.1"
bson = "1.1.0"

Is there a hidden issue I can't seem to notice, or is there another issue in dependencies?

A: The issue is that you're trying to serialize a value of type Json<Gyro>, not Gyro. Assuming this is the actix-web Json type, it doesn't implement Serialize. You'll need to either unwrap it by using &packet.into_inner() (which consumes the value) or referencing the inner value with &*packet or &packet.0.


text:
Q: Regex match and substring in one? I have a HTML source as input and would like to know what CMS the website is made in.
Many CMS leave their name in a meta tag like this:
<meta name="Generator" content="MY CMS" />

I can get the result like this:
        Match match = Regex.Match(html, ".*(?i)meta.*generator.*");
        match = Regex.Match(match.ToString(), "content.*\".*\"");
        match = Regex.Match(match.ToString(), "\".*\"");

Gives me "MY CMS"
But is there any way to shorten it down to one Regex.Match?
Please notice, that the meta tag could be like this:
<meta content="MY CMS" name="Generator" />

Thanks and best regards

A: var regex = new Regex(@"<meta\s+name=""Generator""\s+content=""([^""]+)""", RegexOptions.IgnoreCase);
var match = regex.Match(html);
var generator = match.Groups[1].Value;

A: Try the following:
Regex regex = new Regex(@"<meta[^>]+content\s*=\s*['"]([^'"]+)['"][^>]*>");
Match match = regex.Match(input);

The value is in group 1.
Hope it helps.

A: Regex is not a good choice for parsing HTML files..
HTML is not strict nor is it regular with its format..
Use htmlagilitypack
Regex is used for Regular expression NOT Irregular expression
You can use this code to retrieve it using HtmlAgilityPack
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);

var content= doc.DocumentNode
                .SelectSingleNode("//meta[@name='Generator']")
                .Attributes["content"].Value;


text:
Q: Is it true, that $(a:b) \cdot 2=a:(b:2)$, when b is even? I was doing my maths homework and I found that $(a:b) \cdot 2=a:(b:2)$ when b is even!I tried to improve it with examples, but I am not sure if it is true.Can you put it to the test and tell me if I have found a formula!

A: It is in fact true for all $a,b$ but if $b$ is odd, then you will get a non-integer in the denominator. In fact a more general statement is true:

$$a :(b:c)=(a:b)\times c$$

To see this, note that I can multiply with $c : c$, which is just 1.
$$a :(b:c) \times c:c =(a:b)\times c$$
But as you probably know, we do denominator times denominator and numerator times numerator when multiplying fractions. So we get
$$(a\times c) :(b:c \times c) =(a:b)\times c$$
$$(a\times c) :b =(a:b)\times c$$
$$(a:b)\times c =(a:b)\times c$$
which is clearly true. When you are formally writing a proof, you should write this form the end to the beginning, but I think this is easier for you to understand.

A: That is true for any number and can be proven using the associativity of the product (https://en.wikipedia.org/wiki/Associative_property). You just have to consider that dividing is the same as multiplying by the inverse of any number.
In your particular situation:
$$(a/b) \cdot 2=(a \cdot 1/b) \cdot 2 = a \cdot (2 \cdot 1/b) = a \cdot (2/b) = \frac{a}{b/2}$$
The only thing is that $b/2$ is an integer only when $b$ is even.


text:
Q: Why django inspectdb skips some ids? I was running inspectdb on my schema. At first, the defitions are very correct like these:
class Diagnosis(models.Model):
    id = models.BigIntegerField(primary_key=True)
    code = models.CharField(max_length=255)
    starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'diagnosis'

class DiagnosisTranslation(models.Model):
    id = models.IntegerField(primary_key=True)
    language = models.CharField(max_length=10)
    title = models.CharField(max_length=255, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    diagnosis = models.ForeignKey(Diagnosis, models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'diagnosis_translation'

Then, I added sequences and default values (postgresql) for Ids:
CREATE SEQUENCE diagnosis_id_seq START WITH 100000 INCREMENT BY 1;
ALTER TABLE diagnosis ALTER COLUMN id SET default nextval('diagnosis_id_seq');

CREATE SEQUENCE diagnosis_translation_id_seq START WITH 100000 INCREMENT BY 1;
ALTER TABLE diagnosis_translation ALTER COLUMN id SET default nextval('diagnosis_translation_id_seq');

I reran again python manage.py inspect, and the outcome changes correctly for diagnosis, but not for the other table, it lacks the id attribute now:
class Diagnosis(models.Model):
    id = models.BigAutoField(primary_key=True)
    code = models.CharField(max_length=255)
    starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'diagnosis'

class DiagnosisTranslation(models.Model):
    # Where's the ID ??
    language = models.CharField(max_length=10)
    title = models.CharField(max_length=255, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    diagnosis = models.ForeignKey(Diagnosis, models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'diagnosis_translation'

Why does Django omits the Ids for some tables and not others ? Especially why does it only happens when I make the id fields autoincrement ?

A: If you do not explicitly define a primary key. Django defines a primitive key automatically [Django-doc]. So in that case a field is implicitly added:
id = models.AutoField(primary_key=True)
Django will thus omit specifying the primary key explicitly given:

*

*the primary key has as name id; and

*the primary key has as type IntegerField [Django-doc] (an AutoField [Django-doc] is an IntegerField that automatically increments according to available IDs.


text:
Q: Prevent side effects in Ruby a = [1,2,3,4]
b = a << 5
a == [1,2,3,4] # returns false

How to assign b to a with 5 appended to the end without modifying a itself?

A: Just sum two arrays:
a = [1,2,3,4]
b = a + [5]

# b == [1, 2, 3, 4, 5]
# a == [1, 2, 3, 4]

A: Ruby variables hold references to objects and the = operator copies the references.
It seems you wish to clone a:
irb(main):001:0> a = [1,2,3,4]
=> [1, 2, 3, 4]
irb(main):002:0> b = a.clone << 5
=> [1, 2, 3, 4, 5]
irb(main):003:0> a
=> [1, 2, 3, 4]
irb(main):004:0> b
=> [1, 2, 3, 4, 5]

A: I usually do it this way:
b = [*a, 5]


text:
Q: How to bypass level of detail table calculation limitation I want to use LOD to get how many customers are spending over $1k and flag all the activity for each customer after they hit that threshold. I am using a table calculation to get a running total of their cumulative spend: RUNNING_SUM(SUM(SPEND))
Ideally I would like to do something like this: {FIXED year(date), cust_id: IF RUNNING_SUM(SUM(SPEND)) >1000 then 1 end}
And then add that calculated field as a filter, however Tableau does not support using LOD with table calculations. Are there any good workarounds for this?

A: Quite interesting topic, but I'm not sure if I got it straight.
With the following solution, you can see just the transactions after 1K for each user.

Is this what you want?
I'm asking beacuase if you need to count (transactions or users) I think there's no way due to the problem you've already pointed out.
Otherwise, if you "just" need to track the activity starting from the ones triggering the 1k limit, this could be a solution.


text:
Q: How to capture submit response in a form created dynamically? I have a form-iframe combination created inside jTable-create/edit popup to allow upload file:
$('#someContainer').jtable({
    ...
    FileUploadDownload: {
        input: function (data) {
            if (typeof data.record  == 'undefined' || !data.record.IsFileLoaded) {
                return '<form target="iframeTarget" class="formUploadFile" action="PostFile" method="post" enctype="multipart/form-data"> <input type="file" onchange="hideButtons(); this.form.submit()" name="myFile"/> </form> ';
            }
            else {
                return 'Download Remove File'
            }
        }
    }
}

My server code:
[HttpPost]
public JsonResult PostFile(HttpPostedFileBase myFile)
{
    if (myFile != null && myFile.ContentLength > 0)
    {
    ...
    }
    return Json(true);
}

Everything works.
Now I want to capture the response to re-enable some controls of the popup.
#jtable-edit-form is the id of a parent div of the popup created by jTable
.formUploadFile is a class of the form.
I tried to do this, but don't work:
$("#jtable-edit-form").on("submit", ".formUploadFile", null, function (event) {
    alert("Catch the submit");
    //re-enable some inputs, etc
});


text:
Q: mysql:Get data at particular time Need suggestion for finding list of all users whose status=1 at 31 jan 23:59:59(end of month).
select count(*) from users where status=1 and created_at=?

A: One way you restore your Database to some previous time is reverse running the binlog to current database state.
Or
Start database schema and running all the statement from binlog related to table only.
Take a help of Slave, if its still on some previous state

A: Below syntax will give any users that have status=1 and that was created on the 31:st of Jan 2014
select count(*)
from users
where status=1 and DATE(created_at)='2014-01-31'

This syntax will give the users that have the exact time '2014-01-31 23:59:59'. Assuming that the dateformat is the same. Seems unlikley that users get created at that time.
select count(*)
    from users
    where status=1 and created_at='2014-01-31 23:59:59'

A: select
count(*)
from
users
where status=1 and
created_at = concat(last_day(curdate(), ' 23:59:59'));

*

*read more about the last_day() function here

A: If using linux server then schedule below script through cronjob-
Save below lines in user.sh file.
vi user.sh

#!/bin/bash

DBUSER=your_server_user
DBPASS=your_server_pass

mysql -u$DBUSER -p$DBPASS db_name -e "select count(*) from users where status=1;" >> user.xls

echo -e "Please get the attached user Report." | mail -s"user Report" -a user.xls abc@abc.com

Now cron this script-
crontab -e
59 23 31 1 * /script_path/user.sh

It will execute 31, jan at 23:59 and send user report to your mail id.
If you are using windows server then you can create a batch file and call it with the help of Windows Task Schedular.

A: In the comments you mentioned a table which stores historic user updates. You can use this table to check users who had a status of 1 at that time:
SELECT COUNT(DISTINCT user_id) AS users
FROM status_history sh
WHERE
sh.created = (SELECT MAX(sx.created)
                     FROM status_history sx
                     WHERE sx.user_id = sh.user_id
                     AND sx.created < '2014-01-31 23:59:59')
AND sh.status = 1

We do an inner select to get the latest status change date for each status and user and grab the history with that date. We then count any of those that have status 1. Obviously if your table schema is different you may need to tweak the above.
SQL Fiddle example


text:
Q: MS Visual Web Developer 2010 Express I have installed MS Visual Web Developer 2010 Express and created the dll and also add the strong name to it.
Now I want to installed the dll into GAC. When i searched the file system i did not find gacutil.exe. Therefore i used regasm.exe .
Now im getting RegAsm: warning RA0000:No types were registered.
Suggest how we can install the same. Also for your information im using windows 7

A: Got a solution for this issue i.e. Installation of Windows SDK which will have gacutil.exe


text:
Q: Sabre RedApp Implementation for JxBrowser I am looking for some help with the Sabre Development Kit to get an app that currently uses the standard default browser (IE) to switch to a JxBrowser, but I am not finding much in the way of Java examples of the use of JxBrowser as a plugin.  If you have any Java examples of how this is done would be really helpful!

A: Starting release 2.13.1, there are two types of browser that can be used in Red App: native browser and WebKit.
https://developer.sabre.com/files/Sabre_Red_App_Developer_Toolkit_Overview.pdf
WebKit browser is already based on JxBrowser.


text:
Q: MySQL Server Logs I would like to know about MySQL Server Logs files.

*

*All log file names.

*The path of storing all log files in windows.

*Use MySQL command prompt to see

*Restore log files

Regards.
Ganesh Prasad


text:
Q: Recursion step doesn't update output I have a problem with the recursion. The function I wrote should recursively generate and return a list of pairs, called chain. The breaking condition is when the pair, (remainder, quotient) already belongs to the chain-list, then stop iterating and return the list. Instead of completing, the recursion just blows up, raising a RecursionError. The list doesn't update and contains only a single term, so the breaking condition is not executed. I don't understand why...
How should I proper implement the recursive step to make the list update?
def proper_long_division(a, b):
    """a < b"""
    chain = []

    block_size = len(str(b)) - len(str(a))

    a_new_str = str(a) + '0' * block_size
    a_new = int(a_new_str)
    if a_new < b:
        a_new = int(a_new_str + '0')

    quotient = a_new // b
    remainder = a_new - b * quotient

    print(remainder)
    #print(chain)

    # breaking condition <--- !
    if (remainder, quotient) in chain:
        return chain

    # next step
    chain.append((remainder, quotient))
    chain.extend(proper_long_division(remainder, b))

    return chain

try:
    a = proper_long_division(78, 91)
    print(a)
except RecursionError:
    print('boom')

Here a an example of recursion which (should) follows the same structure but the returned list is updated. I don't know why one code works while the other does not.
import random

random.seed(1701)

def recursion():
    nrs = []
    # breaking condition
    if (r := random.random()) > .5:
        return nrs
    # update
    nrs.append(r)
    # recursive step
    nrs.extend(recursion())
    return nrs

a = recursion()
print(a)
# [0.4919374389681155, 0.4654907396198952]

A: When you enter proper_long_division, the first thing you do is chain = []. That means that the local variable chain refers to a new empty list. Then you do some algebra, which does not affect chain, and check if (remainder, quotient) in chain:. Clearly this will always be False, since chain was and has remained empty.
The next line, chain.append((remainder, quotient)) runs just fine, but remember that only this call to proper_long_division has a reference to it.
Now you call chain.extend(proper_long_division(remainder, b)). You seem to expect that the recursive call will be able to check and modify chain. However, the object referred to by chain in a given call of proper_long_division is only visible within that call.
To fix that, you can use a piece of shared memory that any invocation of the recursive function can see. You could use a global variable, but that would make the function have unpredictable behavior since anyone could modify the list. A better way would be to use a nested function that has access to a list in the enclosing scope:
def proper_long_division(a, b):
    """a < b"""
    chain = {}

    def nested(a, b):
        while a < b:
            a *= 10
        quotient = a // b
        remainder = a - b * quotient

        key = (remainder, quotient)
        if key in chain:
            return chain

        # next step
        chain[key] = None
        nested(remainder, b)

    nested(a, b)
    return list(chain.keys())

A couple of suggested changes are showcased above. Multiplication by 10 is the same as padding with a zero to the right, so you don't need to play games with strings. Lookup in a hashtable is much faster than a list. Since ordering is important, you can't use a set. Instead, I turned chain into a dict, which is ordered as of python 3.6, and used only the keys for lookup. The values all refer to the singleton None.
The second example does not match the structure of the first in the one way that matters: you do not use nrs as part of your exit criterion.