text:
Q: How to display name instead of user_id in a datatable in Rails For a couple of days I have encountered a problem in my application and that is giving me a lot to think about:
I have a data table called "Devices" that contains a reference to "Users", in my data table I am bringing back the "user_id" but I want to take that data in the backend and show the "username" in the frontend.
How can I get the expected result?
in the "user" column the "user_id" is hosted

in my index.html.haml:
.table__wrapper
    = form_tag edit_multiple_devices_path, method: :get do
      %table{:role => 'datatable'}
        %thead
          %tr
            %th
            %th.abbr{:title => "aidi"} Id
            %th.abbr{:title => "imei"} Imei
            %th.abbr{:title => "brand"} Marca
            %th.abbr{:title => "model"} Modelo
            %th.abbr{:title => "prov"} Proovedor
            %th.abbr{:title => "fac"} Factura
            %th.abbr{:title => "din"} Entrada
            %th.abbr{:title => "sim"} Sim
            %th.abbr{:title => "iccid"} Iccid
            %th.abbr{:title => "status"} Status
            %th.abbr{:title => "user_id"} Usuario
            %th.abbr{:title => "client"} Cliente
            %th.abbr{:title => "dout"} Salida
            %th.abbr{:title => :use} Usado
            %th.abbr{:title => :old} Reutilizado
          %tbody
            - @devices.each do |device|
              %tr
                %td= check_box_tag "device_ids[]", device.id
                %td= device.aidi
                %td= device.imei
                %td= device.brand
                %td= device.model
                %td= device.prov
                %td= device.fac
                %td= device.din
                %td= device.sim
                %td= device.iccid
                %td= device.status
                %td= device.user_id
                %td= device.client
                %td= device.dout
                %td= device.use
                %td= device.old
      = submit_tag "Editar", class: "button is-primary is-rounded"

in my device.rb
class Device < ApplicationRecord
belongs_to :user
attr_accessible :aidi, :imei, :brand, :model, :prov, :fac, :din, :sim, :iccid, :status, :user_id, :client, :dout, :use, :old
end

in my user.rb
class User < ApplicationRecord
has_many :devices
end

A: ok
My question is duplicated. Here
The immediate "solution" is %td = device.user.try: email


text:
Q: serial communication reset /etc/profile (linux) I am working on a serial communication between a pc (ubuntu) and an embedded linux (2.6.24) board. The serial communication by itself seems to work (i use Serialib from http://serialib.free.fr/html/index.html ) but everytime my application on the board stop to listen the /etc/profile file is called by the board (this thing don't happen for application not using the serial).
It is to know that while i launch the application on the board, i have a gtkterm opened on the PC to follow the terminal of the board (which use the serial port too), i would think that this is the culprit of this reset of /etc/profile but i am not sure.
My code for the reading application
#include <stdio.h>
#include "serialib.h"
#include <QCoreApplication>
#include <QSettings>
#include <QProcess>
#include <iostream>

#if defined (_WIN32) || defined( _WIN64)
#define         DEVICE_PORT             "COM1"                               // COM1 for windows
#endif

#ifdef __linux__
#define         DEVICE_PORT             "/dev/ttyS0"                         // ttyS0 for linux
#endif

int main()
{
    serialib LS;                                                            // Object of the serialib class
int Ret,res;                                                                // Used for return values
char Buffer[128];

// Open serial port

Ret=LS.Open(DEVICE_PORT,115200);                                        // Open serial link at 115200 bauds
if (Ret!=1) {                                                           // If an error occured...
    printf ("Error while opening port. Permission problem ?\n");        // ... display a message ...
    return Ret;                                                         // ... quit the application
}
printf ("Serial port opened successfully !\n");

// Read a string from the serial device
Ret=LS.ReadString(Buffer,'\n',128,5000);                                // Read a maximum of 128 characters with a timeout of 5 seconds
                                                                        // The final character of the string must be a line feed ('\n')
if (Ret>0)                                                              // If a string has been read from, print the string
    printf ("String read from serial port : %s",Buffer);
else
    printf ("TimeOut reached. No data received !\n");                   // If not, print a message.

// Close the connection with the device

LS.Close();

return 0;
}

I send "TEXT\n" to the serial while in the limits of the timeout and i have "String read from serial port : TEXT" appearing on the terminal copy in gtkterm followed by "running etc/profile". Like i said before i suspect the fact that i am using the serial with gtkterm at the same time i send the string but i must have it working to use the board and i would like your opinion on this issue.
Thank you for the future answers.

A: You have your system configured to run another program (login or its kin) on the same serial port.
Check /inittab.  Make sure no instances of login or getty are being launched with that port.  (You will still want it running on the other serial port, the one you use for your terminal session)

redpajama_set_name: RedPajamaStackExchange


text:
Q: React - Attaching click handler to dynamic children I'm trying to display a playlist in my electron app which uses react+flux.
For some reason I can not attach a click handler to each playlist item.
Here's my code:
var Playlist = React.createClass({

    render: function() {
        var list = this.props.list;
        var playlist = [];

        for (var i = 0; i < list.length; ++i) {
            playlist.push(
                <PlaylistItem song={list[i]} key={i} />
            );
        }

        return (

                {playlist}

        )
    }

});

var PlaylistItem = React.createClass({

    _play: function() {
        console.log(this.props.song);
    },

    render: function() {
        var song = this.props.song;

        return (

{song.artist}

{song.title}

{song.time}

        );
    }

});

I don't understand why the click handler never fires. I'd expect that when clicking the i element i'd get the song object to the console.
Thanks.
Edit: I did some experimenting with this and everytime I get the data from a store (even fake data) the click handlers don't work. But if I move the fake data into the root component the click handlers work fine.
I have checked that the objects in the array are identical multiple times.
I don't understand why this behaviour is happening.
Anyone?

A: You need to bind the onClick method
onClick={this._play.bind(this)}

A: I have experienced this problem myself and resolved it as follows: https://stackoverflow.com/a/32623836/852872. Hope this helps for you too.
Answer from that page

I haven't done any deeper investigation why this didn't work for me,
  but the problem was that in my main file I imported React as
  require('React'), but on other components as require('React/addons').
  After importing React everywhere from react/addons everything works as
  expected.


text:
Q: Adobe Air desktop to read Unity standard output I am working on some Air Desktop application with in some part runs another application built with unity3d as a native process
var processArgs:Vector.<String > = new Vector.<String>();
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.workingDirectory = File.applicationDirectory.resolvePath("bin");
nativeProcessStartupInfo.executable = File.applicationDirectory.resolvePath("bin/unityApp.exe");

var process:NativeProcess = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(ProgressEvent.STANDARD_INPUT_PROGRESS, onOutputData);
process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
process.addEventListener(NativeProcessExitEvent.EXIT, onExit);
process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);

process.start(nativeProcessStartupInfo);
process.standardInput.writeUTFBytes(processArgs + "\n");

function onOutputData(event:ProgressEvent):void
{
    trace("Got: ", process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable));
}

function onErrorData(event: ProgressEvent):void
{
    trace("ERROR -", process.standardError.readUTFBytes(process.standardError.bytesAvailable));

}

function onExit(event:NativeProcessExitEvent):void
{
    trace("Process exited with ", event.exitCode);
}

function onIOError(event: IOErrorEvent):void
{
    trace(event.toString());
}

and in the unity app there is a button which is supposed to send a standard output so i can read it in Air.
my problem is that i used c# methods in unity to send the output but never read in air i used
Debug.log("text");
System.Console.Write("text");
System.Console.WriteLine("text");

i am new to unity and c# so i am asking what function should i use in unity to send standard output that Air can read
thanks.

A: To AIR app add startup arguments:
nativeProcessStartupInfo.arguments[0] = "-nolog";

In Unity add this code that sends some string to console:
System.IO.StreamWriter standardOutput = new System.IO.StreamWriter(System.Console.OpenStandardOutput());
standardOutput.Write("Hello!");
standardOutput.AutoFlush = true;
System.Console.SetOut(standardOutput);


text:
Q: Add list items to a Google map I have a PHP script that generates a list of places and I need to add those to a Google map on the same page. In spite of the MANY tutorials online, I haven't been able to find a straightforward way of doing this. I'm curious to know if there's a simple javascript/php snippet to do this... without resorting to a JQuery plugin, etc.

Pan Africa Market

Buddha Bar

Melting Pot

The Google Map would simply contain markers with these locations on it. Naturally the locations would change, so they can't be hard-coded.

A: Plain jQuery can do this for you with the each function. For the code example you need a google maps object:
$('#myPlaces li').each(function(index, el) {

    new google.maps.Marker({
        position: new google.maps.LatLng($(el).attr("lat"), $(el).attr("lng")),
        map: map,
        title: $(el).attr("name")
    });

});

See the doku for more informations:

*

*http://api.jquery.com/each

*http://code.google.com/intl/en-EN/apis/maps/documentation/javascript/reference.html#Marker
In plain JS it is more code to write and it can be done with the getElementsByTagName function which you can call on the document or a child node:
var i, list, places, place, lat, lng, placeName;

list = document.getElementById("myPlaces");
places = list.getElementsByTagName("li");

for (i = 0; i < places.length; i += 1) {
    place = places[i];
    lat = place.getAttribute("lat");
    lng = place.getAttribute("lng");
    placeName = place.getAttribute("name");

    new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
        title: placeName
    });
}

A: Soc got there first but yeah that is basically how you do it, but one recommendation would be to have the php generate a JSON object with the data and use that to generate the html list and the markers for the map.  If this is part of a large website definitely worth it doing it this way.  Grabbing the data for the map from the HTML is generally not good design.
Google Maps JavaScript API


text:
Q: Learning and practicing advanced materials I'm a first year grad student. I feel that practice problems/examples have been one of the most effective ways to enhance learning of new material. However, there are often no "problem set" for more advanced topics (e.g. papers in a specialized research area). I think if it might be beneficial to make up some problems of my own to enhance my understanding but that sometimes can be time consuming. I'm curious if mathematicians here have any advice for me on this regard.
For those who think this is too broad or off-topic, I'd like to give an example;
Suppose someone proposes the following inequality (Schwarz inequality): $\left| \sum_{i=1}^n u_i \bar{v}_i \right|^2 \leq \sum_{j=1}^n |u_j|^2 \sum_{k=1}^n |v_k|^2$ in their new research. I don't see nothing interesting at first glance. I'm curious of any method/tricks that will help me best "absorb the result" without someone gives me a bunch of examples as illustration (because often times those are either scarce or not available for more obscure result)?


