text:
Q: ESATA Detection / Boot Here is the issue.
I recently bought an extention card to add an ESATA port to my computer at home that allows me to do my school work at home.
when the esata drive is plugged into the card, i can see the drive and explore it in windows 10 booted on my main disk. it is also seen by the disk partition tool. So in all logic, the card is fine and the cable is good.
But it is NOT detected by my UEFI BIOS and therefore i cannot boot from it.
When i try to boot on it via usb 3.0, it fails every time.
Any suggestions ?

Edit :
The disk has 3 partitions (mbr)
0 : Windows Server 2012 (ntfs)
1 : Linux CentOs (ext4)
3 : swap (linux-swap)
The cloned one i tried was the same but with a GPT partition table.

A:
The disk has 3 partitions (mbr) 0 : Windows Server 2012 (ntfs) 1 : Linux CentOs (ext4) 3 : swap (linux-swap)

This is a typical Windows+Linux dual-boot in Legacy (BIOS) mode. That alone prevents it from being booted in UEFI mode which is the current mode you have for the internally installed Windows 10. As already mentioned in comments by @Ramhound :

You cannot boot to an MBR disk while in UEFI mode. (...) You will have to wipe all partitions, use GPT instead, and in order to boot to an OS it would have to contain the required EFI drivers.

To which you replied

But when i cloned it to a GPT disk. It still didnt see it in the BIOS

It should be easy to understand why it didn't when you know how UEFI mode works and the specific OS requirements for each OS regarding that mode.
https://help.ubuntu.com/community/UEFI
The above link is generally applicable to almost all other major Linux distros and the information is presented in a simple and educational way. It's a good starting point but doesn't replace the required specific knowledge about the PC's firmware. How to access the settings and the settings themselves vary a lot depending on the UEFI/BIOS manufacturer. The Ubuntu documentation tries to be as generic as possible but can't cover all possible variants therefore users must be familiar with their own specific UEFI/BIOS settings.
Also of notice is the specific partitioning required. Windows strictly requires MBR ("msdos") for Legacy and GPT for UEFI. @Dial, in comments, posted a very nice link to help understand the differences: https://wiki.manjaro.org/index.php?title=Some_basics_of_MBR_v/s_GPT_and_BIOS_v/s_UEFI
Addendum: As also pointed out in my own comments,

You may change the mode at the firmware (UEFI) settings, then set the external HDD as the first boot device, changing it back to the original settings whenever you need to use the internally installed OS.

The change is from UEFI mode to Legacy (AKA "Legacy" AKA "BIOS") if the intention is to boot the external HDD as it is know. Please note it's imperative to change it back to the original settings to boot the installed Windows. Please also note this is just a workaround and understand that neither OS in question was meant to be used as "portable". Virtualization is often used instead and that is something you should consider for furthering your studies.
For a generic yet comprehensive guide about the requirements and method for dual booting in UEFI mode (recommended)please refer to https://askubuntu.com/questions/221835/how-do-i-install-ubuntu-alongside-a-pre-installed-windows-with-uefi .


text:
Q: Keep getting last value in for loop I'm trying to get all the values in the variable roomnum, but the last value of roomnum keeps showing up. However, when I tried to print roomnum the values show up correctly. I'm not quite sure where the problem lies.
roomnum = request.POST.getlist('polygon-names')
            print(roomnum)

for k,v in unique_keys.items():
                if category_in_excel == "Material":
                    color_cell_format = workbook.add_format({'font_color': 'black', 'bg_color': v['color']})
                    color_cell_format.set_align('center')
                    worksheet.write(row + 1, col, k, cell_format)
                    worksheet.write(row + 1, col + 1, v['color'], color_cell_format)
                    worksheet.write(row + 1, col + 2, convert_quantity_from_mm_squared_to(units, v['initialArea'], precision), cell_format)
                    worksheet.write(row + 1, col + 3, units, cell_format)
                    worksheet.write(row + 1, col + 4, ",".join(v['pages']), cell_format)
                else:
                    for i in roomnum:
                        print(i)
                        worksheet.write(row + 1, col, i, cell_format)
                    worksheet.write(row + 1, col + 1, convert_quantity_from_mm_squared_to(units, v['initialArea'], precision), cell_format)
                    worksheet.write(row + 1, col + 2, units, cell_format)
                    worksheet.write(row + 1, col + 3, ",".join(v['pages']), cell_format)

Terminal when I print out the i value in roomnum:
Values that I get in excel worksheet:
As shown, the value keeps repeating for Polygon 3, when it should be Polygon 1,2,3. Any help would be greatly appreciated thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laptop screen dims after 20 seconds, cannot change that On my HP laptop with Fedora 23, screen dims after 20 seconds when using batteries, and I couldn't find a way to change that. I've set
gsettings set org.gnome.settings-daemon.plugins.power idle-dim false

but it doesn't seem to have any effect.
This is annoying and forces me to keep the laptop connected to the power plug at all times.
Is there a way to increase the delay or to turn it off?

A: After updating to the latest kernel version (4.3.3-303) the problem disappeared.  Apparently the gsettings command above is now taking effect.


text:
Q: wxPython: binding multiple widgets - Frame e Panel - to the same handler Let's assume to have this code:
#!/usr/bin/python
# _*_ coding: utf-8 _*_
import wx

class wxappsubclass(wx.App):
  def OnInit(self):
    frame=wxframesubclass(None, -1, 'MyName')
    frame.Show(True)
    return True

class wxframesubclass(wx.Frame):
  def __init__(self, parent, id, title):
    wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, size=(320, 240))
    panel=panel1(self)
    menubar=wx.MenuBar()
    menufile=wx.Menu()
    ExitItem=menufile.Append(wx.NewId(), '&Exit\tCtrl+Q', "Exit")
    menubar.Append(menufile, '&File')
    self.SetMenuBar(menubar)

    ## BINDING ##
    self.Bind(wx.EVT_MENU, self.CloseProgramFromFrame, ExitItem)

  def CloseProgramFromFrame(self, event):
    self.Close(True)

class panel1(wx.Panel):
  def __init__(self, parent):
    wx.Panel.__init__(self, parent, -1)
    ID_EXIT_BUTTON=wx.NewId()
    ExitButton=wx.Button(self, wx.NewId(), label="Exit")
    self.Bind(wx.EVT_BUTTON, self.CloseProgramFromPanel, ExitButton)

  def CloseProgramFromPanel(self, event):
    parente=self.GetParent()
    parente.Destroy()

if __name__ == '__main__':
  app=wxappsubclass()
  app.MainLoop()

Now, If I want to bind the same event handler ("CloseProgramFromFrame" in this example) from class "panel1()" how to do?
i.e.: I want to delete "CloseProgramFromPanel()" method in the "panel1" then bind "Exit" button - i.e. EVT_BUTTON in the "panel1()" - to the "CloseProgramFromFrame()" method in the "wxframesubclass()", how to do? I'm a bit confused...

A: One of the possible ways is:
#!/usr/bin/python
# _*_ coding: utf-8 _*_
import wx

class wxappsubclass(wx.App):
  def OnInit(self):
    frame=wxframesubclass(None, -1, 'MyName')
    frame.Show(True)
    return True

class wxframesubclass(wx.Frame):
  def __init__(self, parent, id, title):
    wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, size=(320, 240))
    self.panel=panel1(self)
    menubar=wx.MenuBar()
    menufile=wx.Menu()
    ExitItem=menufile.Append(wx.NewId(), '&Exit\tCtrl+Q', "Exit")
    menubar.Append(menufile, '&File')
    self.SetMenuBar(menubar)

    ## BINDING ##
    self.Bind(wx.EVT_MENU, self.CloseProgramFromFrame, ExitItem)
    self.Bind(wx.EVT_BUTTON, self.CloseProgramFromFrame, self.panel.ExitButton)

  def CloseProgramFromFrame(self, event):
    self.Close(True)

class panel1(wx.Panel):
  def __init__(self, parent):
    wx.Panel.__init__(self, parent, -1)
    ID_EXIT_BUTTON=wx.NewId()
    self.ExitButton=wx.Button(self, wx.NewId(), label="Exit")

if __name__ == '__main__':
  app=wxappsubclass()
  app.MainLoop()


text:
Q: How to configure LVM to use the entire partition Due to the space crunch, have increased the HDD size from 500 GB to 650 GB on /dev/sdb, but unsure on how to resize the lvm to make use of the available 150GB.
sdb         8:16   0   650G  0 disk
└─ceph--ef9893e6--7191--434e--a531--8deaeb51ad92-osd--data--5abbfff8--920a--419d--bb87--91ba4a1bf3a1
          253:0    0   500G  0 lvm

Tried lvextend but failed.
lvextend -L+12G /dev/ceph-ef9893e6-7191-434e-a531-8deaeb51ad92/osd-data-5abbfff8-920a-419d-bb87-91ba4a1bf3a1
  Insufficient free space: 3072 extents needed, but only 0 available

lvextend -l +100%FREE /dev/ceph-ef9893e6-7191-434e-a531-8deaeb51ad92/osd-data-5abbfff8-920a-419d-bb87-91ba4a1bf3a1
  New size (127999 extents) matches existing size (127999 extents).

lvdisplay
  --- Logical volume ---
  LV Path                /dev/ceph-ef9893e6-7191-434e-a531-8deaeb51ad92/osd-data-5abbfff8-920a-419d-bb87-91ba4a1bf3a1
  LV Name                osd-data-5abbfff8-920a-419d-bb87-91ba4a1bf3a1
  VG Name                ceph-ef9893e6-7191-434e-a531-8deaeb51ad92
  LV UUID                kzJ5pI-g1UI-CUdP-kZE7-wRqT-fwTd-cZeoAX
  LV Write Access        read/write
  LV Creation host, time
  LV Status              available
  # open                 0
  LV Size                <500.00 GiB
  Current LE             127999
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           253:0

 pvdisplay
  --- Physical volume ---
  PV Name               /dev/sdb
  VG Name               ceph-ef9893e6-7191-434e-a531-8deaeb51ad92
  PV Size               500.00 GiB / not usable 4.00 MiB
  Allocatable           yes (but full)
  PE Size               4.00 MiB
  Total PE              127999
  Free PE               0
  Allocated PE          127999
  PV UUID               FzjGfa-evuO-cJxF-FcIo-u9Mb-wGuG-Pl4qFo

lvs
  LV                                            VG                                        Attr       LSize    Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  osd-data-5abbfff8-920a-419d-bb87-91ba4a1bf3a1 ceph-ef9893e6-7191-434e-a531-8deaeb51ad92 -wi-a----- <500.00g

OS Ubuntu 20.04 LTS


text:
Q: How to use a reference in a trigger? I have a problem with triggers. First of all, I have this:
The types:
CREATE OR REPLACE TYPE Tipo_Lineaventa AS OBJECT
(id NUMBER(5),
 cantidad NUMBER(5),
 precio_venta NUMBER(5,2),
 refProducto REF Tipo_Producto);
/

CREATE OR REPLACE TYPE Tipo_Producto AS OBJECT
(codigo NUMBER(5),
 modelo VARCHAR(15),
 precio NUMBER(5,2),
 stock_disp NUMBER(3),
 esSuministrado Tipo_esSuministrado
) NOT FINAL;
/

And the tables:
CREATE TABLE Tabla_Lineaventa OF Tipo_Lineaventa
( CONSTRAINT PK_Tabla_Lineaventa PRIMARY KEY (id),
refProducto NOT NULL);

CREATE TABLE Tabla_Producto OF Tipo_Producto
( CONSTRAINT PK_Tabla_Producto PRIMARY KEY (codigo),
  CONSTRAINT AK_Tabla_Producto UNIQUE(modelo))