text:
Q: confused with mysql foreign keys I am a little confused with foreign keys and how they are supposed to work.
i have 3 tables in database
database = mydb
table parent = user
table child = hobbies
table child2 = skills

*mydb.user have apID as primary and Auto Increment
*mydb.hobbies have apID with relation with mydb.user apID
and hID as auto increment
*mydb.skills hace apID with relation with mydb.user apID
and sID as auto increment

I am confused on how to insert data so that the apID in hobbies and skills are the same?
Which key in hobbies and skills need to be primary, the foreign or the other?
ok I end up with
INSERT INTO `mydb`.`user` (`appID`, `name`) VALUES (NULL, 'pedro');
INSERT INTO `skills` (`appID`,`dipID`,`name``) VALUES(LAST_INSERT_ID(),NULL,'running')

A: The primary key is the column(s) that uniquely identify a row in a table.  For your user table it is just apID and for the hobbies and skills tables it is either just hID and sID or hID + apID and sID + apID (depends on what your data represents).
A foreign key is a refence to a value in another table. So if you have a foreign key constraint on apID in hobbies that refences apID in user, that means that every apID in hobbies must have a matching apID in user.  If you try to insert or update a row in hobbies or user so that a matching pair goes away MySQL will throw an error.
The hobbies table might look like this:
CREATE TABLE hobbies (
  hID INT(10) AUTO_INCREMENT NOT NULL,
  apID INT(10),
  PRIMARY KEY (hID, apID),
  FOREIGN KEY (apID) REFERENCES user(apID) ON UPDATE CASCADE
);

The neat thing there is the ON UPDATE CASCADE clause.  That will make it so that if you update an apID in user, the database will update any rows it has to in hobbies so that everything stays in synch.  There are also things like ON DELETE CASCADE, but if you do a little research those should be easy to find.
As for how to insert the data, you do it as you normally would.  The only caveat is that before you can insert into hobbies or skills, there has to be a matching apID already in the user table.
Here is a SQL Fiddle that shows all this stuff in action.

A: You have next tables -
CREATE TABLE `USER`(
  APID INT(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (APID)
) ENGINE = INNODB AUTO_INCREMENT = 1;

CREATE TABLE HOBBIES(
  HID INT(11) NOT NULL AUTO_INCREMENT,
  APID INT(11) DEFAULT NULL,
  PRIMARY KEY (HID),
  CONSTRAINT FK_HOBBIES_USER_APID FOREIGN KEY (APID) REFERENCES `USER` (APID)
    ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = INNODB AUTO_INCREMENT = 1;

CREATE TABLE SKILLS(
  SID INT(11) NOT NULL AUTO_INCREMENT,
  APID INT(11) DEFAULT NULL,
  PRIMARY KEY (SID),
  CONSTRAINT FK_SKILLS_USER_APID FOREIGN KEY (APID) REFERENCES `USER` (APID)
    ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = INNODB AUTO_INCREMENT = 1;

Our ID primary fields are declared as AUTO_INCREMENT, so it is better to use this feature - add NULL value and MySQL will generate new ID value itself (1, 2, 3 and so on) -
-- Add first user and all his properties (hobbies, skills)
INSERT INTO user(apID) VALUES(NULL); -- We pass NULL

-- But real ID is 1, we set this value to variable @id
-- This @id will be used to insert correct foreign key values in child tables
SET @id = LAST_INSERT_ID();

-- Add some hobbies and skills for user 1
INSERT INTO hobbies(hID, apID) VALUES (NULL, @id);
INSERT INTO hobbies(hID, apID) VALUES (NULL, @id);
INSERT INTO hobbies(hID, apID) VALUES (NULL, @id);

INSERT INTO skills(sID, apID) VALUES (NULL, @id);
INSERT INTO skills(sID, apID) VALUES (NULL, @id);
INSERT INTO skills(sID, apID) VALUES (NULL, @id);

Do the same for each user.
Check results:
SELECT * FROM `user`;
+------+
| APID |
+------+
|    1 |
+------+

SELECT * FROM hobbies;
+-----+------+
| HID | APID |
+-----+------+
|   1 |    1 |
|   2 |    1 |
|   3 |    1 |
+-----+------+

SELECT * FROM skills;
+-----+------+
| SID | APID |
+-----+------+
|   1 |    1 |
|   2 |    1 |
|   3 |    1 |
+-----+------+

A: sorry but what you wrote is a little bit confusing. i hope i understood your problem.
if you have a table user with primary key userID, and two tables hobbies and skills that use user.userID as foreign keys.
You will need a primary key in both hobbies and skills (e.g. hobbiesID and skillsID). userID can't be the primary key of hobbies/skills, because it would not be unique; it is just used as foreign key to form the relation between the usertable and the hobbies/skillstables.

A: 1.table parent = user
Here apID  is primary key
2.table child = hobbies
here hID is primary key and apID is foreign key
3.table child2 = skills
here sID is primary key and apID is foreign key
--INSERT COMMANDS
1.INSERT INTO user
2.INSERT INTO hobbies
here you have to select apID from users table
3.INSERT INTO skills
here you have to select apID from users table


text:
Q: Remove row from dataframe if column value If I have a dataframe like this:
index   col1   col2
a        a1     a2
b        b1     b2
c        c1     b2

Is it possible to use the .drop() to delete rows which have a sudden value in one of their columns?
Something like: df.drop(col2 = 'b2')

A: You need boolean indexing:
df = df[df.col2 != 'b2']

A: You can use a boolean filter. For example:
df = df[df['col1'] != 'a1']

Would drop all rows with the value a1 in column col1. See this page of the Pandas docs for more details.


text:
Q: Only one ranked attribute, but selected two? InfoGain Ranker in weka I've run an InfoGain evaluation on my dataset, with a Ranker on threshold 0.1.
My output via the GUI says:
Search Method:
    Attribute ranking.
    Threshold for discarding attributes:   0.1

Attribute Evaluator (supervised, Class (nominal): 23 class):
    Information Gain Ranking Filter

Ranked attributes:
 0.141    2 nr_visits

Selected attributes: 2 : 1

In my java implementation, I do the same thing:
Ranker ranker = new Ranker();
ranker.setGenerateRanking(true);
ranker.setThreshold(0.1);

AttributeSelection attsel = new AttributeSelection();
InfoGainAttributeEval eval = new InfoGainAttributeEval();

attsel.setEvaluator(eval);
attsel.setSearch(ranker);

attsel.SelectAttributes(instances);

int[] ranked_attr = attsel.selectedAttributes();
double[][] rawscores = attsel.rankedAttributes();

Where I get similar output:

*

*my ranked_attr is [1, 21] (with 1 being the nr_visits feature, and 21 another)

*my rawscores double array does NOT contain ANY entry for 21. It has the 1, and then another feature with a score lower than my threshold.

What gives? Are there one or two selected features? Is this a bug in weka 3.8.4?

A: Thanks to Eibe on the mailing list:

AFAIK, the set of indices returned by selectedAttributes() includes the index of the class attribute. I assume that attribute 22 in your data is the class attribute. There is no score for the class attribute because it is the attribute that we are trying to predict.

Because yes, the 21 was indeed my class index, which is zero-based in code, one-based in the GUI, which is why I didn't immediately notice.


text:
Q: internal sd card reader works, but without automount On a new laptop I installed Ubuntu 18.04. Everything works fine, except for auto mount of sd cards. After inserting an sd card in the internal card reader, dmesg says:
mmc0: new high speed SDHC card at address b368
mmcblk0: mmc0:b368       7.46 GiB
mmcblk0: p1
mmcblk0: p1

The driver seems to be working OK because manually mounting works with:
sudo mount /dev/mmcblk0p1 /mnt

However, this makes the sd card read-only for all normal users. From my old laptop with the previous version of ubuntu, I was used to usb drives that automatically mount to /media/{user}/{volumename} and that can be unmounted with a context mouse menu on the menu icon for the drive.
My questions are:

*

*how is this auto mount feature configured?

*how do I get this auto mount behaviour to work on my new laptop?

update:
googling the first bullet I found:
https://help.ubuntu.com/stable/ubuntu-help/hardware-cardreader.html.en
with the suggestion to open the Files in the Activities list and do control-L and search for computer:/// . This made the sd card visible. This does not solve my second question, but if this had a solution, it would be mentioned there, and anyway this is a workable situation

A: It turns out that there is no technical problem, but a new Ubuntu GUI. In the Files activity, under Other Locations, the SD card shows up in a very intuitive way, similar to Computer overview of Windows. To me it seems that this top level overview is rather hidden here.
The documentation in https://help.ubuntu.com/stable/ubuntu-help/hardware-cardreader.html.en is not exactly in sync, as it mentions a device list in the side bar, not under Other Locations.
On my previous ubuntu system a popup would appear at insertion of a usb drive. Removal of the popup could be a feature or a bug :-)


text:
Q: Date format in D3.js I have a column (date) in csv which stores the date in "2003-02-01"(y-m-d). I would like to format the date in month and year like Apr 2003. how do i do that?
var format = d3.time.format("%m-%Y");
data.forEach(function(d,i) {
d.date = format(d.date);
});

I am getting the following error Error: TypeError: n.getFullYear is not a function Line: 5
the csv file contains values:
200,300,400,288,123,2003-01-01
300,700,600,388,500,2003-02-01

what is the issue here?

A: D3 version 4 has different time methods now.
https://keithpblog.org/post/upgrading-d3-from-v3-to-v4/
https://github.com/d3/d3/blob/master/CHANGES.md
Your source date
var d = {created_time : "2018-01-15T12:37:30+0000"}

The structure of that date = %Y-%m-%dT%H:%M:%S%Z
I search google with "2018-01-15T12:37:30+0000" and it's suggestions provided the date structure string. Handy.
Create a timeParser to convert(parse) your date string into a date object
var parseDate = d3.utcParse("%Y-%m-%dT%H:%M:%S%Z")
//parseDate(d.created_time)

Now create a time formatter to return a formated date string for displaying.
var formatDate = d3.timeFormat("%b-%Y")
return formatDate(parseDate(d.created_time))

i.e.
Jan-1970

A: Javascript doesn't automatically recognize the values in the CSV file as dates, just reading them in as strings. d3's time functions make it pretty easy to convert them to datetime objects:
> parseDate = d3.time.format("%Y-%m-%d").parse
> parseDate('2003-01-01')
Wed Jan 01 2003 00:00:00 GMT-0600 (Central Standard Time)

To format the dates like you want, we need to go the other way, from a date object to a string:
> formatDate = d3.time.format("%b-%Y")
> formatDate(parseDate('2003-01-01'))
"Jan-2003"

I would recommend representing your dates within your program with date objects and only formatting them as strings when you need to display them.

A: from Adam answer, here is a small helper function to convert a time string from a format to another:
var formatTime = function(input, formatInput, formatOutput){
    var dateParse = d3.time.format(formatInput).parse;
    var dateFormat = d3.time.format(formatOutput);
    return dateFormat(dateParse(input));
};

use:
formatTime("2003-01-01", "%Y-%m-%d", "%b-%Y");

// output -> "Jan-2003"

A: if you are getting date lets say in variable " d = (e.g: '2003-03-01')" in string format then,
var monthNameFormat = d3.time.format("%b-%Y");
return monthNameFormat(new Date(d));

this will result date in "Jan-2003" format.

A: In D3Js v3, this worked for me:
var s = "2018-11-01T19:37:55Z";

d3.time.format("%Y-%m-%dT%H:%M:%SZ").parse(s);

// Thu Nov 01 2018 19:37:55 GMT-0700 (Pacific Daylight Time)


text:
Q: JavaScript Singleton losing reference I have a problem with a singleton pattern that I have implemented in 'program.js':
var Program = (function() {

var _program; // Instance of program

// Constructor
function Program() {

    if (typeof _program != "undefined") {
        throw new Error("Program can only be instantiated once.");
    }

    this.run = false;   // flag to allow for program exec

    _program = this;
};

// Public methods
Program.prototype.init = function() {
    // the run call is nested in 4 callbacks
    callbackHell (
       this.run = true;
    );
};

Program.prototype.execute = function() {
    if(this.run == true) {
        // do stuff
    }
};

Program.getProgram = function () {
    if(typeof _program == "undefined")
    {
        return new this();
    }
    return _program;
};

// Return the constructor
return Program;
})();

In my 'main.js' I keep a reference to the loaded program and check for the run flag to allow execution. Looks like this:
var program = null;

function initDemo() {
    program = Program.getProgram();
    program.init();
    runDemo();
};

function runDemo() {
    if(program != null && program.run) {
        program.execute();
    }
    requestAnimationFrame(runDemo);
};

If I execute this code on a Chrome browser, it will never reach the program.execute() call in main.js. The reference of program will keep the run flag to false, even it is changed in the init() function. I checked for all of this in the debugger. I should point out that the 'this.run = true' call is nested in 4 callbacks. After a while I figured I could just change the run flag of the global reference of program in main.js with the init() function. So instead of 'this.run = true', 'program.run = true'. This works and the loop will run execute(). However this is not the style I am used from OOP. What is actually happening here? It definitely has to do with the callbacks: when I put 'this.run = true' out of the callbacks at the end of init() the flag is changed correctly, however at the wrong time of the program execution.

A: Probably your callbacks in the callbackHell are doing something asynchronously and there is a delay before program.run will actually be set to true, the sequence is approximately this:

*

*You call program.init()

*Your callbacks start working

*You call runDemo(), here program.run is false and it exists

*Callbacks finish their work and program.run becomes true
The solution to that is to make your runDemo to be another callback, so your main code will look like this:
var program = null;

function initDemo() {
    program = Program.getProgram();
    program.init(runDemo);
};

function runDemo() {
    if(program != null) {
        program.execute();
    }
    requestAnimationFrame(runDemo);
};

Here you don't need the program.run flag at all, instead you just start your demo from inside the "callbackHell":
Program.prototype.init = function(functionToRun) {
    // the run call is nested in 4 callbacks
    callbackHell (
       functionToRun(); // instead of setting program.run
                        // we call the specified function
    );
};


text:
Q: Nested JSON to DataFrame I have a JSON file that looks like this
{
   "AAPL":{
      "quote":{
         "symbol":"AAPL",
         "companyName":"Apple, Inc.",
         "primaryExchange":"SQDNAA",
         "calculationPrice":"close"
      }
   },
   "MSFT":{
      "quote":{
         "symbol":"MSFT",
         "companyName":"Microsoft Corp.",
         "primaryExchange":"QSAAND",
         "calculationPrice":"close",
      }
   }
}

How do I convert this to a Pandas DataFrame with columns as in the nested quote? (symbol, companyName, primaryExchange and calculationPrice)

A: you can just loop over the dict and add it to a list.
d = yourjsonobject

dfs = []
for k, _ in d.items():
    for quote,v in _.items():
        dfs.append(pd.DataFrame(v,index=[k]))

df = pd.concat(dfs)

print(df)

     symbol      companyName primaryExchange calculationPrice
AAPL   AAPL      Apple, Inc.          SQDNAA            close
MSFT   MSFT  Microsoft Corp.          QSAAND            close

A: you could give jmespath a try, as it has a nice way of traversing JSON data :
 import jmespath
 #create a compiled expression
 #of the data path
 #similar to re.compile
 #it looks for the quote key and returns its contents
 expression = jmespath.compile('*.quote')
 A = expression.search(data)

#read into a dataframe
 pd.DataFrame(A)

    symbol  companyName primaryExchange calculationPrice
0   AAPL    Apple, Inc.       SQDNAA      close
1   MSFT    Microsoft Corp.    QSAAND     close


text:
Q: sklearn cross_val_score() returns NaN values i'm trying to predict next customer purchase to my job. I followed a guide, but when i tried to use cross_val_score() function, it returns NaN values.Google Colab notebook screenshot
Variables:

*

*X_train is a dataframe

*X_test is a dataframe

*y_train is a list

*y_test is a list

Code:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=50)
X_train = X_train.reset_index(drop=True)
X_train
X_test = X_test.reset_index(drop=True)

y_train = y_train.astype('float')
y_test = y_test.astype('float')

models = []
models.append(("LR",LogisticRegression()))
models.append(("NB",GaussianNB()))
models.append(("RF",RandomForestClassifier()))
models.append(("SVC",SVC()))
models.append(("Dtree",DecisionTreeClassifier()))
models.append(("XGB",xgb.XGBClassifier()))
models.append(("KNN",KNeighborsClassifier()))´

for name,model in models:
   kfold = KFold(n_splits=2, random_state=22)
   cv_result = cross_val_score(model,X_train,y_train, cv = kfold,scoring = "accuracy")
   print(name, cv_result)
>>
LR [nan nan]
NB [nan nan]
RF [nan nan]
SVC [nan nan]
Dtree [nan nan]
XGB [nan nan]
KNN [nan nan]

help me please!

A: My case is a bit different. I was using cross_validate instead of cross_val_score with a list of performance metrics. Doing a 5 fold CV, I kept getting NaNs for all performance metrics for a RandomForestRegressor:
scorers = ['neg_mean_absolute_error', 'neg_root_mean_squared_error', 'r2', 'accuracy']

results = cross_validate(forest, X, y, cv=5, scoring=scorers, return_estimator=True)
results

Turns out, I stupidly included the 'accuracy' metric which is only used in classification. Instead of throwing an error, it looks like sklearn just returns NaNs for such cases

A: I fixed the issue on my side. I was using a custom metric (Area Under Curve Precision-Recall (AUCPR))
def pr_auc_score(y, y_pred, **kwargs):
  classes = list(range(y_pred.shape[1]))
  if len(classes) == 2:
      precision, recall, _ = precision_recall_curve(y, y_pred[:,1],
                                                    **kwargs)
  else:
    Y = label_binarize(y, classes=classes)
    precision, recall, _ = precision_recall_curve(Y.ravel(), y_pred.ravel(),
                                                  **kwargs)
  return auc(recall, precision)

The problem is, for a binary problem, y_pred contains only the predicted probability of the label 1, so y_pred's shape is (n_sample,).
When I try to call the method : y_pred.shape[1], it raises an error.
The solution: inside cross_validate, use the parameter error_score="raise". This will allow you to detect the error.

A: Well thanks everyone for your answers. The answer of Anna helped me a lot!, but i don't used X_train.values, instead i assigned an unique ID to the Customers, then dropped Customers column and it works!
Now the models has this output :)
LR [0.73958333 0.74736842]
NB [0.60416667 0.71578947]
RF [0.80208333 0.82105263]
SVC [0.79166667 0.77894737]
Dtree [0.82291667 0.83157895]
XGB [0.85416667 0.85263158]
KNN [0.79166667 0.75789474]

A: For my case, I had a time delta data type inside my numpy array that resulted in the error

A: I face to face with that problem. I solved this way; i convert X_train and y_train to DataFrame.
cross_val_score(model,X_train,y_train, cv = kfold,scoring = "accuracy")

A: I know this is answered already but for others who still cannot figure out the problem, this is for you...
Check if you y data type is a int or not. It will return nan if your date type for the y value is an object
How to check
y.dtype
How to change the data type
y = y.astype(int)

A: Try doing encoding of categorical columns before passing to cross_val_score. It worked for me.

A: The cross_val_score method returns NaN when there are null values in your dataset.
Either use a model which can deal with missing values or remove all the null values from your dataset and try again.

A: For me using xtrain.values, ytrain.values worked as the cross validation needs the input to be an array and not dataframe.


text:
Q: AHK: Remove Text From String This Word To The First Line Break I work at a doctors office doing billing, and I've run into a problem. Because of an issue with the way the EMR (electronic medical record) program works, immunization codes don't always make it into the chart. In order to compensate for this, I have AHK also search for the name of the immunization (dangerous, I know). Just until recently, this was working fine, until one of the doctors canceled an order for an immunization. This threw a false positive because of the failsafe I included for the charts without the code (IMM94, and IMM97). I need to remove, from a very large string, everything after the word "CANCELED: " to the first line break that occurs after that word. I created a rather pretty string clipping function to do most of this kind of stuff, but it's taking issue with finding the line break because there are so many. The test case I'm working with is:

Assessment and Plan:

*

*Need for prophylactic vaccination and inoculation against influenza     (tab) CANCELED: Influenza, High Dose (65+) (newline)

*Prediabetes     Work on weight loss and exercise

*Osteopenia  Exercise and vit d and b 12

There's a lot of stuff both above this, and below this, but I want to extract ALL instances from my string of the word "CANCELED: " to the first line break after it.
This is what I'm trying, along with my function. It's not working, and in fact, it's duplicating the line beginning with "1. ":
^L::
lString := ClipBoard
If lString Contains Canceled
fString := ClipString(lString, "CANCELED: ", "`n")
Clipboard := fString
Return

ClipString(lString, aMarker, bMarker, Only := 0)
{
If (Only = 1)
Return SubStr(SubStr(lString, 1, InStr(lString, bMarker)+StrLen(bMarker)-1), InStr(lString, aMarker))
Else
Return SubStr(lString, 1, InStr(lString, aMarker)-StrLen(aMarker)) . SubStr(lString, InStr(lString, bMarker)+StrLen(bMarker))
}

A: Strips "cancelled:" and any text following it from each line in clipboard
Program:
Clipboard := RegExReplace(Clipboard, "im)\s*CANCELLED:.*\R?", "`r`n")

Sample Input:
alpha
beta cancelled: ABC asldkfalsd
delta
gamma omega CANCELLed: zeta
theta

Sample Output:
alpha
beta
delta
gamma omega
theta

A: Got it figured out. I'll comment it to help anyone who has this issue. I love how compact you can get functions usually, but this piece really needed a couple more lines than I'd like. If anyone can get it down to less, and have it still work, let me know!
^L::
ClipBoard := ClipString(ClipBoard, "Canceled: ", "`n",2) ;This is the function call here.
;The first parameter is the string to do stuff to, the second is what to cut out of the
;string, and the third parameter is how far after that piece to cut, so if you wrote
;Canceled: thenawholebunchofstuffthena newline, it'd remove all of it except for the
;newline. The third parameter is which mode to put ClipString to.
Return

ClipString(lString, aMarker, bMarker, Mode := 0) ;already explained above.
;Mode defaults to zero because I call the zero mode a lot.
{
If (Mode = 0) ;Mode Zero returns the ONLY the section from the original string
;between aMarker and bMarker.
    Return SubStr(lString, 1, InStr(lString, aMarker)-StrLen(aMarker)) . SubStr(lString, InStr(lString, bMarker)+StrLen(bMarker))
Else If (Mode = 1) ;Mode One returns the original string with the section between aMarker
;and bMarker removed.
    Return SubStr(SubStr(lString, 1, InStr(lString, bMarker)+StrLen(bMarker)-1), InStr(lString, aMarker))
Else If (Mode = 2) ;Mode Two returns the original string with all instances of aMarker
;to bMarker removed. I.E. Every occurrence of aMarker will be removed to bMarker.
    {
    aString := lString
    StringReplace, aString, aString, %aMarker%, %aMarker%, UseErrorLevel ;Count how many
;instances of aMarker are in the original string.
    CanCnt := Errorlevel ;actual count of # of aMarkers
    Loop, %CanCnt% ;loop as many times as there are aMarkers
        {
        aString := SubStr(aString, 1, InStr(aString, aMarker)-1) . SubStr(SubStr(aString, InStr(aString, aMarker)), InStr(SubStr(aString, InStr(aString, aMarker)), bMarker)-1)
;this is a tad complicated. The first part before the concatenate takes the string, and
;keeps from the start point to the first aMarker. The concatenate adds the substring of the
;substring between aMarker and the end of the string, and the location of the substring in
;aString from the occurrence of aMarker to one position before the start of bMarker.
;An easier way to read this would be to replace "SubStr(aString, InStr(aString, aMarker))
;with a variable like bString. It shortens it up quite a bit.
        }
    Return aString
    }
}


text:
Q: Add /demo/ slug with rewrite rule
Possible Duplicate:
Add extra parameters after permalink?

I need to add a slug to every post.
Current permalinks
http://www.my-domain.com/2012/01/01/my-post-title/ or
http://www.my-domain.com/my-post-title/
Rewritten permalinks
http://www.my-domain.com/2012/01/01/my-post-title/demo/ or
http://www.my-domain.com/my-post-title/demo/
Additional information

*

*My demo-page should not return a 404-page.

*I should be able to get the current ID of the post "my-post-title" from my demo-page.


text:
Q: Issue in merge array and delete duplicate all array I've merged two arrays. A duplicate entry is a deleted. Let me explain the as an example (I have compare array using user_id)
$array1 = Array
(
[0] => Array
(
[id] => 44
[user_id] => 2
[name] => jina_testl
[profilePhoto] =>
)
)

$array2 = Array
(
[0] => Array
(
[id] => 2
[user_id] => 3
[name] => demo_test1
[profilePhoto] =>
)
[1] => Array
(
[id] => 3
[user_id] => 2
[name] => abc
[profilePhoto] =>
)
[2] => Array
(
[id] => 4
[user_id] => 4
[name] => test
[profilePhoto] =>
)
)

I have merged array1 and array2 and duplicate array remove. I get the following output:
Array
(
[0] => Array
(
[id] => 44
[user_id] => 2
[name] => jina_testl
[profilePhoto] =>
)
[1] => Array
(
[id] => 2
[user_id] => 3
[name] => demo_test1
[profilePhoto] =>
)
[3] => Array
(
[id] => 4
[user_id] => 4
[name] => abc
[profilePhoto] =>
))

But I want such an output like this:
Array
(
[0] => Array
(
[id] => 2
[user_id] => 3
[name] => demo_test1
[profilePhoto] =>
)
[1] => Array
(
[id] => 4
[user_id] => 4
[name] => abc
[profilePhoto] =>
))

A: You could do something like the following: first get all the user_ids that we do not want to be included, by taking the intersection of the two columns.
If we then merge the two separate arrays and exclude the ones that are present in the array of unwanted IDs we should get our final result.
$userId = 'user_id';

$userIdsArray1 = array_column($array1, $userId);
$userIdsArray2 = array_column($array2, $userId);

// If we then take the negation we should get something similar to an exclusive or.
// Thus those in one or the other but not in both arrays.
$unwantedUserIds = array_intersect($userIdsArray1, $userIdsArray2);

$result = [];

foreach (array_merge($array1, $array2) as $record) {
    if (!in_array($record[$userId], $unwantedUserIds)) {
        $result[] = $record;
    }
}

echo '<pre>', print_r($result, true), '</pre>';

Result:
Array
(
    [0] => Array
        (
            [id] => 2
            [user_id] => 3
            [name] => demo_test1
            [profilePhoto] =>
        )

    [1] => Array
        (
            [id] => 4
            [user_id] => 4
            [name] => test
            [profilePhoto] =>
        )

)


text:
Q: qnap nfs mounting delays after Ubuntu Updated After last Ubuntu Update (20.04 LTS), when I mount my qnap nfs shares:

*

*It delays for several minutes (prior to this, it took 1 second to mount it)

*During that "long mounting time"... I can move the mouse but nothing respond to clicks, nor to keystrokes.

*I put and "strace -t" but it was not evident where the delay is. All events are reported in the same second.

*I have 2 different model Network adapters in the Ubuntu computer, and the behavior is the same mounting through any of them. So that, is not a problem specifically related to the network card.

Any idea?

A: This is also happening with Manjaro and OpenSUSE tumbleweed on the latest 5.16 kernels. On these OSes, I had to drop back to an earlier kernel to get QNAP NFS shares working again. My systems can mount nfs shares exported from other, non-Qnap machines, so it looks as though there is some strange incompatibility with the Qnap kernel. I will let you know if I find out anything more.

A: Temporary fix: try mounting using NFS 3 (mount -o mountvers=3 ...).
This got my client systems working again, but I do not know why.

A: That is the same solution I came up with but I just disabled NFS v4 from control panel.  I have 2 QNAP NAS units and one stopped responding to mount requests while the other was working fine.  I was able to compare setting between the 2 systems until I found the difference.
Go to [Control Panel][Network & File Services][Win/Mac/NFS/WebDav][NFS Service]
Uncheck [Enable NFS v4 Service] and leave [Enable NFS v2/v3 Service] checked
You will need to restart the NAS for this to work.


text:
Q: Consulta em três tabelas por uma coluna com Foreign Key Essa foi a forma que eu achei para fazer uma consulta nas minhas três tabelas: PAIS, FILHOS e NETOS usando o operador LIKE:
SELECT `PAIS`.nome,
       `FILHOS`.nome,
       `NETOS`.nome
 FROM  `PAIS`, `FILHOS`, `NETOS`
 WHERE `PAIS`.nome LIKE '%MATILDE%'
 OR    `FILHOS`.nome LIKE '%MATILDE%'
 OR    `NETOS`.nome LIKE '%MATILDE%'

Tenho outra pergunta relacionada ao problema: consulta recursiva em tabelas relacionadas usando foreign keys
Só para recapitular, estou repassando as definições de como está meu banco de dados novamente (veja a imagem abaixo):

Observe que a tabela FLHOS está relacionada com a tabela PAIS pela coluna idPAI, no caso JOSE é filho de SEVERINO e MARIA é filha de JOSEFINA:

Agora a pergunta que não quer calar: como eu faço para trazer essa relação do id com o nome da pessoa através da busca pelo palavra '%MATILDE%' usando o operador LIKE?

Exemplo:
MATILDE idFILHOS 1 quer dizer que é filha de JOSE, que é filho de SEVERINO, deu pra entender? Eu quero fazer essa "recursão" buscando pelo nome, porém trazendo somente os que estão relacionados pela chave primária id.

A: Olá, você precisa relacionar as chaves primárias e estrangeiras das tabelas... Fazer um INNER JOIN.
OBS: Coloquei errado o JOIN. Segue código correto:
SELECT
  PAIS.nome,
  FILHOS.nome,
  NETOS.nome
FROM PAIS
INNER JOIN FILHOS
  ON PAIS.id = FILHOS.idPAI
INNER JOIN NETOS ON FILHOS.idPAI = NETOS.idFILHOS
WHERE
  PAIS.nome LIKE '%MATILDE%' OR FILHOS.nome LIKE '%MATILDE%' OR NETOS.nome LIKE '%MATILDE%'


text:
Q: Rails 3 redirecting to strange ID after create trail has_many chapters
chapter belongs_to trail
my routes:
resources :trails do
  member do
    resources :chapters do
      member do
        resources :clues
    end
  end
 end
end

called from a standard form in new.html view
from my chapters_controller.rb
def creat
  @trail = Trail.find(params[:id])
  @chapter = @trail.chapters.build(params[:chapter])
     if @chapter.save
       flash.now[:status] = "Chapter created"
       redirect_to @chapter
     else
       flash.now[:error] = "Name needed"
       render 'new'
     end
end

The log which reveals how the trail ID starts out as 1, and then after the create the trail ID is 28 (or the chapter_id).
Started POST "/trails/1/chapters" for 127.0.0.1 at Fri May 04 20:31:15 -0700 2012
Processing by ChaptersController#create as HTML
Parameters: {"commit"=>"Create New Chapter", "chapter"=>{"name"=>"", "gate"=>"", "assetkind"=>"url", "description"=>"", "asset"=>""}, "authenticity_token"=>"Puu7EL8yQEsU4/NimBdL6mJRXiXoFTbHb1DSYvFNDgI=", "utf8"=>"✓", "id"=>"1"}

.
.
.
(3.7ms)  commit transaction
Redirected to http://localhost:3000/trails/28/chapters/28

I expect it to redirect to ..trails/1/chapters/28  ...  when I change the url to reflect the path I expect, the correct page shows with the correct content.
I'm having a number of problems, but I think this might be a clue to help me figure them out.  Is there something wrong with my routes or with my associations?  I kind of restructured my associations and nested them and now I'm having issues.
Much thanks for your time and attention!

A: Your routes are overly specific. You really just need this:
resources :trails do
  resources :chapters do
    resources :clues
  end
end

And really, you should probably consider whether it's worth it to leave clues nested at the third level rather than providing shallow routes.
Also, you will need to hand both objects used to build a nested chapter route to the path helper:
redirect_to trail_chapter_path(@trail, @chapter)

Otherwise it'll only have the ID of the chapter. This is what is causing your trail ID to jump unexpectedly to 28.


text:
Q: (SDL Render Problem) C++ Exception Thrown: read access violation. THIS was nullptr Whenever I run my program I get an exception thrown on two seperate lines of code should I comment one of them out the problem jumps to another but both refer to the same variable.
GameScreenManager.cpp:
#pragma once
#include <SDL.h>
#include "Commons.h"
#include "GameScreenManager.h"
#include "GameScreenLevel1.h"
#include "GameScreen.h"

GameScreenManager::GameScreenManager(SDL_Renderer* renderer, SCREENS startScreen)
{
    SDL_Renderer* mRenderer;
    mRenderer = NULL;
    ChangeScreen(startScreen);
}

GameScreenManager::~GameScreenManager()
{
    mRenderer = NULL;
    delete mCurrentScreen;
    mCurrentScreen = NULL;
}

void GameScreenManager::Render()
{
    mCurrentScreen->Render();
}

void GameScreenManager::update(float deltaTime, SDL_Event e)
{
    mCurrentScreen->Update(deltaTime, e);
}

void GameScreenManager::ChangeScreen(SCREENS newScreen)
{
    //Clear up the old screen
    if (mCurrentScreen != NULL)
    {
        delete mCurrentScreen;
    }

    GameScreenLevel1* tempScreen;

    switch (newScreen)
    {
    case SCREEN_INTRO:
        break;
    case SCREEN_MENU:
        break;
    case SCREEN_LEVEL1:
        tempScreen = new GameScreenLevel1(mRenderer);
        mCurrentScreen = (GameScreen*)tempScreen;
        tempScreen = NULL;
        break;
    case SCREEN_LEVEL2:
        break;
    case SCREEN_GAMEOVER:
        break;
    case SCREEN_HIGHSCORES:
        break;
    default:
            break;
    }
}

GameScreenManager.h:
#pragma once
#ifndef _GAMESCREENMANAGER_H
#define _GAMESCREENMANAGER_H
#include <SDL.h>
#include "Commons.h"

class GameScreen;

class GameScreenManager
{
    private:
        SDL_Renderer*    mRenderer;
        GameScreen*      mCurrentScreen;

    public:
        GameScreenManager(SDL_Renderer* renderer, SCREENS startScreen);
        ~GameScreenManager();

        void Render();
        void update(float deltaTime, SDL_Event e);
        void ChangeScreen(SCREENS newScreen);
};

#endif //_GAMESCREENMANAGER_H

Currently the problem occurs on line 24;
    mCurrentScreen->Render();

However if I comment out that line then it appears on line 29:
    mCurrentScreen->Update(deltaTime, e);

"Unhandled exception thrown: read access violation.
this was nullptr. occurred"

A: Apparently, the mCurrentScreen field is NULL when you call Render() or update(). Either protect calls by checking the mCurrentScreen for NULL:
void GameScreenManager::Render()
{
    if (mCurrentScreen != NULL)
        mCurrentScreen->Render();
}

void GameScreenManager::update(float deltaTime, SDL_Event e)
{
    if (mCurrentScreen != NULL)
        mCurrentScreen->Update(deltaTime, e);
}

or make sure that mCurrentScreen is set before calling Render() or Update().

A: As it happens I had actually missed a line of code that set the mCurrentScreen and the switch statement was not passing through correctly so it was not firing. In addition the mRenderer variable was not setup correctly in any of my cpp files, as such returned "Invalid Renderer" whenever I tried to use it. The following is the working code, thanks for the help everyone it steered me in the right direction;
#pragma once
#include <SDL.h>
#include "Commons.h"
#include "GameScreenManager.h"
#include "GameScreenLevel1.h"
#include "GameScreen.h"

GameScreenManager::GameScreenManager(SDL_Renderer* renderer, SCREENS startScreen)
{
    mRenderer = renderer;
    GameScreen* mCurrentScreen = NULL;
    ChangeScreen(startScreen);
}

GameScreenManager::~GameScreenManager()
{
    mRenderer = NULL;
    delete mCurrentScreen;
    mCurrentScreen = NULL;
}

void GameScreenManager::Render()
{
    mCurrentScreen->Render();
}

void GameScreenManager::Update(float deltaTime, SDL_Event e)
{
    mCurrentScreen->Update(deltaTime, e);
}

void GameScreenManager::ChangeScreen(SCREENS newScreen)
{
    //Clear up the old screen
    if (mCurrentScreen != NULL)
    {
        delete mCurrentScreen;
    }

    GameScreenLevel1* tempScreen;

    switch (newScreen)
    {
    case SCREEN_INTRO:
        break;
    case SCREEN_MENU:
        break;
    case SCREEN_LEVEL1:
        tempScreen = new GameScreenLevel1(mRenderer);
        mCurrentScreen = (GameScreen*)tempScreen;
        tempScreen = NULL;
        break;
    case SCREEN_LEVEL2:
        break;
    case SCREEN_GAMEOVER:
        break;
    case SCREEN_HIGHSCORES:
        break;
    default:
        break;
    }
}


text:
Q: flexslider not loading "" Flexslider is not working properly when the content is dynamic. I have tried it for static data, it worked. But it didn't work when the content is dynamic. The problem is it didn't load

. Actually, it loads just for first tablist, it didn't load for rest of the tablists.
My code is something like this:

<?php
   foreach ($cats as $k => $cat)
   {
       $cat = (object) $cat;
       $id = strtolower(str_replace(' ', '-', $cat->category_name));
       $name = ucfirst($cat->category_name);
    ?>
       <li role="presentation" <?php echo $k == 0 ? 'class="active":' : NULL; ?>>
            <a href="#<?php echo $id; ?>" role="tab" data-toggle="tab" id="<?php echo $id; ?>1"><?php echo $name; ?>

<?php } ?>

<?php
     foreach ($cats as $k => $cat)
     {
         $cat = (object) $cat;
         $id = strtolower(str_replace(' ', '-', $cat->category_name));
         $name = ucfirst($cat->category_name);

      ?>
         <div role="tabpanel" class="tab-pane <?php echo $k == 0 ? 'active' : NULL; ?>" id="<?php echo $id; ?>">
             <div id="carousel<?php echo (7 + $k); ?>" class="flexslider">

............
                                  ..........

The final code after loading flexslider should look like

                        <li.......

                        <li.......

But div with id carousel8 didn't load div with class flex-viewport. It only load for category electronics.
Please help me.
Thanks in advance.


text:
Q: MYSQL SELECT CASE with SUM and MAX In this project I'm trying to create a query that returns the total of GPA points of a college student according to his/her grades. I'm using MySQL 5.7.19 and the data is stored as follows:
CourseID     Grade
5              A
8              D-
4              B-
8              B+
2              A

I used a CASE statement to convert the letter grades to numbers and used the MAX function combined with GROUP BY to get only the higher grade from courses taken more than once (in this case course # 8)...
SELECT MAX(
    CASE WHEN Grade = 'A+' OR Grade = 'A' THEN 4
        WHEN Grade = 'A-' THEN 3.67
        WHEN Grade = 'B+' THEN 3.33
        WHEN Grade = 'B'  THEN 3
        WHEN Grade = 'B-' THEN 2.67
        WHEN Grade = 'C+' THEN 2.33
        WHEN Grade = 'C'  THEN 2
        WHEN Grade = 'C-' THEN 1.67
        WHEN Grade = 'D+' THEN 1.33
        WHEN Grade = 'D'  THEN 1
        WHEN Grade = 'D-' THEN 0.67
        ELSE 0 END) AS Grade
FROM courses_taken WHERE Grade IS NOT NULL AND Grade != 'W'
GROUP BY CourseID

That works fine, I get the following results:
Grade
4.00
2.67
3.33
4.00

But I need to get the sum of those values and when I try using the SUM function I get an error:
SELECT SUM(MAX(
    CASE WHEN Grade = 'A+' OR Grade = 'A' THEN 4
        WHEN Grade = 'A-' THEN 3.67
        WHEN Grade = 'B+' THEN 3.33
        WHEN Grade = 'B'  THEN 3
        WHEN Grade = 'B-' THEN 2.67
        WHEN Grade = 'C+' THEN 2.33
        WHEN Grade = 'C'  THEN 2
        WHEN Grade = 'C-' THEN 1.67
        WHEN Grade = 'D+' THEN 1.33
        WHEN Grade = 'D'  THEN 1
        WHEN Grade = 'D-' THEN 0.67
        ELSE 0 END)) AS Total
FROM courses_taken WHERE Grade IS NOT NULL AND Grade != 'W'
GROUP BY CourseID

ERROR 1111 (HY000): Invalid use of group function
I tried removing the GROUP BY clause but I got the same error. I also removed MAX and GROUP BY, it worked, however, I got the total of all the grades, which is not what I want. I was wondering what exactly I'm doing wrong or if there is any other way to accomplish this.
Thanks.

A: You can't stack multiple aggregate expressions in the same query. The trick is to use a sub query for the inner aggregate & wrap it in another query for the 2nd aggregate.
SELECT SUM(Grade) Total
FROM (
SELECT MAX(
    CASE WHEN Grade = 'A+' OR Grade = 'A' THEN 4
        WHEN Grade = 'A-' THEN 3.67
        WHEN Grade = 'B+' THEN 3.33
        WHEN Grade = 'B'  THEN 3
        WHEN Grade = 'B-' THEN 2.67
        WHEN Grade = 'C+' THEN 2.33
        WHEN Grade = 'C'  THEN 2
        WHEN Grade = 'C-' THEN 1.67
        WHEN Grade = 'D+' THEN 1.33
        WHEN Grade = 'D'  THEN 1
        WHEN Grade = 'D-' THEN 0.67
        ELSE 0 END) AS Grade
FROM courses_taken WHERE Grade IS NOT NULL AND Grade != 'W'
GROUP BY CourseID) max_grade


text:
Q: Change the height of UINavigationBar I'm trying to change the UINavigationBar height.
I found various solutions to solve this but none of them worked/made my app crash.
For Example how to increase the height of navigation bar in xcode?
I'm using iOS 11/10/9 by the way...
Thanks (:


text:
Q: can two component with different fields have a common component in react? i have two components in which i am rendering different list, each of the list are table which are created using div's.
i want to make a common component to render both the list with the same style, but cannot figure out how to approach it since the field values are different.
basically i have displayed my list inside container so i want to move these containers into a common container.
----1- network list component container-
<Container className={classes.tableContainer} maxWidth={false}>

NETWORKS

              {data?.networks.nodes?.map(
                (network) =>
                  network && (

{network.name}

{network.defaultShow?.name ?? ''}

        {network.locationCount}
        {network.locationCount === 1 ? 'location' : 'locations'}

        {network.deviceCount}
        {network.deviceCount === 1 ? 'device' : 'devices'}

        {network.userCount}

             {network.userCount === 1 ? 'user' : 'users'}

                <TableActionLink
                  className={classes.settings}
                  title="Settings"
                  Icon={Settings}
                  to={route(`/settings/network/${network.slug}/settings`)}
                />
                <TableAction
                  className={classes.moreActions}
                  {...moreTableActionProps(network)}
                />

          ),
      )}

        <Menu {...moreMenuProps}>
          <MoreDeleteAction
            {...moreActionProps}
            onClick={async () => {
              assert(moreMenuProps.context !== undefined);
              if (!(await confirmDelete())) return;
              try {
                await deleteNetwork({
                  variables: { networkId: moreMenuProps.context.id },
                });
              } catch (error: unknown) {
                alert('could not delete network');
              } finally {
                moreMenuProps.onClose();
              }
            }}
          />
        </Menu>

        <TablePagination {...paginationProps} />

        <ConfirmDialog {...confirmDeleteProps} />

    </Container>

----2-user table component container-
 <Container className={classes.tableContainer} maxWidth={false}>
                <UserTable
                  users={data?.users}
                  paginationProps={paginationProps}
                  sortProps={sortProps}
                />
   </Container>

--userTable:

USERS

          {
            //rows.map(({ /* checkboxProps, */ labelProps, row: user, rowProps }) => foo)
            nodes.map((user) => (

        {/* <TableCheckbox checkboxProps={checkboxProps} /> */}

          <UserAvatar user={user} className={classes.avatar} />
          {user.name}

{user.email}

{role}

{user.confirmedAt ? 'Active' : 'Not Verified'}

{formatDateString(user.currentSignInAt)}

          <TableActionLink
            className={classes.settings}
            title="Settings"
            Icon={Settings}
            to={route(`/settings/network/users/${user.slug}/settings`)}
          />
          {currentUser.admin && (
            <TableAction className={classes.moreActions} {...moreTableActionProps} />
          )}

            ))
          }

      <Menu {...moreMenuProps}>
        {moreMenuProps?.context?.canDestroy.value && (
          <MoreDeleteAction
            {...moreActionProps}
            onClick={async () => {
              assert(moreMenuProps.context !== undefined);
              if (!(await confirmDelete())) return;
              try {
                await deleteUser({
                  variables: { userId: moreMenuProps.context.id },
                });
              } catch (error: unknown) {
                alert('could not delete user');
              } finally {
                moreMenuProps.onClose();
              }
            }}
          />
        )}
      </Menu>

      <TablePagination {...paginationProps} />

      <ConfirmDialog {...confirmDeleteProps} />

currently the component i made looks like this :
interface listTableProp {
  tableHeading: string;
  children?: ReactElement;
  data?: any;
}

export const ListTable = ({ tableHeading, children, data }: listTableProp) => {
  // hooks
  const classes = useStyles();

  return (
    <Container className={classes.tableContainer} maxWidth={false}>

{tableHeading}

{children}

    </Container>
  );
};

but instead of rendering rows as direct children, i want to know if its possible to render rows with styling from this component only.


text:
Q: Spring boot microservices exception behaviour with @ControllerAdvice & @CircuitBreaker My question is related to exception behaviour in microservices.
Suppose we have a microservice(Let's say microservice-A) having a controller advice annotated class to handle all exceptions.
Also my microservice-A is calling one another microservice(let's say microservice-B). Assuming this call is happening from a service layer method annotated with @CircuitBreaker(name="myService", fallback="myFallbackMethod")
So if I introduce any runtime exception after the successful call to the microservice-B, will the fallback method execute, or will the @ExceptionHandler annotated method present in the @ControllerAdvice annotated class execute?
Attaching the piece of poc
    //Microservice-A
    package com.example.iplservice.controller;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.env.Environment;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import com.example.iplservice.feign.MyFeignClient;
    import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;

    @RestController

    @RequestMapping("ipl")

    public class IplController {

        @Value("${ipl.team}")
        private String iplTeam;

        @Autowired
        private Environment env;

        @Autowired
        private MyFeignClient myFeignClient;

        @GetMapping("/team/hello")
        @CircuitBreaker(name = "cricketService", fallbackMethod = "getHelloFallBack")
        public ResponseEntity < String > getHello() {
            String body = myFeignClient.getHello().getBody();
            //introducing an error here!!
            int a = 2 / 0;
            System.out.println("-----------------" + a);
            return ResponseEntity.ok("Hello " + iplTeam + " : " + env.getProperty("local.server.port") + " : Called : " + body);
        }
    }
    //Microservice-A ends

    //Microservice-A Controller Advice
    package com.example.iplservice.excetion;

    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

    @ControllerAdvice
    public class CricketExceptionHandler extends ResponseEntityExceptionHandler {

        @ExceptionHandler(Exception.class)
        public ResponseEntity < String > handleGenericException(Exception ex) {
            return ResponseEntity.ok("Error From Controller Advice : " + ex.getMessage());
        }
    }
    //Microservice-A Controller Advice ends

    //Microservice-B
    package com.example.cricketersdetailservice.controller;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.cloud.context.config.annotation.RefreshScope;
    import org.springframework.core.env.Environment;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    @RefreshScope
    @RequestMapping("/cricket")
    public class CricketController {

        @Value("${cricketer.team}")
        private String teamName;

        @Autowired
        private Environment env;

        @GetMapping("/team/hello")
        public ResponseEntity < String > getHello() {
            return ResponseEntity.ok("Hello " + teamName + " : " + env.getProperty("local.server.port"));
        }
    }
    //Microservice-B ends

A: As I can see on the code, the fallback method will be triggered. Even tough the call to micro-service B was successful, the Circuit Breaker will watch every exception that occurs on the method getHello.
If you want to change this behavior, there are some alternatives:

*

*Decorate only the feign client method call with the circuit-breaker

*Separate the feign client call on a new method and annotate that method with @CircuitBreaker

*Configure the circuit-breaker to watch only some specific exceptions thrown by feign client

Check resilience4j docs here and here


text:
Q: Contagem de Números usando Array em C Como fazer para contar inteiros usando um array em C, nesse modelo:
Entrada> duas strings com "inteiros"
ex: 8 15
Saída> Um string com os números do intervalo, inclusivo:
ex: 8 9 10 11 12 13 14 15.
Provavelmente uma dúvida básica, mas sou iniciante na área ainda.
Obrigado!

A: Vamos lá, se for em C que você precisa então segue:
//Define a entrada dos 2 valores
char rangeStr[] = "8 15";
//Define a variavel que vai armazenar os valores convertidos
int rangeInt[2] = { 0, 0 };

//Tokeniza a string com delimitador ' '
char* splitedRange = strtok(rangeStr, " ");

//Define a variavel de contagem para garantir que apenas 2 valores sejam atribuidos
int i = 0;
//inicializa o loop para extrair os valores entre ' ' e garantir que sejam até 2
while (splitedRange && i < 2)
{
    //verifica se o valor recebido é numérico
    if (isdigit(*splitedRange))
        rangeInt[i] = atoi(splitedRange);
    splitedRange = strtok(NULL, " ");
    i++;
}
//Cria o looping em cima dos dois valores entregues
for (int start = rangeInt[0]; start <= rangeInt[1]; start++)
    printf("%d\n", start);


text:
Q: Опустить скролл после загрузки в див данных есть блок с сообщениями

 0" ref="msg_wrapper">

        <div class="chat--user__image" v-bind:style='{ backgroundImage: `url("/storage/${message.avatar}")` }'>

как после загрузки из метода
selectUser(id){
                axios.post('/profile/dialogs/messages',{
                    dialog_id: id,
                    offset: this.offset,
                    limit: this.limit
                })
                    .then((response) => {
                        this.messages = response.data.messages;
                        this.dialog.like = response.data.like;
                        this.dialog.favorite = response.data.favorite;
                        this.dialog.ignore = response.data.ignore;
                    })
                    .catch(error => {});
            },

опустить скролл блока .chat--messages__wrapper вниз?

A: Как то так

      div

A: Хотел бы дополнить немного ответ Alexandra Lonberga
Чтобы не использовать setTimeout, который постоянно будет запускать проверку, можно использовать библиотеку (А остальное по логике Александра(Не стал копи пастить))

  /**
     * Copyright Marc J. Schmidt. See the LICENSE file at the top-level
     * directory of this distribution and at
     * https://github.com/marcj/css-element-queries/blob/master/LICENSE.
     */

    (function(root, factory) {
        if (typeof define === "function" && define.amd) {
            define(factory);
        } else if (typeof exports === "object") {
            module.exports = factory();
        } else {
            root.ResizeSensor = factory();
        }
    }(this, function() {

        // Make sure it does not throw in a SSR (Server Side Rendering) situation
        if (typeof window === "undefined") {
            return null;
        }
        // Only used for the dirty checking, so the event callback count is limited to max 1 call per fps per sensor.
        // In combination with the event based resize sensor this saves cpu time, because the sensor is too fast and
        // would generate too many unnecessary events.
        var requestAnimationFrame = window.requestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            function(fn) {
                return window.setTimeout(fn, 20);
            };

        /**
         * Iterate over each of the provided element(s).
         *
         * @param {HTMLElement|HTMLElement[]} elements
         * @param {Function}                  callback
         */
        function forEachElement(elements, callback) {
            var elementsType = Object.prototype.toString.call(elements);
            var isCollectionTyped = ('[object Array]' === elementsType ||
                ('[object NodeList]' === elementsType) ||
                ('[object HTMLCollection]' === elementsType) ||
                ('[object Object]' === elementsType) ||
                ('undefined' !== typeof jQuery && elements instanceof jQuery) //jquery
                ||
                ('undefined' !== typeof Elements && elements instanceof Elements) //mootools
            );
            var i = 0,
                j = elements.length;
            if (isCollectionTyped) {
                for (; i < j; i++) {
                    callback(elements[i]);
                }
            } else {
                callback(elements);
            }
        }

        /**
         * Class for dimension change detection.
         *
         * @param {Element|Element[]|Elements|jQuery} element
         * @param {Function} callback
         *
         * @constructor
         */
        var ResizeSensor = function(element, callback) {
            /**
             *
             * @constructor
             */
            function EventQueue() {
                var q = [];
                this.add = function(ev) {
                    q.push(ev);
                };

                var i, j;
                this.call = function() {
                    for (i = 0, j = q.length; i < j; i++) {
                        q[i].call();
                    }
                };

                this.remove = function(ev) {
                    var newQueue = [];
                    for (i = 0, j = q.length; i < j; i++) {
                        if (q[i] !== ev) newQueue.push(q[i]);
                    }
                    q = newQueue;
                }

                this.length = function() {
                    return q.length;
                }
            }

            /**
             *
             * @param {HTMLElement} element
             * @param {Function}    resized
             */
            function attachResizeEvent(element, resized) {
                if (!element) return;
                if (element.resizedAttached) {
                    element.resizedAttached.add(resized);
                    return;
                }

                element.resizedAttached = new EventQueue();
                element.resizedAttached.add(resized);

                element.resizeSensor = document.createElement('div');
                element.resizeSensor.className = 'resize-sensor';
                var style = 'position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: hidden; z-index: -1; visibility: hidden;';
                var styleChild = 'position: absolute; left: 0; top: 0; transition: 0s;';

                element.resizeSensor.style.cssText = style;
                element.resizeSensor.innerHTML =
                    '
' +
                    '

' +
                    '
' +
                    '
' +
                    '

' +
                    '
';
                element.appendChild(element.resizeSensor);

                if (element.resizeSensor.offsetParent !== element) {
                    element.style.position = 'relative';
                }

                var expand = element.resizeSensor.childNodes[0];
                var expandChild = expand.childNodes[0];
                var shrink = element.resizeSensor.childNodes[1];
                var dirty, rafId, newWidth, newHeight;
                var lastWidth = element.offsetWidth;
                var lastHeight = element.offsetHeight;

                var reset = function() {
                    expandChild.style.width = '100000px';
                    expandChild.style.height = '100000px';

                    expand.scrollLeft = 100000;
                    expand.scrollTop = 100000;

                    shrink.scrollLeft = 100000;
                    shrink.scrollTop = 100000;
                };

                reset();

                var onResized = function() {
                    rafId = 0;

                    if (!dirty) return;

                    lastWidth = newWidth;
                    lastHeight = newHeight;

                    if (element.resizedAttached) {
                        element.resizedAttached.call();
                    }
                };

                var onScroll = function() {
                    newWidth = element.offsetWidth;
                    newHeight = element.offsetHeight;
                    dirty = newWidth != lastWidth || newHeight != lastHeight;

                    if (dirty && !rafId) {
                        rafId = requestAnimationFrame(onResized);
                    }

                    reset();
                };

                var addEvent = function(el, name, cb) {
                    if (el.attachEvent) {
                        el.attachEvent('on' + name, cb);
                    } else {
                        el.addEventListener(name, cb);
                    }
                };

                addEvent(expand, 'scroll', onScroll);
                addEvent(shrink, 'scroll', onScroll);
            }

            forEachElement(element, function(elem) {
                attachResizeEvent(elem, callback);
            });

            this.detach = function(ev) {
                ResizeSensor.detach(element, ev);
            };
        };

        ResizeSensor.detach = function(element, ev) {
            forEachElement(element, function(elem) {
                if (!elem) return
                if (elem.resizedAttached && typeof ev == "function") {
                    elem.resizedAttached.remove(ev);
                    if (elem.resizedAttached.length()) return;
                }
                if (elem.resizeSensor) {
                    if (elem.contains(elem.resizeSensor)) {
                        elem.removeChild(elem.resizeSensor);
                    }
                    delete elem.resizeSensor;
                    delete elem.resizedAttached;
                }
            });
        };

        return ResizeSensor;

    }));
    $('#click').on('click', function () {
        $('#Test_DIV').append('
SomeNewlines
');
    });

    new ResizeSensor(jQuery('#Test_DIV'), function(){
        console.log('Размер div изменился');
    });

 Тут что-то;

<button id="click">Тык</button>


text:
Q: preLaunchTask " " terminated with exit code -1 I'm trying to debug a C++ file in VSCode, I followed all the instructions of VSCode but this always shows up. I am using Windows 10. If I click  Debug Anyway It will not hit any breakpoint. How do I fix it?  The error.
This is my cpp file (so you can also see the explorer tab).
This is the code
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};

    for (const string& word : msg)
    {
        cout << word << " ";
    }
    cout << endl;
    return 0;
}

This is the directory to the c++ file.
C:\Users\ADMIN\Desktop\Program\CppNew\helloworld.cpp
I use this option to debug in VSCode
g++.exe
{ //tasks.json
    "tasks": [
        {
            "type": "cppbuild",
            "label": "BuildProject",
            "command": "C:\\msys64\\mingw64\\bin\\g++.exe",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\helloworld.exe"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build",
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

{ //launch.json
    "version": "0.2.0",
    "configurations": [
        {
            "name": "C/C++: g++.exe build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
                    "description": "Set Disassembly Flavor to Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "BuildProject"
        }
    ]
}

My Debugging Console Log
=thread-group-added,id="i1"
GNU gdb (GDB) 12.1
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-w64-mingw32".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word".
Warning: Debuggee TargetArchitecture not detected, assuming x86_64.
=cmd-param-changed,param="pagination",value="off"

Thread 1 hit Breakpoint 1, 0x00007ff7e987146c in main ()
Loaded 'C:\Windows\SYSTEM32\ntdll.dll'. Symbols loaded.
Loaded 'C:\Windows\System32\kernel32.dll'. Symbols loaded.
Loaded 'C:\Windows\System32\KernelBase.dll'. Symbols loaded.
Loaded 'C:\Windows\System32\msvcrt.dll'. Symbols loaded.
Loaded 'C:\msys64\mingw64\bin\libgcc_s_seh-1.dll'. Symbols loaded.
Loaded 'C:\msys64\mingw64\bin\libstdc++-6.dll'. Symbols loaded.
Execute debugger commands using "-exec <command>", for example "-exec info registers" will list registers in use (when GDB is the debugger)
Single stepping until exit from function main,
which has no line number information.
[Thread 11160.0x2ff4 exited with code 0]
[Thread 11160.0x459c exited with code 0]
[Thread 11160.0x37bc exited with code 0]
[Inferior 1 (process 11160) exited normally]
The program 'c:\Users\ADMIN\Desktop\Program\CppNew\helloworld.exe' has exited with code 0 (0x00000000).

These are my g++, gcc, and gdb versions.
g++ (Rev7, Built by MSYS2 project) 12.2.0
gcc (Rev7, Built by MSYS2 project) 12.2.0
GNU gdb (GDB) 12.1
This is my directory to bin (also in my PATH)
C:\msys64\mingw64\bin
I tried reinstalling mingw through msys2 but it still didn't work. I tried putting absolute values in
    "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",

but it says my file does not exist.
Update:
I change this from tasks.json
 "options": {
                "cwd": "C:\\Users\\ADMIN\\Desktop\\Program\\CppNew"
            },

Also changed this from launch.json
 "program": "C:\\Users\\ADMIN\\Desktop\\Program\\CppNew\\helloworld.exe",
"cwd": "C:\\Users\\ADMIN\\Desktop\\Program\\CppNew",

It is also active when I try to click the debug button.

Tried restarting VSCode after I input the absolute values.
Still not working. Same error.


text:
Q: Best constant for Poincaré inequality on spheres I am interested in the following Poincaré-type inequality,
$$ \int_{S(r)} \lvert u-\bar{u}\rvert^2 d\sigma  \leq C(N) \int_{S(r)} |u_{\theta}|^2 d\sigma$$
where $\bar{u} = \frac{1}{\lvert S(r)\rvert}\int_{S(r)} u d\sigma$ and $u_{\theta}$ denotes the tangential derivative of $u$.  The domain $S(r)$ is just the $N$-dimensional sphere with radius $r$. The function $u$ can be assumed to be smooth for the purpose of this question.
In the case $S(r)$ is $1$ dimensional (i.e. a circle), then the constant $C(1)=1$ and this is the Wirtinger's inequality. Are there any references where I can find the best constant in higher dimensions?

A: The best constant is just the multiplicative inverse of the smallest positive eigenvalue of the Laplacian on the sphere. On $\mathbb{S}^N$ this the smallest eigenvalue is $N$, so $C(N)$ in that case equals $1/N$.
You can figure out the appropriate $r$ scaling yourself.


text:
Q: How to create a working initial app release with Firebase OTP and Google App Signing without re-releasing? I have a white-label app that uses OTP phone verification via Firebase. I plan to brand and publish this app several times with distinguishable icons and themes under different names.
I want to use Google App Signing in which I release a bundle file (.aab) and let Google sign the application for me. This is what Google recommends, because it will prevent the keystore from being leaked / exploited. After all, using Google App Signing will streamline the publishing experience, since Apple will sign my app for the App Store as well. I also want to restrict my Firebase API key that is added in the Google Cloud.
In summery: The SHA-1 and SHA-256 signature hash from Google's keystore needs to be added in the project settings of Firebase and in the app restriction section of my Firebase API key within the Google Cloud Credentials dashboard, because only then I can use the Firebase OTP phone verification. However, I also have to download the google-services.json and add it to my app build. If I don't do the last step, I will still get the error:

E FirebaseAuth     [SmsRetrieverHelper] SMS verification code request failed: unknown status code: 17499 Requests from this Android client application are blocked.

To fix this, I have to provide the SHA-1 and SHA-256 hash to Firebase before building my app, since I have to download and add the google-services.json to my build after this step. The crux is, I cannot obtain the signing hashes before creating a release:

Long story short: I have to create a release with a wrong google-services.json to be able to obtain my SHA-1 and SHA-256, which I then add in Firebase, re-download my now correct google-services.json just to create another release and to fix my app?
This is a heavy additional step that feels absolutely unnecessary and hindering for mass publishing.
Is there any way to circumvent this terrible design choice by Google to make my app work with OTP Firebase phone verification on the initial release when using Google App Signing?


text:
Q: React PWA without https - what are the limitations?
Service workers require HTTPS ... If your production web server does
not support HTTPS, then the service worker registration will fail, but
the rest of your web app will remain functional.

quoted from the docs at https://create-react-app.dev/docs/making-a-progressive-web-app.
What does it mean the rest of your web app will remain functional, but service worker registration will fail? In other words, if my app remains functional, do  I really care if service worker has failed? (what are the limitations?)

A: So your app would still work, but you would lose all of the functionality provided with the service worker. At the bottom of the "Why Opt-in?" section of the Making a Progressive Web App it states:

The workbox-webpack-plugin is integrated into production configuration, and it will take care of generating a service worker file that will automatically precache all of your local assets and keep them up to date as you deploy updates. The service worker will use a cache-first strategy for handling all requests for local assets, including navigation requests for your HTML, ensuring that your web app is consistently fast, even on a slow or unreliable network.

So you could use it as normal but you would lose:

*

*Offline support,

*Precaching of your local assets,

*Cache-first approach for your local assets and navigation requests,

*Performance improvements of your application in slow or unreliable network conditions.

Whether or not you care if it fails is directly related to if you value these features in your application. If they are critical to your application, you probably care a lot. If it doesn't matter to you either way or affect your end-user, it's probably not a big deal.
You can find out more about Service Workers and why they only work using HTTPS in the Service Workers API documentation


text:
Q: Docker RUN Not Finding an Executable File I am having issues setting up a Dockerfile in Ubuntu. I tried the following command:
sudo docker build -t chaste .

But when it reaches to the following command:
RUN chmod +x chaste.sh && ./chaste.sh -q && rm -f chaste.sh

I get the following error:
chmod: cannot access 'chaste.sh': No such file or directory

However, chaste.sh is in the current directory. I am not sure why it complains about not being able to find it.
I would appreciate it if someone could help me out.

A: To use the file from current directory you should add it from build context to the container by adding the following command above RUN command in your Dockerfile:
ADD ./chaste.sh ./chaste.sh


text:
Q: Chrome v70+ has issue with innerText in td cells This was working in v69 and lower.
Every innerText value of a cell before the last has a trailing character.
Check it out here: http://jsfiddle.net/L16x9gpe/

        1
        2
        3

Edit: I have raised an issue with Chromium development here: https://bugs.chromium.org/p/chromium/issues/detail?id=897373 It seems all browsers at the moment do not contain the trailing character issue, including Firefox where the original specification apparently was derived. The commit author Yoshifumi Inoue (yosin@chromium.org) has stated this should be the correct implementation. I think it should act like other browsers and not have this differentiating behavior. The whatwg spec should be changed to be more specific and only include a trailing tab character (U+0009) for table or row innerText calls instead of a direct call to a td cell.

A: I have the exact same problem. The workaround I'm using for now is changing my code to cell.innerText.trim().

A: It appears that the Chrome team "fixed a glitch" that hadn't been working correctly, according to the standard (based on the link below).
This caught me off-guard with an inherited application, as well.
innerText functionality

A: I am doing some simple text comparison, so I switched to .innerHTML because it seems to not have the same tab/LF append requirements that .innerText has.
In my case, the cells don't have any HTML in them. I thought that .innerText was more clear that I only wanted the text. But, I guess, if you are converting table cells to text you would want to have those separator characters.

A: This broke an extension I wrote for a client. I was checking cells[blah].innerText == 'somevalue', and those checks became false with the update when they should be true.
Changing innerText to textContent fixed it, which is counter-intuitive, because textContent is supposed to preserve whitespace the same as a pre tag, and innerText is supposed to just get you the text.


text:
Q: Java wrong timezone As can be seen below, system time and SoapUI's time value is different.

SoapUI using JRE time and that's why it should be a bug of Java's itself because; also below code gives: Venezuela Time
String tzn = TimeZone.getDefault().getDisplayName();
System.out.println(tzn);

What I've tried and failed:

*

*Playing with regedit and changing time zone then get it back to correct.

*Giving -Duser.timezone="Europe/Istanbul" at Control Panel/Java/JRE Settings/Runtime Parameters or giving same parameter inside the JAVA_OPTS variable.

*Changing time or time zone and get it back.

I checked this question surely, correcting the timezone programmatically is doable but I need to correct SoapUI's timezone which affects automated test results. Because tests are time dependent.

A: I really tried hard to solve this issue, for days. I really don't know why the most plausible two methods are not working properly which:

*

*Creating JAVA_OPTS system variable which has the value of: -Duser.timezone="Turkey"

*Passing vm parameter from command line.

At last I gave up and set this parameter for each specific program, to be able to do this for SoapUI, go to SoapUI Home Path/bin folder and right click to soapui-pro.bat and choose to edit. (If you are using the community version, the name of the bat file will be different)
Then go to line 29 which starts with set JAVA_OPTS=-Xms128m... and insert time-zone parameter: -Duser.timezone="Turkey". Now execute the bat file, it's going to start to work properly!


text:
Q: I compiled an app with apktool_2.6.1 and i didn't make any changes to the app but when i run : apktool b app.apk I got the following error:

invalid resource directory name: C:\Users\test\Documents\APK Easy Tool\1-Decompiled APKs\com.app.app2\res navigation
brut.androlib.AndrolibException: brut.common.BrutException: could not exec (exit code = 1): [C:\Users\test\AppData\Local\Temp\brut_util_Jar_121707779579717501731948984067731632634.tmp, p, --forced-package-id, 127, --version-code, 4591, --version-name, 4.59.1, --no-version-vectors, -F, C:\Users\test\AppData\Local\Temp\APKTOOL3747578255524950029.tmp, -e, C:\Users\test\AppData\Local\Temp\APKTOOL7131208164915828680.tmp, -0, arsc, -I, C:\Users\test\AppData\Local\apktool\framework\1.apk, -S, C:\Users\test\Documents\APK Easy Tool\1-Decompiled APKs\com.app.app2\res, -M, C:\Users\Everspin\Documents\APK Easy Tool\1-Decompiled APKs\com.app.app2\AndroidManifest.xml]

A: You should move to aapt2. Add --use-aapt2 during compilation and make sure you update to a more recent version.
You can tell from the res / navigation error that you are rebuilding an application and that was built from aapt2 with aapt1.


text:
Q: Automated data frame summaries with mixed data types I am trying to automatically create a new data frame that, given an existing data frame, contains either the median of a numerical variable or the most common category for a factor.  So:
Number Factor
3      A
2      A
5      B

Should turn into
Number Factor
3      A

I can calculate it for each variable individually. For purely numerical variables I could even use the colMeans command. For purely factor variables I would use which.max(). But I have not been able to combine the two into a scalable and flexibe solution

A: You can use lapply with if branching:
y <- read.table(text = "Number Factor
3      A
2      A
5      B", header = TRUE)

as.data.frame(lapply(y, function(x) {
if (is.numeric(x)) return (median(x))
else return(x[which.max(table(x))])
}))

A: you can test something like that:
FUN <- function(x) {
  if (is.numeric(x))
     return(median(x))
  else
     x <- sort(as.character(x))
  rl1 <- rle(x)
  rl1$val[which.max(rl1$le)]
  }

as.data.frame(lapply(tab, FUN))
aggregate(tab, by=list(gl(1,nrow(tab))), FUN=FUN)
# even easier
bob <- lapply(tab, function(x) if(is.numeric(x)) median(x) else x[median(as.numeric(x))])
as.data.frame(bob)

A: as.data.frame( lapply(dfrm, function(x) if(is.numeric(x)) {
                            median(x) } else {
                            names(sort( table(x) , decreasing=TRUE )[1])
                                             })
              )


text:
Q: Updating a collection I would like to create a PL/SQL function which return a list of element. I've already created a new type like this:
CREATE OR REPLACE TYPE listeIngredient_col AS OBJECT
(
  idIngredient int,
  nomIngredient varchar(25),
  quantite int,
  dateE date
);
/

CREATE OR REPLACE TYPE  isteIngredient_tab IS TABLE OF listeIngredient_col;
/

There is my function
CREATE OR REPLACE FUNCTION genererListe(user IN INT, dateEstime IN date)
RETURN isteIngredient_tab
AS
  tab_res isteIngredient_tab;

  quantiteAacheter INT;
  quantitePosseder INT :=0;
  exist INT;

-- Cursor on recipe
  CURSOR cursor_recette IS
  SELECT r.* FROM Recette r
  JOIN planning p
  ON p.idRecette=r.idrecette
  JOIN Utilisateur u
  ON p.idUtilisateur=u.idUtilisateur
  WHERE u.idUtilisateur=1
  AND p.jour>dateEstime;

BEGIN
  tab_res  := isteIngredient_tab();

  FOR row_recette IN cursor_recette
  LOOP

    --Iterate on all ingredient of a recipe
    FOR result IN (SELECT i.*,ir.quantite FROM Ingredient i
                  JOIN IngredientRecette ir
                  ON ir.idIngredient=i.idIngredient
                  JOIN Recette r
                  ON r.idRecette=ir.idRecette
                  WHERE i.Disponibilite = 'N'
                  AND r.idRecette=row_recette.idrecette)
                  LOOP
                    SELECT CASE

                    -- Check if an ingredient is already present in the tab_res
                    WHEN EXISTS(select * from table(tab_res) WHERE idIngredient = result.idIngredient)
                    THEN 1
                    ELSE 0
                    END INTO exist
                    FROM dual;

                    --If it is not present, add a new line in tab_res
                    IF exist = 0 THEN
                    tab_res.extend;
                    tab_res(tab_res.count) := listeIngredient_col(result.idIngredient,
                                                                  result.nom,
                                                                  5,
                                                                  dateEstime);

                    -- If it is present uprgrade quantity value
                    ELSE

                    UPDATE table(tab_res)
                    SET quantite=quantite+result.quantite
                    WHERE idIngredient = result.idIngredient;
                    END IF;

          END LOOP;
    END LOOP;
    RETURN tab_res;
END;
/

The problem is, sometime I want to add a new line in the result tab and sometime I want to update a specific line in the result table but the update doesn't work.
 UPDATE table(tab_res)
 SET quantite=quantite+result.quantite
 WHERE idIngredient = result.idIngredient;

Hhe error is: ORA-00903: invalid table name.
It is possible to update like this ? Or there is an another solution ?

A: you don't need to use like table(tab_res) fro an update statement, just using tab_res is enough like below :
                UPDATE tab_res
                   SET quantite=quantite+result.quantite
                 WHERE idIngredient = result.idIngredient;