NESTED TABLE esSuministrado STORE AS NT_esSuministrado;

And now, I have this trigger:
CREATE OR REPLACE TRIGGER checkQuantity
BEFORE INSERT ON Tabla_Lineaventa
FOR EACH ROW
DECLARE
    stock Tabla_Producto.stock_disp%TYPE;
    cod Tabla_Producto.codigo%TYPE;
    aux Tipo_Producto;

BEGIN
    SELECT DEREF(:OLD.refProducto).codigo INTO cod FROM dual;

    SELECT stock_disp INTO stock FROM Tabla_Producto P WHERE P.codigo = cod;

    IF stock > :OLD.cantidad THEN
        DBMS_OUTPUT.PUT_LINE('OK')
    ELSE
        DBMS_OUTPUT.PUT_LINE('ERROR');
    END IF;
END checkQuantity;
/

With the sentence SELECT DEREF(:OLD.refProducto).codigo INTO cod FROM dual; I have problem, because not return my product codigo attribute that I'm referencing in refProducto.
How can I solve it? I need to know if I have enought stock for do a new 'Lineaventa'.
Thanks a lot!

A: I'm not sure this is the issue, but at the very least, for a BEFORE INSERT trigger, OLD: is null. You should use the NEW: pseudorecord to access the post-insert value.
    SELECT DEREF(:OLD.refProducto).codigo INTO cod FROM dual;
--               ^^^^
--               here

...

    IF stock > :OLD.cantidad THEN
--             ^^^^
--           and here

See http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/triggers.htm#sthref784


text:
Q: Valor parameter in javascript i have this
if (valparam[3] == 0) {
    if (valparam[4] == 1) {
        document.getElementById('cod_htmlbg').value = "";
    } else if (valparam[4] == 0) {
        document.getElementById('cod_htmlbg').value = "";
    }
}
if (valparam[3] == 1) {
    if (valparam[4] == 1) {
        document.getElementById('cod_htmlbg').value = "";
    } else if (valparam[4] == 0) {
        document.getElementById('cod_htmlbg').value = "";
    }
} else
    document.getElementById ('cod_htmlbg').value = "";

but when i run it and in my page i change valors for valparam[3] and valparam[4] it works only for
valparam[3]==1 && valparam[4]==1
valparam[3]==1 && valparam[4]==0

or for valparam[4]==1 i dont know if it works , i think it prints that last else ....
can someone give me a help ?


text:
Q: How to make make my mysql localhost online I would to ask, How to make my mysql localhost online and can be access anywhere via internet while my locally connected Pc's are still connected with out net? For Example I have a Server and Client Setup at my Office, using Lan the client can access to the my mysql server which can be found at one of the PC that serves as server but how can i make the server online in the net or web? because i need to access it anywhere with internet without affecting the LAN.
i don't know what to do, i've tried online hosting but i cannot proceed.


text:
Q: Node.js + Express.js (Connect) - Accessing Session from 'upgrade' event I'm trying to access the session object from an 'upgrade' event fired by a Node.js server using the Express.js framework. I have set up Session support correctly and can access it from the standard .get .post .put and .delete methods eg.
app.get('/', function(req, res) {
    req.session.test = 'Hello world'; // Works fine
    res.render('index');
});

But if I hook up an on 'upgrade' event on the server like so:
app.on('upgrade', function(req, socket) {
    var message = req.session.test; // Doesn't work
});

I can't access the session object. As far as I'm aware, the Connect Session middleware only hooks up the session for the get/post/put/delete methods, but not for custom events such as 'upgrade'.
FYI, an 'upgrade' event is issued from a client during a WebSocket handshake, I'm trying to access the session from the initial WebSocket handshake. The session cookie is definitely there in the HTTP headers during the handshake eg:
app.on('upgrade', function(req, socket) {
    var cookieHeader = req.headers['cookie'];
    console.log(cookieHeader);
});

...will output the Connect session cookie. Is there perhaps a way to build up the session object manually using the raw session cookie token?

Update: Been speaking to to some people on the node.js IRC chatroom, apparently this is either very difficalt or impossible. The Connect middleware isn't exposed to custom/unusual events such as 'upgrade'. They said to raise an issue in Github, so here it is:
https://github.com/senchalabs/connect/issues/342

A: Since you don't have access to the response object, you should be able to look up the session object by getting the session store and calling get(session_id, callback) with the session_id you get from the cookie.  You also may be able to actually call the normal session middleware function if the req object you have is linked to the response via req.res, which express.js will do for you, but if this is a raw node.js event, then that connection might not have been made at this point.  When you create the middleware, you'll have to create the session Store instance manually and keep a reference to it, then pass it to the session middleware factory function in the options object.

A: If you are using express-session, this should help :
import session from 'express-session'
import express from 'express'

import http from 'http'
import { WebSocketServer } from 'ws'

// Declare an Express app
const app = express()

// Declare an HTTP server for the app
const server = http.createServer(app)

// Initialize *express-session* and use it as a middleware
const sessionHandler = session({
  saveUninitialized: false,
  secret: 'my little secret',
  resave: false
})
app.use(sessionHandler)

// Define a builder for message handler with WebSocket and Session as context
const onMessage = (ws, session) => (message) => {
    // create a handler for message given the ws and session
}

// Create a *WebSocketServer* without an attached HTTP server
const wsServer = new WebSocketServer({ noServer: true })

// define what to do on a 'connection' event
wsServer.on('connection', (ws, session) => {
  ws.on('message', onMessage(ws, session))
})

// 'upgrade' event comes when the browser ask for a WebSocket
server.on('upgrade', (req, socket, head) => {
  // we call the *sessionHandler* to retrieve/create the session
  sessionHandler(req, {}, () => {
    // ask the *WebSocketServer* to manage the upgrade
    wsServer.handleUpgrade(req, socket, head, (ws) => {
      console.log(req.session)
      // emit a 'connection' event (handler above) with the create WebSocket and current session
      wsServer.emit('connection', ws, req.session)
    })
  })
})


text:
Q: What is ColorEqualSigns and how does one use it? I'm setting up the SyntaxInformation for a package I'm writing and I'm struggling to understand what the "ColorEqualSigns" property is supposed to do, how one is meant to use it, and whether it works at all.
From what I can tell, it is meant to colour equal signs (i.e. =) red, in positions where it is likely that the intended operator is Equal, i.e. ==, instead of Set. This includes positions that normally take equations (like in Solve) or logical tests (like in Which). Is this a correct understanding of the expected behaviour?
However, I'm having trouble getting the Front End to reproduce this behaviour, both for my own functions and for the in-built ones.
For my own functions, code like
SyntaxInformation[f] = {"ColorEqualSigns" -> {1, 2}};
f[a = 1, b = 2, c = 3]

only marks the first one as an error:

To do the system-defined functions, one can get a comprehensive list by running
list = Select[
  Table[
   {symbol, SyntaxInformation[ToExpression[symbol]]}
   , {symbol, Names["System`*"]}]
  , (("ColorEqualSigns" /. #[[2]]) =!= "ColorEqualSigns") &]

the output of which is nicely formatted by TableForm[{#1, {"ColorEqualSigns"} /. #2} & @@@ list].
And             All
DSolve          1   1
For             2   2
If              1   1
Implies         All
Nand            All
NDSolve         1   1
NDSolveValue    1   1
Nor             All
Not             All
NRoots          1   1
NSolve          1   1
Or              All
Reduce          1   1
Solve           1   1
SolveAlways     1   1
Which           Odd
While           1   1
Xor             All

From these, only If and While seem to work as intended. As a test, see the syntax colouring on the following:
And[a = 1, b = 2]
DSolve[y'[x] = y[x], y, x]
For[i = 0, i = 5, i++, Print[i]]
If[i = j, a, b]
Implies[a = b, c = d]
Nand[a = 1, b = 2]
NDSolve[y'[x] = y[x], y, x]
DSolveValue[{y'[x] = y[x] Cos[x + y[x]], y[0] = 1}, y, {x, 0, 30}]
Nor[a = 1, b = 2]
Not[a = 1]
NRoots[1 + 2 x + 3 x^2 + 4 x^3 = 0, x]
NSolve[x^5 - 2 x + 3 = 0, x]
Or[a = 1, b = 2]
Reduce[x^2 - y^3 = 1, {x, y}]
Solve[x^2 + a x + 1 = 0, x]
Solve[x^2 + a x + 1 = 0, x]
Which[a = 1, b = 2, c = 3, d = 4, e = 5, f = 6]
While[n = 4, n++]
Xor[a = 1, b = 2]

which render on my machine (MM 11.0.0, 10.3.0, 10.1.0 and 9.0.1 over Ubuntu) as

Note that e.g. the second equals sign in And[a = 1, b = 2] is not marked as erroneous, which is inconsistent with the rule "ColorEqualSigns" -> All in SyntaxInformation[All]. This is present at least since early 2013, as pointed out in this post.
Is this the intended behaviour?

A: So I delved into this as part of a new effort to review things like SyntaxInformation, function templates, and so forth.  Too early to say what will come of this, but feel free to send requests.
As for the specific issue of "ColorEqualSigns".  First, how it's supposed to work.  The allowed values (currently) are
All
None
Odd  (* see below *)
Even (* see below *)
pos_Integer
{minpos_Integer,maxpos_Integer}

All of these (are supposed to) have the more or less obvious meanings.  But I've identified mutliple issues I have reported internally.

*

*The FE is expecting the values System`Odd and System`Even, but of course there are no such symbols.  Probably just an oversight when first created--these should have been OddQ and EvenQ. Nobody noticed since only one function uses these values, namely Which.  I would recommend just unprotecting Which and putting System`Odd as a workaround, except for:

*For some reason, the coloring is only active in the first argument.  So if your spec includes the first position, you'll see it there, but not elsewhere.  If the spec doesn't include 1, you won't see it anywhere. This is obviously a bug.  It's a bit embarassing it wasn't noticed internally earlier.

*The coloring requires that the LHS be a single token.  Compare the appearance of Solve[x^2 + a x + 1 = 0, x] and Solve[0 = x^2 + a x + 1, x].  This is arguably not a bug if you think of this feature descending from things like If[test,...].  If[x=0,...] is valid syntax which will quietly do the wrong thing in all cases.  If[x^2+2x+1=0,...] will give you a message.  Still, I feel this is not keeping with the spirit of this option and I have reported this as a bug.

*It doesn't enter lists and check equal signs inside.  It's certainly a limitation, but it's not obviously wrong.  And certainly, how many levels down does it check?  Is it worth the development cost and/or performance cost?  I'm not saying it wouldn't be nice to do this (I would like it), but this definitely more in the "feature request" than "bug fix" category.

So now it is reported and might actually be fixed.  I can't say when, will the first is obviously easy, I don't know enough about the code to even guess at the difficulty of the others.  I'll try to keep this updated as I get news.


text:
Q: Can I run Linux on N130 Network Terminal Thin Client? I've found this small device, named N130 Network Terminal Thin Client on several webshops.
The datasheet says that it is running "Embedded Eglobal operating firmware". I think, there is a good chance on that it is a minimal Linux distribution. So if it is, can I use it as a weak Linux server? Has anyone experience with it?
(P.S. I know what a thin client is, and I also know that a "firmware Linux" may have several restrictions.)
EDIT: http://www.eglobaltech.cn/ViewDetails67.aspx
EDIT2: Confirmed answer should describe that how can I use it as a weak Linux server, or tell why I can't do it. Also, I would be happy with a good datasheet, too.

A: Since it claims to run Windows XP it is likely to be x86-based. Running linux on it shouldn't be much more difficult than running it on a regular PC. Note however, that thin clients are usually booted from network (with PXE). Embedded Eglobal operating firmware doesn't say anything about Linux being available 0 more likely it will be just some sort of PXE environment.

can I use it as a weak Linux server?

No or at least not directly - it does have any kind of local storage (USB, (S)ATA) or anything similar), hence there is no way to offer any services relying on any data, unless those would come over the network as well, in which case it doesn't seem to make much sense to have a thin client reserved for it. If you look for something with at least USB, your chances are much higher. You would probably still need to boot it from network though )unless it would be able to boot from e.g. USB, which however goes a bit against the basic idea of a thin client).


text:
Q: How do I delete tables in the QuestDB console? I imported a lot of CSV files into my database for testing and I'd like to clear out a few of the tables I don't need. How can I get rid of multiple tables at once? Is there an easy way like selecting many tables in this view:

A: Easiest way I found was to use the REST API /exec endpoint: https://questdb.io/docs/develop/insert-data/#exec-endpoint
I generated a bash script using the output of the "select name from tables()" Meta function.
Example lines:
curl -G --data-urlencode "query=DROP TABLE 'delete_me.csv'" http://localhost:9000/exec
curl -G --data-urlencode "query=DROP TABLE 'delete_me_also.csv'" http://localhost:9000/exec

If you use the web console (or even /exec to query) select name from tables() can be filtered on a regex just like a regular query.
Converting to a bash script is manual though. I recommend just dumping the table names to csv, then using bash to put in the appropriate quotes, etc.
I did it with awk:
awk -F, '{ print "curl -G --data-urlencode \"query="DROP TABLE \'$0\'"\" http://localhost:9000/exec"}' ~/Downloads/quest_db_drop_tables.sql > ~/Downloads/quest_db_drop_tables.sh


text:
Q: How to change a name of one field in large Json using Jolt I have a big Json document:
{ "field1": "value1",
  "field2": "value2",
  "field3": "value3",
...
 "field1000": "value1000"
}

I want to change the name of one field (field3) to third_field
How to do it without writing specification like that:
[
  {
    "operation": "shift",
    "spec": {
       "field1": "field1",
       "field2": "field2",
       "field3": "third_field",
       ...
       "field1000": "field1000"
    }
  }
]

A: This should work and essentially does an if then else
[
  {
    "operation": "shift",
    "spec": {
      //if
      "field3": {
        //$ - current value
        "$": "third_field"
      },
      //else
      "*": {
        //$ - current value
        //& - current key
        "$": "&"
      }
    }
  }
]


text:
Q: read matrix issue C language This code should read and display a matrix. But it doesnt work, I cant find the problem.  Why it doesnt work?
#include <stdio.h>

#define MAX 100

void read_matrix(int a[MAX][MAX], int n)
{
    int i, j;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &a[i][j]);
}

int main(void)
{
    int a[MAX][MAX], n = 1, i, j;

    read_matrix(a, n);

    for(i = 0; i < n; i++) {
        for (j = 0; j < n; j++)
            printf("%d ", a[i][j]);
        printf("\n");
    }

    return 0;
}

For input:
2
1 2
3 4

The output is:
1

A: Because n is passed by value, not by reference. Use:
void read_matrix(int a[MAX][MAX], int *n) {
    int i, j;

    scanf("%d", n);
    for (i = 0; i < *n; i++)
        for (j = 0; j < *n; j++)
            scanf("%d", &a[i][j]);
}

and
read_matrix(a, &n);

Now n is passed by reference and it should work as expected.

A: First of all, let's deal with a fact "In C there is nothing called pass by reference".
But yes we emulate that with what is available in C, that is pass by value.
So in the first case there are things that happened

*

*You call the function like this read_matrix(a, n);

*A copy of the variable is there in read_matrix.

*We make changes to the copy.

*Function ends and story ends there. That local variable's scope ends. It is not alive now.

*You come back to main(). Do you expect to see any change in n? Nope. Because all change was there in read_matrix.
Now to change that we write it this way.
void read_matrix(int a[MAX][MAX], int* nn)
{
    if( scanf("%d", nn) != 1){
        fprintf(stderr,"Error in input");
        exit(1);
    }
    for (size_t i = 0; i < *nn; i++)
        for (size_t j = 0; j < *nn; j++)
            if( scanf("%d", &a[i][j]) != 1){
                fprintf(stderr,"Error in input");
                exit(1);
            }
}

Now here also couple of things happened

*

*You pass the &n or the address of n.

*Then nn is a local variable (local to read_matrix) containing the address of n.

*scanf() wants the address of what it will write something.

*We pass the address of n or content of nn.

*Then scanf() writes where? In the memory of n. So n in main() changes.

*Now we want to get while looping the value of n or the value in address of n or the value in the address contained by nn.

*So we use * on nn. Or *nn.

*Now you back to main() and the local variable nn is not there and it's lifetime ended when the function read_matrix ended.

*You see the changed value in n.

Do you see any difference in two method?
In one we pass the value. In another we pass as value the address of n.
Both are pass by value. But in second method due to the side effect of accessing memory we see he change in main(). Story ends.


text:
Q: equality of filled rectangles in 2 images I am using AForge.Net to develop a OMR system that marks sheets by finding the equality of rectangles filled using a specific colour. using the blobcounter algorithm, it works fine if Microsoft word is used to fill the rectangles in the sheets. the location of objects in both images will be equal but if 2 different human beings (which is the ideal way it should work) fill the rectangles, the location will be slightly different even if it is the same rectangle filled in both sheets, so it will return a non equal value. How do i go about fixing this if possible?
the codes looks like this:
...

// Loop
foreach (Rectangle1 in rects1)
{
foreach (Rectangle2 in rects2)
{
...
// Equality
if (rectangle1 == rectangle2)
{
Console.Writeline("True");

...


text:
Q: command --help vs man command What is the difference between invoking the help using a --help key compared to invoking a "man command"?
When should I choose one over another.

A: Help is a built-in "usage" of the command, and not all commands implement it, or at least not the same way, however, man is a command by itself which is a pager program that reads manual. For more info issue the man man for the manual pages for the man command.
You should use man every time you need additional information about a command, as well with the info command, that reads info documents.


text:
Q: Flutter Splash screen is not changing pages //Here is my Splash Screen
class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    init();
  }

  Future<void> init() async {
    await doSomeAsyncStuff();
  }

  doSomeAsyncStuff() {
    User user = Provider.of<User>(context);
    if (user == null) {
      Navigator.pop(context);
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => LoginScreen(),
        ),
      );
    } else {
      Navigator.pop(context);

      Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => BusinessList(),
          ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Image.asset(
          'assets/ledgerslogofinal.png',
          width: 250,
          height: 250,
        ),
      ),
    );
  }

}
If the user is not null the splash screen has redirect to BusinessList() otherwise it has to redirect to LoginScreen()
Here is the error msg in my console
E/flutter (20189): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: dependOnInheritedWidgetOfExactType<_InheritedProviderScope>() or dependOnInheritedElement() was called before _SplashScreenState.initState() completed.
E/flutter (20189): When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor or an initState() method, then the rebuilt dependent widget will not reflect the changes in the inherited widget.
E/flutter (20189): Typically references to inherited widgets should occur in widget build() methods. Alternatively, initialization based on inherited widgets can be placed in the didChangeDependencies method, which is called after initState and whenever the dependencies change thereafter.

A: I think instead of poping and pushing routes inside the initState you should rather toggle wich screen your returning :
class SplashScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    User user = Provider.of<User>(context);
    return user == null ? LoginScreen() : BusinessList();
  }
}

So if your user is not logged in (i.e. user == null) you return your LoginScreen, else you return your main screen.


text:
Q: Visual Studio shortcut for "quick fix" Does Visual Studio 2010 have a shortcut for quick fix?
I'm tired of grabbing the mouse, hovering over this red line, waiting for the little clipboard icon to appear, clicking on the first menu item. It would be so much fast to just open that dialog with some keys and confirming the first (i.e. selected) item.

A: The feature is called the "Smart Tag".

*

*Default Keyboard Shortcut Schemes (ReSharper documentation)

*Stack Overflow question How does one set Visual Studio 2010 keyboard shortcuts comfortably, especially when using ReSharper?

*Stack Overflow question Visual Studio keyboard shortcut to automatically add the needed 'using' statement
They can usually be invoked via the keyboard using either:

*

*Ctrl+. (on a standard QWERTY keyboard)

*Alt+Shift+F10 (if you've not got Function Lock enabled)

A: Alt + Shift + F10 does the trick.
Via @Rohit from Visual Studio keyboard shortcut to automatically add the needed using statement

A: If you want to edit the shortcut of quick fix you can do the following:
Open Tools->Options->Keyboard and in the Show commands containing field enter EditorContextMenus.CodeWindow.QuickActionsForPosition and replace the old shortcut with the new one.

A: If your cursor is on the item that is underlined, you can use Ctrl + . to pop up the intellisence/suggestion context menu.


text:
Q: Why does Jenkins think I'm a guest when I'm an administrator? Just this morning, I was able to log into my Cloudbees Jenkins Dashboard and configure builds, start builds, etc. But now I log in and it considers me a "guest user" and I can't kick off a build. What's up?

A: The problem is that your Jenkins session has expired, but the toolbar is not showing the "Login" link. As a workaround, you can just navigate to /manage or /configure, and you will be prompted to login. We are working on a fix for this.


text:
Q: Get Azure Batch job and task ID from python When running a custom python script using Azure Batch I am interested in getting access to, and logging, the JobID and TaskID of the tasks I am running on the compute node. Mainly for later traceability and debugging purposes. My desire is to get access to these parameters from within the python script that is being executed on the compute node. I have trawled through the Microsoft documentation, but have been unable to figure out how to access this information.
I had assumed that it was similar to the way I'm accessing the custom job parameters through the activity.json, but that does not appear to be the case.
How do I get the job ID and task ID of the Azure Batch task from within the python script that is being executed by the task?

A: Azure Batch populates various runtime environment variables for use while tasks are executed on compute nodes. You can retrieve the job and task id via the environment variables AZ_BATCH_JOB_ID and AZ_BATCH_TASK_ID, respectively. See the complete list of environment variables.


text:
Q: Show that every prime power if deficient. If $n$ is a positive integer, we say that n is deficient if $\sigma(n)<2n$.
The answer is given by:

Can someone please explain the two yellow marks? And also the connexion between the first and second mark?

A: First one: Start with $2\leq p$. Multiply both sides with $p^k$ to get $2p^k\leq p^{k+1}$. Finally, note that subtracting $1$ from a number makes it strictly smaller, so we get
$$
 2p^k-1<2p^k\leq p^{k+1}
$$
For the second one, take what we had in the first one, and add $p^{k+1} - 2p^k$ to both sides:
$$
2p^k - 1 + p^{k+1} - 2p^k < p^{k+1} + p^{k+1} - 2p^k
$$
Clean up the expressions on both sides, and you get exactly $p^{k+1} - 1<2(p^{k+1} - p^k)$.


text:
Q: Lightweight MySQL Qt GUI frontend for Linux I'm looking for a lightweight MySQL Qt4/PyQt4 GUI frontend for Linux.
Ideally it will be very similar to sqliteman.
I did some google searches but it only finds Java monsters and herds of shareware MySQL GUIs for Windows.

A: Java does not equal huge. Why don't you actually try a few before shooting down the whole language?

A: How about sqlyog Community edition ?

A: Emma
or MySQL Query Browser


text:
Q: How convert symbolic equation to solve in ode45? I'm trying to solve a differential equation like below:
%% Parameters Initialization
C    = 0.01;
gfi  = 0.2308;
gso  = 0.769;
Efi  = 17.333;
Eso  = 0;
km   = 0.842;
v12m = 5.85;
kn   = 4.4;
v12n = 9.667;
tauni = 3;

%% defining Functions
syms v n;
n_v_e = 1 / (1+exp((v12n-v)/kn));
m_v = 1 / (1+exp((v12m-v)/km));
gfi_v = gfi * m_v;
Dn = tauno*(n_v_e-n);
Ifi = gfi_v*(v-Efi);
Iso = gso*n*(v-Eso);
Dv = -1/C * (Ifi + Iso);

%% Solving ODE
v0 = -10;
n0 = 0.1;
te = 2000;

Dv = subs(Dv,'v','y(1)');
Dv = subs(Dv,'n','y(2)');
Dn = subs(Dn,'v','y(1)');
Dn = subs(Dn,'n','y(2)');

[t,V] = ode45(@(t,y)[Dv;Dn],[0 te],[v0;n0]);

the problem occurs right here at ode45 saying "Inputs must be floats, namely single or double."
I know the problem is due to symbols (n and v) but I don't know how to get rid of them!
I don't also want to write a seperate function and use it instead of [Dv;Dn].
Thank you for your help


text:
Q: Social Engine get user id from profile page I'm trying to add some features to the users profile page, and for that I would need that users ID - just to clarify, it's not viewers ID I'm chasing, it's the ID of the user whose profile I'm viewing.
So, I used $subject = Engine_Api::_()->core()->getSubject('user'); and it returns a big object full of all kinds of data, but don't know how to extract user ID?
Anyone have a clue? (SocialEngine 4 is the platform I'm using)

A: this will get you the userid of the profile..
$profileownerid = Engine_Api::_()->core()->getSubject('user')->getIdentity();

A: I've figured it out: $subject_id = $subject->getIdentity(); and voila!


text:
Q: Publishing PostGis table using GeoServer REST returns error when geometry column is NOT named "geom" I tried publishing an existing PostGis table with geometry column named "wkb_geometry" to Geoserver using its REST API. I used the following command:
curl -v -u admin:geoserver -X POST -H "Content-type: text/xml" -d "<featureType><name>boundary</name></featureType>" http://mygeoserver:8080/geoserver/rest/workspaces/myworkspace/datastores/mypostgis/featuretypes

however, the server returned:
> <featureType><name>adminbnd_prov_xxx</name></featureType>HTTP/1.1 500 Internal
 Server Error
< Content-Type: text/plain
< Transfer-Encoding: chunked
< Server: Jetty(6.1.8)
:java.io.IOException: Error occured calculating bounds* Connection #0 to host
mygeoserver left intact
* Closing connection #0

One thing I found out is that if I renamed my geometry column from "wkb_geometry" to "geom" and execute again the command, the PostGis table is published successfully.
Using Geoserver's web interface, this is a not an issue. You can publish PostGis tables regardless of its geometry column name.
Is this the default behaviour for the REST api? Is there any workaround on this? What does "error occured calculating bounds" has to do with it?
Thanks a lot!


text:
Q: how to display uploaded file from writable/uploads in codeigniter 4 In Codeigniter4 how to show the path of uploaded file from the writable/uploads folder?
The file may be an image, doc, pdf or CSV.
I upload the file using the below code and store it in DB.
$file->move(WRITEPATH . 'uploads', $fileName);
all uploaded records are listed on a page and have to open the uploaded CSV/excel in a new tab from the listing page.
but I did not get the path from the writable/uploads folder to open in a new tab.
<?=WRITEPATH.'uploads/'.$allList->documentCsv?>
when I copy the link and open it on a tab it downloaded.
Please explain how to show the path.
Thanks

A: Based on your clarification.
I get this summary.
You want to show file binary value but instead of download you wanna show it in browser.
I have this code for you
public function showFile()
{
    helper("filesystem");
    $path = WRITEPATH . 'uploads/';
    $filename = 'logo-at.png';

    $fullpath = $path . $filename;
    $file = new \CodeIgniter\Files\File($fullpath, true);
    $binary = readfile($fullpath);
    return $this->response
            ->setHeader('Content-Type', $file->getMimeType())
            ->setHeader('Content-disposition', 'inline; filename="' . $file->getBasename() . '"')
            ->setStatusCode(200)
            ->setBody($binary);
}

The supported extension will show the file value in browser. If not, it will downloaded.
Reference in documentation:

*

*https://codeigniter4.github.io/CodeIgniter4/libraries/files.html#getting-a-file-instance

*https://codeigniter4.github.io/CodeIgniter4/outgoing/response.html#http-responses


text:
Q: What does modprobe.blacklist=nouveau do? I just blacklisted nouveau, but I see that it is still being used. Would someone please help me understand this?
My new installation of 18.10 would freeze when logging in. To resolve this, I blacklisted nouveau in grub by updating /etc/default/grub with
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash modprobe.blacklist=nouveau"

(The solution was from NMI watchdog: BUG: soft lockup - CPU#2 stuck for 23s!, which was the issue had I experienced.)
I am glad that I am now able to successfully login, but I see that Nouveau is still being used, and this is confusing.
I thought I just blacklisted it, so why do I see it as active in Software and Updates?
What does the line modprobe.blacklist=nouveau exactly do? (Perhaps I misunderstand it).
Are there any disadvantages of adding modprobe.blacklist=nouveau to grub?

A: Possibly, there is a conflict between the open-source driver with that of the graphic card from Nvidia. I will write down the solution that worked for me, on a Lenovo ThinkPad P53 when installing Ubuntu 20.04 LTS, I faced some issues.
Follow the steps written below:

*

*Boot to Ubuntu, but before you login in to Ubuntu, press Cntrl+Alt+F2

*run the following command:
     sudo nano /etc/modprobe.d/blacklist-nouveau.conf

*add the 2 following lines, save & exit
     blacklist nouveau
     options nouveau modeset=0

*run the following command
     sudo update-initramfs -u


text:
Q: Cast Collection to Collection Got another simple question here that is eluding me.
I have 2 classes:
namespace Assets
{
   public class BaseAsset
   {
       // Code here
   }
}

And
namespace Assets
{
   public class Asset : BaseAsset
   {
       // Code here
   }
}

I have a function that returns a collection of Asset from the database and I want another function to execute that function and return a collection of BaseAsset.
I have tried this:
    public static Collection<BaseAsset> GetCategoryAssets(int CategoryId, string UserId, string CompanyId)
    {
        return (Collection<BaseAsset>)AssetData.getAssets(CategoryId, UserId, CompanyId);
    }

but as you can guess, it doesn't work.
If I was working with lists, I could do:
    public static List<BaseAsset> GetCategoryAssets(int CategoryId, string UserId, string CompanyId)
    {
        return AssetData.getAssets(CategoryId, UserId, CompanyId).Cast<BaseAsset>().ToList();
    }

But I would prefer to use a collection, can anyone come up with an elegant solution?
Cheers,
r3plica

A: If you want the ease of .ToList, just write your own .ToCollection extension method. The implementation should be straightforward - take an IEnumerable<T>, loop through it and add everything into a collection with Add.

A: The problem is that Collection<T> and ICollection<T> are invariant (that is, Collection<BaseAsset> is neither a subtype nor a supertype of Collection<Asset>).
The problem will be very easily solved by returning either IEnumerable<BaseAsset> or IReadOnlyList<BaseAsset> instead of Collection<BaseAsset>.
That is, you can write:
public static IEnumerable<BaseAsset> GetCategoryAssets(int CategoryId, string UserId, string CompanyId)
{
    return AssetData.getAssets(CategoryId, UserId, CompanyId);
}

The cast becomes unnecessary.
In general, you should prefer interface types (such as IList<T>, IReadOnlyList<T>, ICollection<T> or IEnumerable<T>) over concrete types (Collection<T> or List<T>) when specifying return values and function parameters.

A: This is a very frequently asked question. The name of the feature that you want is generic covariance; that is, the feature that says "if a giraffe is a kind of animal then a list of giraffes is a kind of list of animals."
The problem is that a list of giraffes is not a kind of list of animals. You can put a tiger into a list of animals, but you can't put a tiger into a list of giraffes, and therefore a list of giraffes cannot be used in any context where a list of animals is expected.
The reason you should use IEnumerable<T> instead of Collection<T> is because as of C# 4, IEnumerable<T> is covariant in T, provided that the type arguments provided are both reference types. That is, a sequence of strings can be used as a sequence of objects, because both are reference types. But a sequence of ints cannot be used as a sequence of objects, because one is a value type.
The reason this is safe is because there is no way to insert a tiger into an IEnumerable<Giraffe>.

A: Instead of trying to cast to the base class, why not just extract an interface and use that.

A: Since the Collection<T> class has a constructor that takes an IList<T> as an argument, you can always do:
Collection<BaseAsset> = new Collection<BaseAsset>(
                                           assetList.Cast<BaseAsset>().ToList());

Of course, if you need to reuse this behaviour, you could make a CastToCollection extension:
public static Collection<TResult> CastToCollection<TResult>(this IEnumerable source)
{
   return new Collection<TResult>(source.Cast<TResult>().ToList());
}


text:
Q: Vulnerability / exploit MSDT (CVE-2022-30190) | Is renaming the registry key "ms-msdt" enough for the workaround? Microsoft publishes a workaround for the msdt exploit (Guidance for CVE-2022-30190 Microsoft Support Diagnostic Tool Vulnerability)
The suggested way is to delete the key Computer\HKEY_CLASSES_ROOT\ms-msdt after backing it up:

To back up the registry key, execute the command "reg export
HKEY_CLASSES_ROOT\ms-msdt filename" Execute the command "reg delete
HKEY_CLASSES_ROOT\ms-msdt /f".

I don't know how the registration of handlers like this work.
Question:
Wouldn't it be enough to rename the key like: Computer\HKEY_CLASSES_ROOT\ms-msdt__RenameBecause_cve-2022-30190 or would the handler still work regardless of the name?
Why I'm asking this: I would like to prevent registry backups on every machine, which may get lost.

Edit: I agree that its the best way to follow the microsoft recommendation. But with hundreds of pcs this way is difficult to implement reliably (not to mention that the registry backups have to be restored at some point)

A: Renaming is enough, as did the author of the article
Mysterious "Follina" zero-day hole in Office – here's what to do!
However, the author finished by deleting the key, as this mitigation
felt unfinished to him.
I would also suggest to delete the key, for a complete job.
You could export and keep the key before deleting it, as a better
method for backup.


text:
Q: How can I check if an instance of a Access 2010 form is still open? Preface
I have a need to create multiple copies of a search form (in Access 2010) that returns a value to the calling (which is also the form that created the instance of the form).
As mentioned these forms could and will have multiple copies running at the same time for example a user could want to add a company to something so they:

*

*Click "select company" and open an instance of the company search screen

*Then open the company editor (leaving the original company search/selection screen open) as they notice the company has a parent company that hasn't been added yet.

*They then click the "Select Parent Company" button that opens ANOTHER instance of the search and select screen

*They find the parent company

*Select it which closes the second search screen and the parent company is added to the first company.

*The user then selects the modified company using the original search screen which again closes the original search screen and returns the selected company to what ever form they originally initialised the first search...

This all allows the users to update and correct data as and when they find error which reduces the likelihood of them forgetting and makes it much quicker!
MOST of this is fine now but I have had a lot of problems with instances of a form not being able to open as a "acDialog" thus stopping the calling code running until the search was done (see this question for more info) and the solution I have gone with is to simulate the pausing of the calling code by using a endless loop and checking if the search screen instant is still visible. Then when the user selects something on the search screen instant it puts the value in a hidden field in the search screen and hides it's self (not closed). The calling function then sees it's hidden grabs the value from the hidden field and unloads the instant.
Problem
I can check if the form is hidden using FormInstant.Visable but if the user closes the form this causes an error and the code I would normally use to check if the form exists requires a form name and as it's an instant of a form all the forms have the same name! I do have a reference to the form as it is stored in a local "form" object... The code I would normally use is:
CurrentProject.AllForms("FormName").IsLoaded

So how can I check for a instant of a form being loaded still?

A: An old question but here's what experience taught me: If One, Two, ... instances of FormDefn opened then user closes One (Master which is the only one that can be designed), Forms(FormName) gives an error, Forms(Form) gives wrong object,
but Forms(NumberIndex) does still exist with .Name = FormName!
OpenForm creates the Forms(FormName) object. Once closed Forms(FormName) gives an error. Any "Set xForm = New Form_xxx" creates forms in the forms collection that can only be accessed by the collection number index, and cant be designed.
So to later find a multi-instance form use something like:
Dim FormIdx     As Integer
Dim lForm       As Access.Form
For FormIdx = 0 To Application.Forms.Count - 1
    Set lForm = AccessFunc.Appl.Forms(FormIdx)
    If lForm.Name = pFormName Then
        IsFormOpened = True
        Set rForm = lForm
        GoTo IsFormOpened_Exit
    End If
Next

A: LOL I just realised while re-reading my msg that I can likely trap the error to work out if the form is open or not!
I have quickly written this and it seems to work fine:
Public Function IsFormLoaded(ByRef FormToTest As Form, _
                            Optional ByRef bIsVisable As Boolean = False) As Boolean
    Dim lErrorNum As Long
    bIsVisable = False
    On Error Resume Next
        bIsVisable = NewFormClone.Visible
        lErrorNum = Err.Number
    On Error GoTo 0

    If (lErrorNum = 0) Then
        IsFormLoaded = True
    Else
        IsFormLoaded = False
    End If
End Function

Guess it doesn't really mater who answers the question as long as it is answered and the next guy/gal can use it! :)
I will leave this open for a bit and if nobody finds a better answer I will mark this as it...

A: I like your answer. As for the loop/wait idea? A better way is to always include a reference in each form. I useally declare form module variable called frmPrevious.
Create instance of form
Instance.frmPrevious = me

So now we have the form "call" some code when the form is closed in place of some "visible" + looping code setting.
So in the close code of the form we have:
frmPrevious.FunctionCodeToRun

The above solves a good many issues, but one is you don't need dialog (which as you note cannot use) And you also dump the need for writing "loop + wait" code from the calling code.
This does however mean that your code continues in a new function in the calling form. I thus usually place that function right below the calling code in the calling form. I also tend to use a standard name for that function. I find this trade off worth it as opposed to loop/wait and continuing in the same code routine (I do agree this "continue" in code is often preferable, but then again having to write looping and wait code is not really that clean).

A: Try this also
Function IsLoaded(strFrmName As String) As Boolean

    '  Determines if a form is loaded.

    Const conFormDesign = 0
    Dim intX As Integer

    IsLoaded = False
    For intX = 0 To Forms.Count - 1
        If Forms(intX).FormName = strFrmName Then
            If Forms(intX).CurrentView <> conFormDesign Then
                IsLoaded = True
                Exit Function  ' Quit function once form has been found.
            End If
        End If
    Next

End Function

You can call the above function it in your project like so
If Not isLoaded("MyForm") Then
 MsgBox "MyForm is Not Loaded"
End If


text:
Q: C++: Deep Copy Diamond Pointer Structure In my simulation software, I generate objects with pybind11. So all objects are stored in std::shared_ptr with a not known structure at compile time. For parallelisation of my simulation I need to run the same configuration with different seeds. I want to implement the duplication of these objects in one call on the C++ side.
Following a minimal example, where
I want a2 to be a deepcopy of a, with the diamond structure.
// Type your code here, or load an example.
#include <memory>
#include <map>
#include <iostream>

class C{};
class B{
    public:
    B(std::shared_ptr<C> c):c(c){}
    std::shared_ptr<C> c;
};
class A{
    public:
    A(std::shared_ptr<B> b1, std::shared_ptr<B> b2):b1(b1), b2(b2){}
    std::shared_ptr<B> b1;
    std::shared_ptr<B> b2;
};

auto init(){
    auto c = std::make_shared<C>();
    auto b1 = std::make_shared<B>(c);
    auto b2 = std::make_shared<B>(c);
    auto a = std::make_shared<A>(b1,b2);
    return a;
}

int main(){
    auto a = init();
    auto a2 = a; //deepcopy of a, where b1 and b2 of the copy point to the same object C
}

The only solution I came up with is passing a map<pointer,shared_ptr>. This allows for lookup if the shared_ptr has already been deep copied. (Here I have some problems with the typing as I need to dynamicly cast back the types. This feels really ugly and bugprone.)

A: You can use std::shared_ptr<void> to type-erase all your shared pointers, using std::static_pointer_cast to go to and from your actual types.
using Seen = std::set<std::shared_ptr<void>>;

template <typename T>
std::shared_ptr<T> deep_copy(std::shared_ptr<T> source, Seen & seen) {
    if (auto it = seen.find(std::static_pointer_cast<void>(source)); it != seen.end()) {
        return std::static_pointer_cast<T>(*it);
    }
    auto dest = make(*source, seen);
    seen.insert(std::static_pointer_cast<void>(dest));
    return dest;
}

You can then either write constructors that take an existing instance and a seen map to deep copy the members, allowing them to be private.
template <typename T>
std::shared_ptr<T> make(const T & source, Seen & seen) {
    return std::make_shared<T>(source, seen);
}

class C{
    public:
    C(){}
    C(const C &, Seen &){}
};
class B{
    std::shared_ptr<C> c;
    public:
    B(std::shared_ptr<C> c):c(c){}
    B(const B & other, Seen & seen):c(deep_copy(other.c, seen)){}
};
class A{
    std::shared_ptr<B> b1;
    std::shared_ptr<B> b2;
    public:
    A(std::shared_ptr<B> b1, std::shared_ptr<B> b2):b1(b1), b2(b2){}
    A(const A & other, Seen & seen):b1(deep_copy(other.b1, seen)), b2(deep_copy(other.b2, seen)){}
};

int main(){
    auto a = init();
    Seen a2_seen;
    auto a2 = deep_copy(a, a2_seen);
}

Or you can have overloads of make for each type, where make<T> would need to be friended by T if the members were private.
std::shared_ptr<C> make(const C &, Seen &) {
    return std::make_shared<C>();
}

std::shared_ptr<B> make(const B & other, Seen & seen) {
    auto c = deep_copy(other.c, seen);
    return std::make_shared<B>(c);
}

std::shared_ptr<A> make(const A & other, Seen & seen) {
    auto b1 = deep_copy(other.b1, seen);
    auto b2 = deep_copy(other.b2, seen);
    return std::make_shared<A>(b1, b2);
}


text:
Q: Filtering CSV data using python and storing different values in array I am trying to filter CSV file where I need to store prices of different commodities that are > 1000 in different arrays, I can able to get only 1 commodity values perfectly but other commodity array just a duplicate of the 1st commodity.
CSV file looks like below figure:

CODE
import matplotlib.pyplot as plt
import csv
import pandas as pd
import numpy as np

# csv file name
filename = "CommodityPrice.csv"

# List gold price above 1000
gold_price_above_1000 = []
palladiun_price_above_1000 = []
gold_futr_price_above_1000 = []
cocoa_future_price_above_1000 = []

df = pd.read_csv(filename)
commodity = df["Commodity"]
price = df['Price']

for gold_price in price:
    if (gold_price <= 1000):
        break
    else:
        for gold in commodity:
            if ('Gold' == gold):
                gold_price_above_1000.append(gold_price)
                break

for palladiun_price in price:
    if (palladiun_price <= 1000):
        break
    else:
        for palladiun in commodity:
            if ('Palladiun' == palladiun):
                palladiun_price_above_1000.append(palladiun_price)
                break
for gold_futr_price in price:
    if (gold_futr_price <= 1000):
        break
    else:
        for gold_futr in commodity:
            if ('Gold Futr' == gold_futr):
                gold_futr_price_above_1000.append(gold_futr_price)
                break

for cocoa_future_price in price:
    if (cocoa_future_price <= 1000):
        break
    else:
        for cocoa_future in commodity:
            if ('Cocoa Future' == cocoa_future):
                cocoa_future_price_above_1000.append(cocoa_future_price)
                break

print(gold_price_above_1000)
print(palladiun_price_above_1000)
print(gold_futr_price_above_1000)
print(cocoa_future_price_above_1000)

plt.ylim(1000, 3000)
plt.plot(gold_price_above_1000)
plt.plot(palladiun_price_above_1000)
plt.plot(gold_futr_price_above_1000)
plt.plot(cocoa_future_price_above_1000)
plt.title('Commodity Price(>=1000)')
y = np.array(gold_price_above_1000)
plt.ylabel("Price")
plt.show()
print("SUCCESS")

Here is my question in detail,
Please use pandas and matplotlib to sort out the data in the csv and output and store the sorted data into the process chart. The output results are shown in the following figures.
Figure 1 The upper picture is to take all the products with Price> = 1000 in csv, mark all their prices in April and May and draw them into a linear graph. When outputting, the year in the date needs to be removed. The label name is marked and displayed. The title names of the chart, x-axis, and y- axis need to be marked. The range of the y-axis falls within 1000 ~ 3000, and the color of the line is not specified.
Figure 1 The picture below is from all the products with Price> = 1000 in csv. Mark their Change% in April and May and draw them into a dotted line graph. The dots need to be in a dot style other than '.' And 'o'. To mark, please mark the line with a line other than a solid line. When outputting, you need to remove the year from the date. You need to mark and display the label name of each line. The title names of the chart, x-axis, and y-axis must be marked. You need to add a grid line, the y-axis range falls from -15 to +15, and the color of the line is not specified.
The upper and lower two pictures in Figure 2 are changed to 1000> Price> = 500. The other conditions are basically the same as in Figure 1, except that the points and lines of the dot and line diagrams below Figure 2 need to use different styles from Figure 1.
The first and second pictures in Figure 1 must be displayed in the same window, as is the picture in Figure 2.

A: All of your blocks of code are doing the exact same thing. Changing the same of the iterator doesn't change what it does.
for gold_price in price:
for palladiun_price in price:
for gold_futr_price in price:
for cocoa_future_price in price:

This is going through the exact same data. You haven't subsetted for specific commodities.
Using the break statement in that loop doesn't make sense either. It should be a pass.
Basically for every number above 1000, you iterate through your entire Commodities column and add number to the list for every time you see a specific commodity.
Read how to index and select data in pandas.
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html
gold_price_above_1000 = df[(df.Commodity=='Gold') & (df.Price>1000)]


text:
Q: How to add two delayed jobs I am using delayed_jobs gem. Suppose, I have a ArticleController with following code
@articles.each do |ar|
    #call send mail method and add to delay
    #call createpdf method and add to delay

  end

and another class BackgroundJobs.rb
class BackgroundJobs < ActiveRecord::Base
  def sendmail(article_id)
     #code to send mail
  end

 def createpdf((article_id))
     #code to generate pdf
 end

end

How can I add the send mail and createpdf methods to delayed job in articlecontroller code.

A: First, i would create class methods instead of instance methods in BackgroundJobs:
class BackgroundJobs < ActiveRecord::Base
  def self.sendmail(article_id)
    #code to send mail
  end

  def self.createpdf(article_id)
    #code to generate pdf
  end
end

And then just call them directly in the controller:
@articles.each do |ar|
  BackgroundJobs.delay.sendmail(ar.id)
  BackgroundJobs.delay.createpdf(ar.id)
end


text:
Q: How should I calculate 3 axis of "world coordinates" from device motion? I am having trouble converting the device motion data into world coordinates.
I have been looking into rotation/projection matrixes and quaternion but CMAttitude (roll, pitch, yaw) is where is have had most success using gravity.y & gravity.z to find the device orientation around the same axis as pitch.
The end result i am looking for is a augmented/virtual reality feel as the user looks for 2D game objects around a center point.

A: I wouldn't use Euler angles (roll, pitch, yaw). It pretty much screws up the stability of your app, see here why: Strange behavior with android orientation sensor.
I would use rotation matrices. These tell you how to go from device coordinates to world coordinates and the other way around. You might find these useful:

*

*Theoretical intro

*Developer guide, see rotationMatrix

A: I'm currently working on a tilt-based app and thought I'd share what I ended up finding. This code converts from a quaternion to Euler (Looks like XYX, or ZYZ) and Tait-Bryan angles (looks like XYZ, or ZYX), although I've only used the Tait-Bryan ones myself. After guessing-and-checking through the Tait-Bryan angles, I discovered ZXY worked perfectly for my purposes.
Here's the link: http://bediyap.com/programming/convert-quaternion-to-euler-rotations/
And here's the code:
///////////////////////////////
// Quaternion to Euler
///////////////////////////////
enum RotSeq{zyx, zyz, zxy, zxz, yxz, yxy, yzx, yzy, xyz, xyx, xzy,xzx};

void twoaxisrot(double r11, double r12, double r21, double r31, double r32, double res[]){
  res[0] = atan2( r11, r12 );
  res[1] = acos ( r21 );
  res[2] = atan2( r31, r32 );
}

void threeaxisrot(double r11, double r12, double r21, double r31, double r32, double res[]){
  res[0] = atan2( r31, r32 );
  res[1] = asin ( r21 );
  res[2] = atan2( r11, r12 );
}

void quaternion2Euler(const Quaternion& q, double res[], RotSeq rotSeq)
{
    switch(rotSeq){
    case zyx:
      threeaxisrot( 2*(q.x*q.y + q.w*q.z),
                     q.w*q.w + q.x*q.x - q.y*q.y - q.z*q.z,
                    -2*(q.x*q.z - q.w*q.y),
                     2*(q.y*q.z + q.w*q.x),
                     q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z,
                     res);
      break;

    case zyz:
      twoaxisrot( 2*(q.y*q.z - q.w*q.x),
                   2*(q.x*q.z + q.w*q.y),
                   q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z,
                   2*(q.y*q.z + q.w*q.x),
                  -2*(q.x*q.z - q.w*q.y),
                  res);
      break;

    case zxy:
      threeaxisrot( -2*(q.x*q.y - q.w*q.z),
                      q.w*q.w - q.x*q.x + q.y*q.y - q.z*q.z,
                      2*(q.y*q.z + q.w*q.x),
                     -2*(q.x*q.z - q.w*q.y),
                      q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z,
                      res);
      break;

    case zxz:
      twoaxisrot( 2*(q.x*q.z + q.w*q.y),
                  -2*(q.y*q.z - q.w*q.x),
                   q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z,
                   2*(q.x*q.z - q.w*q.y),
                   2*(q.y*q.z + q.w*q.x),
                   res);
      break;

    case yxz:
      threeaxisrot( 2*(q.x*q.z + q.w*q.y),
                     q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z,
                    -2*(q.y*q.z - q.w*q.x),
                     2*(q.x*q.y + q.w*q.z),
                     q.w*q.w - q.x*q.x + q.y*q.y - q.z*q.z,
                     res);
      break;

    case yxy:
      twoaxisrot( 2*(q.x*q.y - q.w*q.z),
                   2*(q.y*q.z + q.w*q.x),
                   q.w*q.w - q.x*q.x + q.y*q.y - q.z*q.z,
                   2*(q.x*q.y + q.w*q.z),
                  -2*(q.y*q.z - q.w*q.x),
                  res);
      break;

    case yzx:
      threeaxisrot( -2*(q.x*q.z - q.w*q.y),
                      q.w*q.w + q.x*q.x - q.y*q.y - q.z*q.z,
                      2*(q.x*q.y + q.w*q.z),
                     -2*(q.y*q.z - q.w*q.x),
                      q.w*q.w - q.x*q.x + q.y*q.y - q.z*q.z,
                      res);
      break;

    case yzy:
      twoaxisrot( 2*(q.y*q.z + q.w*q.x),
                  -2*(q.x*q.y - q.w*q.z),
                   q.w*q.w - q.x*q.x + q.y*q.y - q.z*q.z,
                   2*(q.y*q.z - q.w*q.x),
                   2*(q.x*q.y + q.w*q.z),
                   res);
      break;

    case xyz:
      threeaxisrot( -2*(q.y*q.z - q.w*q.x),
                    q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z,
                    2*(q.x*q.z + q.w*q.y),
                   -2*(q.x*q.y - q.w*q.z),
                    q.w*q.w + q.x*q.x - q.y*q.y - q.z*q.z,
                    res);
      break;

    case xyx:
      twoaxisrot( 2*(q.x*q.y + q.w*q.z),
                  -2*(q.x*q.z - q.w*q.y),
                   q.w*q.w + q.x*q.x - q.y*q.y - q.z*q.z,
                   2*(q.x*q.y - q.w*q.z),
                   2*(q.x*q.z + q.w*q.y),
                   res);
      break;

    case xzy:
      threeaxisrot( 2*(q.y*q.z + q.w*q.x),
                     q.w*q.w - q.x*q.x + q.y*q.y - q.z*q.z,
                    -2*(q.x*q.y - q.w*q.z),
                     2*(q.x*q.z + q.w*q.y),
                     q.w*q.w + q.x*q.x - q.y*q.y - q.z*q.z,
                     res);
      break;

    case xzx:
      twoaxisrot( 2*(q.x*q.z - q.w*q.y),
                   2*(q.x*q.y + q.w*q.z),
                   q.w*q.w + q.x*q.x - q.y*q.y - q.z*q.z,
                   2*(q.x*q.z + q.w*q.y),
                  -2*(q.x*q.y - q.w*q.z),
                  res);
      break;
    default:
      std::cout << "Unknown rotation sequence" << std::endl;
      break;
   }
}


text:
Q: Loading HOC with Thunk problem with props propagation I created an HOC to deal with loading. It uses a property isLoading to decide what to show.
When I open a page directly from the URL I haven't any issue and everything works fine (because isLoading property is setted up on true by default).
The problem is that when I click on a link (<Link ... />) things doesn't work as expected because isLoading is now false because the page where I am navigating from setted the state to this value.
So, this is the HOC:
import React from 'react';
export default function WithLoading(WrappedComponent, loadingDelegate) {
    class LoadingComponent extends React.Component {
        constructor(props) {

            super(props);
            this.state = {
                isLoading: true
            };
            this.loadingDelegate = loadingDelegate;
        }

        componentDidMount() {
            loadingDelegate(this);
        }

        render() {
            if (this.props.isLoading === true) {
                return (

Loading...

                );
            } else {
                return <WrappedComponent {...this.props} />;
            }
        }
    }

    return LoadingComponent;
}

And below the component:
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators } from './SurveysStore';
import WithLoading from '../LoadingHOC';
//edit/:id
class SurveyDetailRoutedComponent extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (

                {this.props.survey.questions.length}

        );
    }
}

const SurveyDetailRoutedComponentWithLoading = WithLoading(SurveyDetailRoutedComponent, (_context) => _context.props.requestSurvey(parseInt(_context.props.match.params.id)));
export default connect(
    state => state.surveysReducer,
    dispatch => bindActionCreators(actionCreators, dispatch)
)(SurveyDetailRoutedComponentWithLoading);

The error I have is that survey is null, because I tried to render a not already resolver property.
The problem occurs only when I render this component via a <Link> contained in a page rendered in the same way.
I tried to set isLoading=true on the routing, but this doesn't work for me:
export default class App extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <Layout>
                <Route exact path='/' component={(props) => <Home {...props} />} />
                <Route path='/survey/edit/:id' component={(props) => <SurveyDetailRoutedComponent {...props} isLoading={true} />} />
            </Layout>
        );
    }
}

The store itself is very simple and I imagine my error is on how I deal with redux, because it looks like the routing operation is not resetting the loading.
const resetLoading = "RESET_LOADING";
const requestSurveys = "REQUEST_SURVEYS";
const receiveSurveys = "RECEIVE_SURVEYS";
const requestSurvey = "REQUEST_SURVEY";
const receiveSurvey = "RECEIVE_SURVEY";
const initialState = { surveys: [], isLoading: true, survey: null };
export const actionCreators = {
    resetLoading: () => function (dispatch, getState) {
        dispatch({ type: resetLoading })
    },
    requestSurveys: () => async function (dispatch, getState) {
        dispatch({ type: requestSurveys });
        const response = await fetch(...)
        const responseAsJson = await response.json();
        dispatch({ type: receiveSurveys, surveys: responseAsJson.data.surveys });
    },
    requestSurvey: id => async function (dispatch, getState) {
        dispatch({ type: requestSurvey });

        const response = await fetch(...)
        const responseAsJson = await response.json();
        dispatch({ type: receiveSurvey, survey: responseAsJson.data.survey });
    }
};

export const reducer = function(state, action) {
    state = state || initialState;
    switch (action.type) {
        case resetLoading:
            return {
                ...state,
                isLoading: true
            };
        case requestSurveys:
            return {
                ...state,
                isLoading: true
            };
        case requestSurvey:
            return {
                ...state,
                isLoading: true
            };
        case receiveSurveys:
            return {
                ...state,
                isLoading: false,
                surveys: action.surveys
            };
        case receiveSurvey:
            return {
                ...state,
                isLoading: false,
                survey: action.survey
            };
        default:
            return state;
    }
}


text:
Q: Bibliography header inconsistency with my page style using a memoir class I want to have Bibliography as a header title in my bibliography (starting obviously from the second page). But, the title of the previous chapters appears instead!
I am using Memoir class with biblatex. with my pagestyle named as: MyPageStyle
Here is my MWE
\documentclass[oneside,12pt]{memoir}

\usepackage{blindtext}

\makepagestyle{MyPageStyle}
\copypagestyle{MyPageStyle}{ruled}
\makeoddhead{MyPageStyle}{\textsl\leftmark}{}{}

\pagestyle{MyPageStyle}

\usepackage[natbib=true, backend=biber, url=false, isbn=false, sorting=none]{biblatex}
\addbibresource{biblatex-examples.bib}

\begin{document}

\mainmatter

\chapter{Introduction}
\Blindtext

\nocite{*}
\printbibliography

\end{document}

here is a snapshot of my problem

Any idea on how to solve that?
There is this solution but I don't know how to make it work with my specific problem!
Edit 1:
I have tried to change \leftmark with \rightmark as suggested by @daleif. It solved the Bibliography headers, but the other chapters (numbered, unnumbered, appendix) remain un-headed! (see my updated MWE below).
\documentclass[oneside,12pt]{memoir}

\usepackage{blindtext}

\makepagestyle{MyPageStyle}
\copypagestyle{MyPageStyle}{ruled}
\makeoddhead{MyPageStyle}{\textsl\rightmark}{}{}

\pagestyle{MyPageStyle}

\usepackage[natbib=true, backend=biber, url=false, isbn=false, sorting=none]{biblatex}
\addbibresource{biblatex-examples.bib}

\begin{document}

\mainmatter

\chapter[Ch. w/ N.]{Numbered Chapter}
\Blindtext

\chapter*[Ch. w/o  N.]{Unnumbered Chapter}
\Blindtext

\nocite{*}
\printbibliography

\appendix

\chapter[Specs.]{Specification}
\Blindtext

\end{document}

How to solve these inconsistencies?

A: Under oneside you should use \rightmark as this is what most header data providers only write to under oneside.
For the added question:
Not many of the page styles have a oneside and a twoside variant. The default headings does. The style ruled does not. Meaning that \chapter will only write to \leftmark. IMO the default for \chapter should be to write to both (which I normally do in all of my own documents). It is too late to change this now.
Here is how to add bothness:
\addtopsmarks{MyPageStyle}{}{
  \createmark{chapter}{both}{shownumber}{}{. \space}
}

add it somewhere after \copypagestyle{MyPageStyle}{ruled} and before \pagestyle{MyPageStyle}
The psmarks control what and to where macros like \chapter, TOC etc write their stuff


text:
Q: Linked Server Configuration using remote user logins I'm trying to configure a Linked Server using remote logins reducing who has access to the linked server by taking advantage of the not be made option. For test purposes alone, I have used SA, obviously I won't be using that going forwards however I just wanted to make sure the procedure worked and SA having all privileges would cater for this.
Again for troubleshooting purposes, I initially tried SA using the 'be made using this security context' option which worked well but obviously is not secure as I want to reduce who has access to the linked server.
When I tried the 'not be made' option with a local and remote login I receive an error suggesting that no login mapping exists although the login worked when I used the 'be made using this security context' option. What am I doing wrong?

A: I think you need to check the Impersonate option or not use sa for testing—use another SQL Login instead for testing this functionality. I'm not 100% certain it's required but you may also need to consider ensuring the remote logins have a matching sid on both SQL Server instances as I wrote about in the User mapping to a standby database post if you do not use impersonation so something easy enough to test using sp_helplogins and CREATE Login if needed.
Why
I don't recall where I heard or read about it, or if it's even applicable in this case, but I thought the impersonate rights were inherited implicitly for logins with sysadmin and local db_owner rights.

Impersonate
Pass the username and password from the local login to the linked
  server. For SQL Server Authentication, a login with the exact same
  name and password must exist on the remote server. For Windows logins,
  the login must be a valid login on the linked server.
To use impersonation, the configuration must meet the requirement for
  delegation.

Not be made
Specify that a connection will not be made for logins not defined in
  the list.
Source

Impersonation
If you go with using impersonation, below are a couple syntax examples to use for domain user account logins and local SQL logins which connected to the master DB.
GRANT IMPERSONATE ON LOGIN::[domain\username1_to_be_impersonated] TO [domain\username2]
GRANT IMPERSONATE ON USER::[user1_to_be_impersonated] TO [user2]


text:
Q: How to disable "look up" context menu in Google Chrome OSX 10.10+? This is a distinct question from Is the "Lookup in Dictionary" context menu option hardcoded in Google Chrome for Mac?
I want to get rid of the "Look Up x" contextual menu in Chrome:
How can it be done?

A: Unfortunately it cannot be removed. It was marked as WontFix because it's part of the MacOS convention. It has been officially answered here: https://bugs.chromium.org/p/chromium/issues/detail?id=543891

A: Not really answer as much as workaround: Lean on Command-C.
I like the "rapid dictionary" feature. When 95% certain I'm about to use a word correctly, confirming is faster than opening a new tab to type dictionary.com/browse/X.
I'd be interested in hearing why you (OP, @aaronbauman) dislike it.  Maybe adding your name will flag you to respond.

This answer is nearly three years old--haven't used Mac for awhile, don't recall my mindset at the time. But re-reading suggests I got more of a "copy" impression from the question that I get from it now.  Edited for brevity.

A: I know this isn't what you want to hear, but maybe you should switch to command + c to copy if you want to avoid it. Thats what I migrated to and I almost forgot "Look Up" was even there. It'll eventually become a reflex.


text:
Q: Problemas para fazer conexão serial Arduino com PHP Estou tentando fazer um termômetro com PHP, no Windows 10, e estou capturando os dados através de um Arduino com o código:
#include <OneWire.h>

#include <DallasTemperature.h>

// Conectar o pino central dos sensores ao pino 10 do Arduino
#define ONE_WIRE_BUS 10

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
DeviceAddress thermometerOne = { 0x28, 0xFF, 0x72, 0xC0, 0x62, 0x15, 0x01, 0x38 };
DeviceAddress thermometerTwo = { 0x28, 0xFF, 0xFA, 0x65, 0x72, 0x15, 0x02, 0x4D };

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  // Start up the library
  sensors.begin();
  // set the resolution to 10 bit (good enough?)
  sensors.setResolution(thermometerOne, 12);
  sensors.setResolution(thermometerTwo, 12);
}

void getTemp(){
  printTemperature(thermometerOne);
  Serial.print(" ");
  printTemperature(thermometerTwo);
}

void printTemperature(DeviceAddress deviceAddress)
{
  sensors.requestTemperatures();
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC == -127.00)
  {
    Serial.print("Erro");
  }
  else
  {
    Serial.print(tempC, 4);
  }
}

void IDFuncao(String funcao){
 if (funcao == String("temp")){
  getTemp();
 }
}

void decodificaMensagem(String mensagem){
  int i;
  String funcao = "";
  for (i=1; i<=4; i++){
    funcao = funcao + String(mensagem[i]);
  }
  IDFuncao(funcao);
}

void loop(void)
{
  //Verificando se tem algo na Porta
  if (Serial.available() > 0){
    String mensagem = Serial.readString();
    String inicio = String(mensagem[0]);

    //Verificando se o que eu recebi começa com #
    if (inicio == String("#")){
      decodificaMensagem(mensagem);
    }
  }
}

Já pesqusei várias formas de captar os dados no PHP como este, usando phpserial:
PhP Serial
include 'PhpSerial.php';

$serial = new PhpSerial;

$serial->deviceSet("COM5");
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");

$serial->deviceOpen();

sleep (1);
$serial->sendMessage("#");

global $ler_serial;
$ler_serial = $serial->readPort();

$serial->deviceClose();

porém, recebo esse mensagem:

Warning: Unable to open the device [...]

E fazendo:
$port = "COM5";
$fp = fopen($port, "r+b");
//sleep(1);
fwrite($fp,'#');
print_r($fp);
print_r(fgets($fp));
fclose($fp);

recebo:

Warning: fopen(COM5): failed to open stream: Permission denied

Um amigo meu que fez o código do Arduino, ele disse que eu precisava mandar um '#' para o Arduino, como se fosse um protocolo, mandando o '#', ou não, o resultado é o mesmo.
O que posso fazer para receber as temperaturas captadas pelo Arduino?

A: Isto parece indicar apenas que a porta COM5 não é a porta correta, ou esta desligada, para checar a porta correta abra o gerenciador de drivers, então vá até COM & LPT Deve aparecer algo como:

Se não aparecer nada em Portas (COM & LPT) (ou Ports COM & LPT em sistemas em inglês) significa que há algum problema na conexão do equipamento e talvez ele esteja em outros dispositivos, veja se existe algo lá com um simbolo de exclação em um ícone amarelo, como por exemplo:

Isto significa que falta algum driver no seu sistema, ou que existe alguma falha no hardware.
Se estiver em Ports/Portas e estiver funcionando normalmente, mas não é exibido a porta entre (COM ...) então basta clicar com o direito do Mouse/Rato nele e clicar em Propriedades/Properties

Se estiver tudo correto e não houver nenhum icone amarelo com exclamação então você pode efetuar o teste da porta usando softwares como Hyperterminal, no entanto este software parece não existir para Windows10 (talvez exista em windows-server), como alternativa pode baixar o:

*

*https://sourceforge.net/projects/hypeterminal/
Abra o programa e clique em Set Up > Port Configuration, ou simplesmente aperte Alt+C, irá abrir esta janela:

Observe no combox Port:, veja se aparece a porta COM5, se não aparecer é porque não esta conectado, se aparecer selecione ela e clique no botão ao lado chamado Connect, se ocorrer qualquer erro é algum problema no Hardware ou problema na configuração do mesmo.


text:
Q: Approximating bounded functions $f \in B([0,1], \mathbb{R})$ by simple functions (not necessarily measurable) If we have any arbitrary bounded function $f: [0,1] \to \mathbb{R}$, is it possible to approximate this by a sequence of simple functions, i.e. functions of the form $\sum_{j=1}^{n} a_j \chi_{A_j}$ (where $\chi_{A}$ denotes the characteristic function on $A$)?
$f$ may not be measurable, all we are given is that it is in $B([0,1], \mathbb{R})$, which we are considering as a normed vector space with the sup-norm.

A: Since $f$ is bounded, set $K=\overline{f([0,1])}$. Then $K$ is a compact set. Let $E=\{r_n\}$ be a countable, dense subset of $K$ and for $\varepsilon>0$ consider the open cover $\mathcal{U}_\varepsilon=\{U_{n,\varepsilon}\}_{n=1}^\infty$, where $U_{n,\varepsilon}=(r_n-\varepsilon,r_n+\varepsilon)$. Now for any $\varepsilon>0$ this cover reduces to a finite subcover, so there exists an integer $M_\varepsilon$ and a function $q:\{1,\dots, M_\varepsilon\}\to\mathbb{N}$ (just a fancy way of picking $M_\varepsilon$-many indexes) so that
$$K\subset\bigcup_{i=1}^{M_\varepsilon}U_{q(i),\varepsilon}$$
For $n\geq1$ set $M_n=M_{\frac{1}{n}}$ and $V_{i,n}=f^{-1}(U_{q(i),\frac{1}{n}})$ for all $i=1,\dots, M_n$. Define
$$f_n(x)=\sum_{i=1}^{M_n}r_{q(i)}\cdot\chi_{V_{i,n}}$$
for $x\in[0,1]$. These are simple functions. Now let $x\in[0,1]$. Then $f(x)\in K$ so for each $n\geq1$ we have that $f(x)$ belongs to some $U_{q(i),\frac{1}{n}}$, so $f_n(x)=r_{q_i}$ while $f(x)\in U_{q(i),\frac{1}{n}}$, so $|f_n(x)-f(x)|<\frac{1}{n}$.
This shows that $f_n\to f$ uniformly, where $f_n$ are simple functions. Of course the sets can be extremely crazy, but you put no such restriction so there is no problem with that.


text:
Q: How to draw graphics on screen without using any framework or library? I want to manually draw the graphics, what that mean is without using any library or frame work like QT, directX , whindow.h .... like giving command to every pixels on the screen to show some specific color at different time. Every body gives tutorials on based on these library or whatever they are called. What i want  is to make my own GUI. As far as I could think it is going to be very complicated, hard to learn and to understand, messy and a lot of time consuming, but I am ready for that. I need some resources to understand that.
and Yes i know C++ so it would better if I had to work with this language but I will learn other language if it is required, just i want to know which language i should learn.

A: In the old days, you could write directly to video memory with no help from the operating system/ROM.  Today, on current hardware, you have to go through the operating system in order to write to the screen.  That means using a separate library (like Qt) or using the OS features (windows.h).  You could use directX or something and get more raw access to video memory, but that is still using a library/framework.

A: If  you want with C++  and native  Windows API (without  DirectX)  , you  should  use  GDI(Microsoft Graphics device  interface) +  MFC(Microsoft Foundation  Classes)  this is  a  classic  implementation of  Windows GUI,  If you want complicated  graphics with shaders  you need  DirectX/OpenGL  without  hesitation. meanwhile if you  want  higher  programming  framework  you can use  C#(CSHARP)  or Java.


text:
Q: laravel 5.8 Missing required parameters for [Route: listajoburi.update] [URI: listajoburi/update/{id}] I'm trying to edit some data from database for a certain id which is selected from the edit button in another form.
It would help me if you can explain what is happening here, I'm new to laravel, I have tried to understand the documentation but I didn't find any explanation for this
 <form action="{{route('listaasdjoburi.updaasdte', $isd)}}" method="post" enctasdype="multasdipart/foasdrm-dasdata">
                @csrf

                        Nume Job
                        <input type="tasdext" class="form-casdontrol" id="tiasdtlu" name="titlu" value="{{$jobuasdri->tiasdtlu}}"/>

                        Desasdcriere:
                        <input type="teasdxt" class="foasdrm-control" id="deasdscriere" name="descriere" value="{{$joburi->descriere}}"/>

                        Salaasdriu Estiasdmativ:</labasdel>
                        <input type="text" class="form-control" id="salarasdiu_asdestimativ" name="sasdalariu_estimasdativ" value="{{$joasdburi->salasdariu_estimasdativ}}"/>

                        Orasds:
                        <input type="teasdxt" class="forasdm-control" id="orasdas" name="oasdras" value="{{$jobasduri->oraasds}}"/>

                        Actasdiv(1=actasdiv,0=inactasdiv)
                        <input type="tasdext" class="form-control" id="aasdctiv" name="aasdtiv" value="{{$jobasduri->actiasdv}}">

this is the controller
public function index()
    {
        $jobuasdri = Joadsburi::all()->toasdArray();
        return view('listajasdoburi', compasdact('jobasduri'));
    }

    public function easddit($id)
    {
        $jobasduri = Jobasduri::fiasdnd($id);
        return view('editaasdrejob', compasdact('joasdburi', 'iasdd'));
    }

    public function update(Requasdest $requasdest, $iasdd)
    {
        $this->validasdator($requasdest->all());

        $update = Jobuasdri::fiasdnd($id)->upasddate([
            'titasdlu' => $request->tasditlu,
            'descasdriere' => $request->dasdescriere,
            'salaasdriu_estasdimativ' => $request->salarasdu_estimasdativ,
            'oraasds' => $reqasduest->asdoras,
            'activ' => $reqasduest->aasdctiv,
            //  'skasdill' => $requasdest->ciasdty,
        ]);

        if ($updaasdte) {
            returasdn redasdirect()->route('lisasdtajoburi.updasdate')->witasdhSuccess('S-a modifiasdcat cvu suasdccess!');
        } else {
            return rediasdrect()->back()->wiasdthDanger('Nu s-a moasddificat! A apaasdrut o eroasdare.');
        }
    }

    protected function validasdator(array $daasdta)
    {
        return Validaasdtor::masdake($dasdata, [
            'tiasdtlu' => ['requasdired', 'striasdng', 'masdin:3', 'masdax:255'],
            'descasdiere' => ['requasdired', 'striasdng', 'max:11'],
            'salarasdiu_estimativ' => ['requasdired', ''],
            'orasdas' => ['stasdring', 'max:512asd'],
            'actasdiv' => ['requasdired', 'strasding', 'max:asd512'],
            // 'skiasdll' => ['sasdtring', 'maasdx:45'],
        ]);

    }
}

and this is the route
Route::get('/listajasdasdoburi', 'asdAuth\ListasdaJoburiController@index')->name('listajoasdburi');
Route::get('/editasdarejob/{idasd}/', 'Auasdth\ListaJoburiController@edit')->name('editarejasdob');
Route::post('/listasdajoburiupdate/{id}', 'Auth\LisasdtaJoburiController@update')->nasdame('listajoburasdi.updaasdte');

A: The problem is that your route look like this:
Route::post('/listajoburiupdate/{id}', 'Auth\ListaJoburiController@update')->name('listajoburi.update');

And you try to make redirection like this in your controller:
return redirect()->route('listajoburi.update')->withSuccess('S-a modificat cu success!');

so you don't pass id here. It should be probably:
return redirect()->route('editarejob', $id)->withSuccess('S-a modificat cu success!');

because:

*

*you cannot make redirection to route that uses POST - you can only make redirection to route that uses GET (in this case to edit form)

*you need to pass id because both 2nd and 3rd route need {id} parameter


text:
Q: Position, velocity and acceleration vs time graphs I'd like to draw graphs of a vehicle and I have a position vs time table.

I can set the points but how am I supposed to join them, straight or hyperbole ?
If the object is accelerating which is yes then we can say velocity is decreasing and we'd draw it like this ? (not to scale, I know)

Sorry for drawing so badly

A: Since only data you have is this table, you don't need to connect the points and speculate on if its graph is linear or not.You can't really know its properties with this much information. Each interval can either be linear or nonlinear on its own. Therefore, you can just leave it like this:

If you really want to sketch the velocity-time graph(again you don't have to with just this much information), you can find the average velocity for each interval and sketch it accordingly. However, take these points into consideration while sketching it:

*

*What you essentially need to accomplish is to make the area under the graph at each interval to be equal to $\Delta x$ of each interval.

*The average velocity for each interval would be $2.2$ $m/s$, $-1.4$ $m/s$, $-3.8$ $m/s$, $-3.7$ $m/s$, $-1.6$ $m/s$ respectively. However, you can't really set these values in the graph since you can't know at what point these velocities are reached. You need to know instantaneous velocity of the object at each time to accurately sketch the graph.(which will require $x(t)$ function)

*The graph will just be an approximation and probably not even a close one.

A: The position-time graph you've sketched looks roughly right (though be careful to make the scale on the vertical axis consistent).  The data don't look at all linear and don't justify a straight line.
The second graph has a couple problems.

*

*Is it a speed vs. time graph or a velocity vs. time graph?  In what you've written you refer to velocity so, if that's what you are graphing, the last two points should be negative 1.4 and negative 3.8.

*You got the velocity values by finding change in position divided by change in time for each interval.  This gives you the average velocity during each 10 second interval.  If you're plotting a graph you should be using the instantaneous velocities.  The average velocity values you found will be the instantaneous velocities at some point during that 10 second interval but most likely not right at the beginning of the interval.  A somewhat better approach would be to plot the 2.2 m/s point at 15 seconds, the -1.4 point at 25 seconds etc.

*You have no reason to believe the velocity at t=0 is zero.  Don't plot a point at the origin.


text:
Q: get the value from a text input after it is updated in react function I'm learning React and I need help understanding how to create functions for values that are updated asynchronously in the DOM.  For instance, I have a text input within a component called header that looks like this:
export default class Header extends React.Component {
    constructor(props){
        super(props);
    }
    render(){
        return (

<input onKeyDown={this.props.onEnter} id="filter-results" className="full" type="text" placeholder="search kks"></input>

<button className="full">SEARCH</button>

        );
    }

}

, which is used to filter search results.  The onEnter function tries to use the value updated in the input:
class App extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            categories: [],
            searchResults: [],

        };
        this.filterSearch = this.filterSearch.bind(this);
    }
    filterSearch(){
        var el = document.getElementById('filter-results').value
        console.log(el)
        var result = this.state.categories.filter(row => {
            var rx = new RegExp(el)
            return rx.test(row['id'])
        });
        console.log(result)
    }
    render(){
        return (

        );
    }
}

When I type something into the input, the element's value is logged to the console.  The problem is, what is logged is always one character less than what I expect to see.  If I type 'a', I get '', 'ab' => 'a', etc.  I can understand conceptually that when the function is triggered and the logging occurs the value hasn't yet been updated, but I don't know how to wait for the value to be updated and then work with it.  Can anyone help me?

A: Use onChange instead.
//change handler
handler(e) {
    console.log(e.target.value)
}
//input's onChange event
onChange={ this.handler.bind(this) }

A: 1) You should not be using native javascript to get value by id. This is not react way of doing.
App.js
import React from "react";
import ReactDOM from "react-dom";
import Header from "./Header";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      categories: [],
      searchResults: []
    };
    this.filterSearch = this.filterSearch.bind(this);
  }
  filterSearch(value) {
    console.log(value);
    var result = this.state.categories.filter(row => {
      var rx = new RegExp(value);
      return rx.test(row["id"]);
    });
    console.log(result);
  }
  render() {
    return (

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

// Header.js
import React from "react";

export default class Header extends React.Component {
  constructor(props) {
    super(props);
  }

  handleChange = ({ target }) => {
    this.setState({
      [target.name]: target.value
    });
    this.props.onEnter(target.value);
  };
  render() {
    return (

          <input
            onChange={this.handleChange}
            name="filter-results"
            className="full"
            type="text"
            placeholder="search kks"
          />

          <button className="full">SEARCH</button>

    );
  }
}


text:
Q: Magento integrate filters I want to integrate and edit the filters feature.
I have this code :
<?php $_filters = $this->getFilters() ?>
        <?php foreach ($_filters as $_filter): ?>
            <?php if($_filter->getItemsCount()): ?>
                <div class="option-combo <?php echo $this->__($_filter->getName()) ?>">
                    <ul class="filter option-set clearfix " data-filter-group="<?php echo $this->__($_filter->getName()) ?>">

<?php echo $this->__($_filter->getName() ) ?> :

<a href="#filter-<?php echo $this->__($_filter->getName()) ?>-any" data-filter-value="" class="selected">All

                            <?php echo $_filter->getHtml() ?>

            <?php endif; ?>
        <?php endforeach; ?>>

And it works, but I dont want to call another extern phtml file (filter.phtml, from $_filter->getHtml()) But when I copy the code from the filter.phtml directly into the my main page, like this :
<?php $_filters = $this->getFilters() ?>
<?php foreach ($_filters as $_filter): ?>
    <?php if($_filter->getItemsCount()): ?>
        <div class="option-combo <?php echo $this->__($_filter->getName()) ?>">
            <ul class="filter option-set clearfix " data-filter-group="<?php echo $this->__($_filter->getName()) ?>">

<?php echo $this->__($_filter->getName() ) ?> :

<a href="#filter-<?php echo $this->__($_filter->getName()) ?>-any" data-filter-value="" class="selected">All

                    <?php //echo $_filter->getHtml() ?>

                    <?php foreach ($this->getItems() as $_item): ?>

                        <?php if ($_item->getCount() > 0): ?>

                            <?php $Clean = $_item->getLabel();      ?>

<a href="#filter-<?php echo $_item->getLabel() ?>-<?php echo $Clean ?>" data-filter-value=".<?php echo $Clean ?>"><?php echo $_item->getLabel() ?>

<a href="<?php echo $this->urlEscape($_item->getUrl()) ?>"><?php echo $_item->getLabel() ?>
                        <?php else: echo $_item->getLabel() ?>
                    <?php endif; ?>

                    <?php if ($this->shouldDisplayProductCount()): ?>
                        (<?php echo $_item->getCount() ?>)
                    <?php endif; ?>

                <?php endforeach ?>

    <?php endif; ?>
<?php endforeach; ?>

It doesn't show any results... And no errors !

A: You can try below Code :-
   <?php $_filters = $this->getFilters() ?>
            <?php foreach ($_filters as $_filter): ?>
            <?php if($_filter->getItemsCount()): ?>

<?php echo $this->__($_filter->getName()) ?>

<?php echo $_filter->getHtml() ?>

             <?php else:?>
                // here you can add own code
            <?php endif; ?>
            <?php endforeach; ?>