text:
Q: Data from server to client in NodeJS express I am new to NodeJS.
I want to perform a task where, HTML submit button POST data to server
below is the HTML code,
<form action="/Device_Data" method="post">
  <select name="deviceSelect" id="deviceSelect" class="selectdevice" type = "text" style="margin-top:1.5%">
    <option value="" selected="selected">Choose Device</option>
    <option value="Device1">Device 1</option>
    <option value="Device2">Device 2</option>
    <option value="Device3">Device 3</option>
    <option value="Device4">Device 4</option>
    <option value="Device5">Device 5</option>
    <option value="Device6">Device 6</option>
    <option value="Device7">Device 7</option>
    <option value="Device8">Device 8</option>
  </select>
  <button id="Import" value="Import" class="button1" type="submit" >Import</button>
</form>

Server received the Data in req.body.
app.post("/Device_Data", function (req, res) {
  console.log("Got response: " + res.statusCode);

  // result.entries contains entities matching the query
  res.setHeader('Content-Type', 'application/json');
  //console.log(req.body.deviceSelect);

  var deviceSelected = (req.body.deviceSelect);
  console.log(deviceSelected);

  var devData = ["deviceId","trainId", "messageId"];

  //var devData = [];
  var text = JSON.stringify(response.body);
  var obj = JSON.parse(text);
  res.write("Hello");
});

Now the part I have question is,
How I can send devData array of string from server to my client and what should be code for that?
Thanks in advance.

A: According to express documentation, use res.json to send json data as an request answer.
res.status(200).json(devData);

Example from documentation :
res.json(null);
res.json({ user: 'tobi' });
res.status(500).json({ error: 'message' });


text:
Q: Cannot find module 'commander' When I try and run my mocha tests I get
$ npm t

> digitalAlarmClock@1.0.0 test /home/durrantm/Dropnot/code/js/mochaChai/digitalAlarmClock
>  mocha *.test.js

internal/modules/cjs/loader.js:979
  throw err;
  ^

Error: Cannot find module 'commander'
Require stack:
- /usr/lib/nodejs/mocha/bin/_mocha
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:976:15)
    at Function.Module._load (internal/modules/cjs/loader.js:859:27)
    at Module.require (internal/modules/cjs/loader.js:1036:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/usr/lib/nodejs/mocha/bin/_mocha:10:17)
    at Module._compile (internal/modules/cjs/loader.js:1147:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
    at Module.load (internal/modules/cjs/loader.js:996:32)
    at Function.Module._load (internal/modules/cjs/loader.js:896:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/usr/lib/nodejs/mocha/bin/_mocha' ]
}
npm ERR! Test failed.  See above for more details.

How to fix?

A: here's how I solve the issue:
run npm list to see if there's any dependency missing, for example, I saw:
[root@d21b188bb7e1 configurable-http-proxy]# npm list
configurable-http-proxy@4.3.2 /srv/configurable-http-proxy
├── UNMET DEPENDENCY commander@~7.2.0
...

install it manually by
npm install --save commander@~7.2.0

A: This can happen for several different reasons.
In this case it is because mocha isn't installed.
Fix with
npm install --save-dev mocha

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change column to unique I have a table with data, and I want to change some column to unique, it must to be unique, but I'm worried about have duplicated data in that column and it brings some problems to my database.
I want to know what happen if I change a column to unique that doesn't have unique data, I'll lost some records, just got an error message, or something else?
PS.: I'm using SQL Server
Thanks in advance.

A: alter table YourTable add constraint UX_YourTable_YourColumn unique(YourColumn)

If there is duplicate data, the alter will abort without making any changes.
You can query duplicates like:
select  YourColumn
,       count(*) as DuplicateCount
from    YourTable
group by
        YourColumn
having  count(*) > 1

A: You just won't be able to add a UNIQUE constraint on a COLUMN with duplicates datas.
In SSMS, the error message is something like that
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.<Table>' and the index name '<constraintname>'. The duplicate key value is (<NULL>).

Could not create constraint. See previous errors.

So you can be quiet, you won't lose any data.


text:
Q: How to make Alt + Click work with Gnome panel in 12.04? I am using 12.04 with Gnome 3.
Super + Alt + Right Click works in Gnome Classic. However, Alt + Click doesn't work with Gnome Panel.
Normally, it should bring up a way to customize the panel.

A: I found a solution to the problem, see: https://bugs.launchpad.net/ubuntu/+source/gnome-panel/+bug/891622
We need to run the following command in terminal:
gconftool-2 --set --type string /apps/metacity/general/mouse_button_modifier '<Super>'


text:
Q: Enable Django and Tastypie support for trailing slashes? My problem is that Backbone is trying to do an HTTP request on a URL with a slash at the end, like the following:
:8000/api/v1/update/2/

For some reason, Django (or tastypie) is not accepting URLs with slashes at the end, so the above URL will not work, but this URL does work:
:8000/api/v1/update/2

Backbone-tastypie falls back to oldSync, which is the original sync that comes with Backbone, when not using its overridden sync. I believe that when Backbone-tastypie uses oldSync, it appends a slash at the end of the URLs, which I do not want.
Most of the solutions being suggested are dealing with the opposite problem I have. They are trying to fix the problem where trailing slashes work, but no trailing slashes do not work.
I need to be able to support trailing slashes in addition to non-trailing slashes. This can be fixed in two ways:

*

*How do I change the backbone-tastypie code so that no AJAX calls append the slash at the end?

*How do I make it so that Django/tastypie will treat the above two URLs as the same?
Either one of those will fix my problem, but I cannot figure out how to implement any of them.

A: You can tell Tastypie/Django to allow or disallow trailing slashes.
Look here

A: For a Backbone solution:
You can overwrite the default behavior of Model.url, even using the normal one and making a small modification like the one you are looking for:
// code simplified and not tested
var MyModel: Backbone.Model.extend({
  url: function() {
    var original_url = Backbone.Model.prototype.url.call( this );
    var parsed_url = original_url + ( original_url.charAt( original_url.length - 1 ) == '/' ? '' : '/' );

    return parsed_url;
  }
});

Same aplies for Collection.


text:
Q: Numbers auto date on template only Is it possible to use the =today() function (or something else) to insert the current date but then not update each time the file is opened?
I want to create a numbers template for my invoices. I'd like it to auto fill invoice date and date due then, when I save the document, store the values, not the function.

A: Go to Insert > Date & Time.

Double-click the date and format to taste. Make sure "Automatically update on open" isn't ticked.


text:
Q: Pulseaudio issue: Audio output randomly stops with Focusrite Scarlett Solo Im using a Focusrite Scarlett Solo as a headphone audio output and mic input.
The audio output randomly stops and can only be restarted by replugging the Scarlett Solo. It doesn't happen for other usb audio outputs.
It randomly stops in very different intervals: sometimes it works for hours, sometimes its fails in quick succession.
I have used it on Windows for a couple of hours and had no issues, but can't be sure that it wasnt "luck".
I suspect PulseAudio is causing the problem. I looked on the internet and found this post https://forums.linuxmint.com/viewtopic.php?t=275031 with these commands to log PulseAudio here :
sudo killall pulseaudio
sudo pulseaudio -vvvv --log-time=1 > ~/pulselog.log 2>&1
The full log is are here : https://pastebin.com/Mzm0X0Q6
but i think the key part happens here:
...
(  14.204|   0.617) I: [pulseaudio] module-device-restore.c: Synced.
( 882.588| 868.384) I: [pulseaudio] main.c: Got signal SIGINT.
( 882.590|   0.001) I: [pulseaudio] main.c: Exiting.
( 882.590|   0.000) I: [pulseaudio] main.c: Daemon shutdown initiated.
( 882.590|   0.000) I: [pulseaudio] module.c: Unloading "module-filter-apply" (index: #23).
...

To me this looks like a crash or shutdown of some kind but i wasn't able to find further information. How do i go on debugging this?
After a crash the correct audio output device is still shown in the PulseAudio Volume Control and the microphone input of the Scarlett Solo still works fine, the audio output just doesn't work.
Specs:
Audio device: Focusrite Scarlett Solo
Distro: Linux Debian 10 (Gnome)
Pulseaudio version 12.2
Im not experienced on debugging linux issues so any help or direction is appreciated.
Edit: Turns out it was a Hardware issue, it happened on Windows and also didn't happen with another Focusrite Scarlett Solo 3rd Gen over 10s of hours.

A: Attach GDB to the running PulseAudio daemon and let it continue running:
$ gdb -p $(pgrep pulseaudio) -ex continue /usr/bin/pulseaudio

When a signal is delivered, GDB will catch it and let you examine it. For example:
(gdb) ptype $_siginfo
[...]
(gdb) print $_siginfo._sifields._kill
$2 = {si_pid = 19569, si_uid = 1234}

man sigaction provides some background.

A: The root of your problem could be the USB autosuspend feature of TLP (power management) if that is being shipped with your distro.
Try to disable it by running systemctl disable tlp.service and reboot.
If you want to keep it running you can also blacklist your audiointerface as described in the documentation: https://linrunner.de/tlp/settings/usb.html
There is also a UI for adjusting the config called tlpui.
More Info here:
https://wiki.archlinux.org/index.php/TLP#USB_autosuspend


text:
Q: Extjs How to scroll to selected item in a combo box on expand I am new to Extjs so please kindly help me out on this issue even though it may sound easy.
I have a combo box which I want it to display the area of the selected items whenever it is expanded.
My code looks like below:
xtype: 'combo',
id: 'hdpbox',
store: storeNumber,
queryMode: 'local',
forceSelection: true,
selectOnFocus: true,
displayField: 'display',
valueField: 'value',
listeners: {
  expand: function(){
  //Some functions will go here in order to show where the selected item in the list
  }
}

It always display the top records on expanding although the selected item is the one from the bottom.
I have tried many ways but non have worked out. I am using Ext 4.2.1 just for your info.
Thank you very much for you time and concern

A: I found solution based on ExtJs 4.2.1 + jQuery (you can use vanilla js):
      expand: function(combo) {
        var val = combo.getValue();

        if (val !== null) {
          var rec = combo.findRecordByValue(combo.getValue()),
            node = combo.picker.getNode(rec);

          $(combo.picker.listEl.dom).scrollTop($(combo.picker.listEl.dom).scrollTop() + $(node).position().top);
        }

      },

A: To expand on Alex Dzeiko answer, instead of jQuery we can use:
combo.picker.getTargetEl().setScrollTop(node.offsetTop);

or (using a somewhat undocumented propertie/function)
combo.picker.listEl.scrollChildIntoView(node, false);

Complete example
expand: function(combo) {
    var val = combo.getValue();

    if (val !== null) {
      var rec = combo.findRecordByValue(combo.getValue()),
        node = combo.picker.getNode(rec);

      combo.picker.getTargetEl().setScrollTop(node.offsetTop);
    }
  },

This also worked for me
We need to set autoSelect = true (the default setting) on the combo box for this to work.
expand: function(combo) {
    var val = combo.getValue();

    if (val !== null) {
      var rec = combo.findRecordByValue(val);

      combo.picker.getSelectionModel().lastSelected = rec;
    }
  },

Note
Ext JS already selects the proper item by default, I needed this code to show a item similar to what the user typed, instead of showing the first item (the code above does not reflect this entire solution).

A: Try this: (added a listener afterrender) to what is in sencha docs.
var states = Ext.create('Ext.data.Store', {
fields: ['abbr', 'name'],
data : [
    {"abbr":"AL", "name":"Alabama"},
    {"abbr":"AK", "name":"Alaska"},
    {"abbr":"AZ", "name":"Arizona"}
    //...
]
});

// Create the combo box, attached to the states data store
Ext.create('Ext.form.ComboBox', {
fieldLabel: 'Choose State',
store: states,
queryMode: 'local',
displayField: 'name',
valueField: 'abbr',
renderTo: Ext.getBody(),
listeners: {
    scope: this,
    'afterrender': function(combo) {
        debugger;
        combo.setValue('AZ');
    }
}
});


text:
Q: Porting a MATLAB code to Python UPDATED TO REFLECT COMMENTS
I am required to port a MATLAB code into python. Unfortunately, despite lot os sleepless nights of debugging and googling, I cannot get my code to run. Here is the MATLAB code in question:
clc;
serie =0:50;
serie = serie - mean(serie);
y = cumsum(serie);
L = length(y);
%Calculate the detrended fluctuation short term coefficient
npuntos = 10;
f1=zeros(1,npuntos);
for n1=4:16
%Segmentation
seg =(1:n1:L);
%disp(length(seg))
yn = zeros(1,L);
    for k = 1:length(seg)-1
        yaux = y(seg(k):seg(k+1)-1);
        x = 1:length(yaux);
        A=[sum(x.^2),sum(x); sum(x),length(x)];
        C=[sum(x.*yaux);sum(yaux)];
        v=inv(A)*C;
        a=v(1); b=v(2);
        pen=a;
        ord=b;
        ytrend = pen*x + ord;
        yn(seg(k):seg(k+1)-1) = ytrend';
    end
f1(n1) = sqrt((1/seg(end)).*sum((y(1:seg(end)-1)-yn(1:seg(end)-1)).^2));
end
n1=4:16;
f1=f1(4:end);
p1 = polyfit(log10(n1(1:end-2)),log10(f1(1:end-2)),1);
alpha1 = p1(1);
disp(alpha1)

My attempt to translate the code into python goes as follows:

import numpy as np

data = np.arange(start=0, stop=51, step=1)
data = data.transpose()
data = data - np.mean(data)
y = np.cumsum(data)
L = len(y)
# Estimate the value of alpha1

npuntos = 12
f1 = [0] * npuntos
for i, n1 in enumerate(np.arange(start=4, stop=16, step=1)):
    seg = np.arange(start=0, stop=L, step=n1)  # Potential error
    yn = [0] * L
    for k in np.arange(start=0, stop=len(seg)-1, step=1):  # Potential Error
        yaux = y[seg[k]:seg[k + 1]-1]  # Potential Error
        x = np.arange(start=1, stop=len(yaux) + 1, step=1)
        A = [[sum(x ** 2), sum(x)], [sum(x), len(x)]]
        C = [[sum(x * yaux)], [sum(yaux)]]
        v = (np.linalg.inv(A)).dot(C)
        pen = v[0]
        ord = v[1]
        ytrend = pen * x + ord
        yn[seg[k]: seg[k + 1] - 1] = ytrend
    f1[i] = np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2))
n1 =np.arange(start=4, stop=16, step=1)
f1 = f1[4:]
xx =np.log10(n1[1: - 2])
yy=np.log10(f1[1: - 2])
print(len(xx))
print(len(yy))
p1 = np.polyfit(xx, yy, 1)
alpha1 = p1[1]
print(alpha1)

Unfortunately, I get TypeError when the program is executing this line
p1 = np.polyfit(xx, yy, 1)

This is indeed expected as xx is of length 9 while xx is just 5. By using try/catch block as suggested in the comment,
try:
    f1[n1] = np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2))
except IndexError:
    f1.append(np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2)))

the error is fixed by the output is completely wrong.
I have gone through the debugger but I cannot quite how the error. Can someone please help?
P.S -The above snippet is supposed to calculate the Detrended Fluctuation Analysis (DFA) if anyone is interested.

A: Thats because you have npuntos = 10 so that f1 = [0] * npuntos makes your f1 list's size equal 10. And then you iterate over
for n1 in np.arange(start=4, stop=16, step=1):

And accessing f1[n1] which from 10 to 15 will give you an IndexError
UPDATE
First of all you can use np.zeros((5,), dtype=np.int) since you already using np module.
Secondly to figure out the thing with IndexError. Personally i don't want to fall into mathematical problem that you are solving, so the solution won't be the best. Just a slight change. I believe that you know that Python indexing is zero based. Since that you will start populating your at 5th element. I'm not sure that you want it. You can do enumerate(np.arange(start=4, stop=16, step=1)) to create zero based indexing to your list:
for i, n1 in enumerate(np.arange(start=4, stop=16, step=1)):
    ...
    f1[i] = np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2))

But len(np.arange(start=4, stop=16, step=1)) is 12 not the size you creating your f1(10). So from that point you can create 12 element list.
npuntos = 12
f1 = [0] * npuntos  # or np.zeros((5,), dtype=np.int)

Or you can do appending values as it done in MATLAB(as @nekomatic noted) if it's required.
So you need to wrap
f1[n1] = np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2))

in try / except:
try:
    f1[n1] = np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2))
except IndexError:
    f1.append(np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2)))


text:
Q: How many control pins needed for L298N H-Bridge? I have a simple robot with two DC motors. Using the L298N Dual H-Bridge, what's the minimum number of control pins I can use to give me forward, back and turn?
Here's a typical setup for the chip. It looks like I'll need 6 control lines to control 2 motors.
If I tied Ven high and relied on the "C=D Fast Motor Stop" when idle would this be bad?
http://letsmakerobots.com/files/userpics/u4107/L298N.png
http://letsmakerobots.com/files/userpics/u4107/L298N.png

A: With two pins you have full control. This allows both forward, reverse and stop. if you want to allow coasting, you will need three pins to bring Ven low. If you do not need fast stop, you could use an XOR to control the Ven from the 2 control lines. When they are equal drive t low. Then it has forward reverse and coast.
If you hold Ven High when you decide to stop moving it will full brake. If you use a simple XOR gate to do the Ven signal then you can only coast. It is decided based on what you want the motor to do. If you need the option, use three lines. from a micro this is almost no cost.

A: The minimum number of pin you need to control is only 'one' per motor, I use this configuration in most of my robot.
Connect a not gate or a transistor to provide inverted the output between C and D pin and supply a PWM signal as a input.
In this setup you'll have only one input controlling both the speed and direction of the motor and comes in very handy in robotics, you can control it by varying the duty cycle.

Direction    V/s     Duty cycle
stop    ---->     50%
forward ---->     51-100%  (forward speed increases with increase in duty
                               cycle where 100% as max forward speed)
reverse ---->      0-49%    (reverse speed increases with decrease in duty
                               cycle where 0% is max reverse speed)


text:
Q: Подсветка строк в html-файле Что означает и как убрать такую подсветку строк

A: Не совсем понял какая именно подсветка имеется в виду, но вам нужно смотреть в сторону настроек

*

*Общие: Settings → Editor → Colors&Fonts
Если речь шла о подсветке строки, то она находятся далее по списку:
→ General → Caret row

*Также можно настраивать подсветку непосредственно для ЯП или гиперразметки

*

*Settings → Editor → Colors&Fonts → HTML

*Settings → Editor → CodeStyle → HTML

A: В Intelij Idea это делается как-то так:

В PhpStorm, я думаю, аналогичное что-то должно быть.


text:
Q: mapDispachToProps is giving error while firing an event onChange function I am very new to react redux. Facing some issue on onChangeHandler inside mapDispachToProps.
class Filterfeeds extends Component {
    checkeboxChangeHandeler = (event) => {
        console.log(this.state.viewScheduledPosts)
        let tempCheckval = !this.state.viewScheduledPosts;
        this.setState({
            viewScheduledPosts: tempCheckval
        });
    }
    render() {

        return (
            <React.Fragment>

                    <TitleHeader title="Filter Feeed" style={{ paddingTop: "20px", fontSize: "18px" }} />

this.props.onLableTribeChange(e)} style={{ marginTop: "5px", display: "flex", flexWrap: "nowrap" }}>
                            <input type="radio" name="labelTribe" defaultChecked value="label" /> Label
                            <input type="radio" name="labelTribe" style={{ marginLeft: "20px" }} value="tribe" /> Tribe

                                <select className='select-box-style' name="chooseLabel" onChange={(e)=>this.props.onSelectChange(e)}>
                                    <option value='' defaultChecked>Choose Label</option>
                                    {this.props.optionsArr.map((item) => {
                                        return <option value={item} key={item}>{item}</option>
                                    })
                                    }
                                </select>

                                <input type='checkbox' onChange={this.checkeboxChangeHandeler} />View scheduled posts

                    {this.props.labelTribe} - {this.props.chooseLabel} -

            </React.Fragment>
        )
    }
}

const mapStateToProps = (state) => {
    // console.log('state in project', state.project)
    return {
        labelTribe:state.project.labelTribe,
        optionsArr:state.project.optionsArr,
        chooseLabel:state.project.chooseLabel
    }
}

const mapDispachToProps = (dispach) => {
    console.log(dispach);
    return {
        onLableTribeChange : (event) => dispach({ type: 'UPDATE_EMP_NUMBER', payload: event.target.value }),
        onSelectChange: (event)=> dispach({type:'SELECT_LABLE_CHANGE',payload:event.target.value}),
    }
}

export default connect(mapStateToProps, mapDispachToProps)(Filterfeeds);

This is myreducer.js file below
const initialState = {
    optionsArr: ["my Label", "my Tribe", "your tribe", "your label"],
    labelTribe: 'label',
    chooseLabel: '',
};

const projectreducer = (state = initialState, action) => {
    let newstate = { ...state };
    // console.log(newstate, action)
    console.log("Action type is==>", action.type)

    switch (action.type) {
        case ('UPDATE_EMP_NUMBER'):
            newstate.labelTribe = action.payload;
            break;
        case ('SELECT_LABLE_CHANGE'):
            newstate.chooseLabel = action.payload;
            break;
        default:
            return newstate;
    }
}
export default projectreducer;

While I am trying to click and change the cheakboxes values, I am getting errors.
Error: Given action "UPDATE_EMP_NUMBER", reducer "project" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.
This is the error i am getting.

A: You don't have a return value in your reducer and this is way it's returning undefined. Always use return in your reducer to change the state.
const projectreducer = (state = initialState, action) => {
  let newstate = { ...state };
  // console.log(newstate, action)
  console.log('Action type is==>', action.type);

  switch (action.type) {
    case 'UPDATE_EMP_NUMBER':
      newstate.labelTribe = action.payload;
      return newstate;
    case 'SELECT_LABLE_CHANGE':
      newstate.chooseLabel = action.payload;
      return newstate;
    default:
      return newstate;
  }
};

You can also simplify your code and return your new state value directly without reassigning the state. Try it like this:
const projectreducer = (state = initialState, action) => {
  console.log('Action type is==>', action.type);

  switch (action.type) {
    case 'UPDATE_EMP_NUMBER':
      return {
        ...state,
        labelTribe: action.payload,
      };
    case 'SELECT_LABLE_CHANGE':
      return {
        ...state,
        chooseLabel: action.payload,
      };
    default:
      return state;
  }
};


text:
Q: SQLite callback causes recursive exceptions after a successful return I am developing this Delhi 2009 app with SQLite database version 3.7.9, accessed by the Zeos components.  Started off OK - I can create a DB if none exists, create tables and insert records - the 'normal stuff'. There is a little table that contains serial params for a connection to some old equipments and the serial comms handler needs to be informed of connection parameter changes, but the Zeos components do not support events on SQLite.
I looked at the SQLite API and there is a 'Data change notification callback', so I set about making this happen.  The setup prototype is:
void *sqlite3_update_hook(
  sqlite3*,
  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  void*
);

So, in Delphi, I imported the DLL call:
function sqlite3_update_hook(pDB:pointer;pCallback:pointer;aux:pointer): pointer; stdcall;
..
function sqlite3_update_hook; external 'sqlite3.dll' name 'sqlite3_update_hook';

..and declared an empty callback for testing:
function DBcallback(aux:pointer;CBtype:integer;CBdatabaseName:PChar;CBtableName:PChar;CBrowID:Int64):pointer; stdcall;
begin

end;

..and called the setup:
sqlite3_update_hook(SQLiteHandle,@DBcallback,dmOilmon);

SQLiteHandle is the sqlite3* pointer for the database as retrieved from the driver after connection. dmOilmon is the DataModule instance so that, when working correctly, I can call some method from the callback, (yes, I know callback is in an unknown thread - I can deal with that OK, I'll just be signaling semaphores).
Good news: when I ran the app, the DBcallback was called, aparrently successfully, upon the first insert.  Bad news: some little time later, the app blew up with 'Too many exceptions', and usually a CPU window full of '??', (the occasional alternative was system death and a reboot - Vista Ultimate 64).  Breaking in the callback, aux, CBtype and CBrowID were all as expected but the debugger tooltip showed the CBdatabaseName / CBtableName PChars to be pointing at a string of Chinese characters..
I tried to trace where the callback is called from - the call chain passes through in the Zeos driver code, for some reason.  Breaking there and stepping through, I checked the stack pointer and it's the same before and after the callback.
So, I set up the 'empty' callback, the callback gets called at the expected point but with a coupe of dodgy-looking parameters, the callback returns to whence it came with the SP correct.  I seem to have done everything right, but... :((
Has anyone seen this, (or fixed it even:)?
Can you suggest a mechanism whereby an aparrently successful callback can pesuade an app to later generate recursive exceptions?
Does anyone have any suggestions for further debugging?
Rgds,
Martin

A: You have the problems with correct translation of SQLite header to Delphi and with linking:

*

*Not stdcall, but must be cdecl.

*Your function DBcallback must be a procedure. Because void(*)(...) is a pointer to C function returning void.

*Not PChar, but must be PAnsiChar. For non-Unicode Delphi's it may be not important, for Unicode Delphi's, it is only a correct translation.

*You are using compile-time dynamic linking (external 'sqlite3.dll' ...) to sqlite3.dll. But ZeosLib uses run-time dynamic linking (LoadLibrary & GetProcAddress). That may lead to "DLL hell" issue, when your EXE loads one sqlite3.dll, and ZeosLib plans to load another sqlite3.dll.


text:
Q: College algebra problem - Paying off debt and the interest rate associated There is a student who graduates with a $\$24,000$ debt.
They pay monthly compounded interest of 5% per year.
Ordinary annuities
First 5 years: $\$300$ per month
After 5 years: $\$200$ per month
Question #1: How long will it take to pay the debt?
Question #2:  How much will they pay in interest

A: So his debt looks something like this:
$d_m = ...\frac{241}{240}(\frac{241}{240}(\frac{241}{240}(24000) - 300)-300)-300...$
You can see that each month you multiply by $\frac{241}{240}$ for interest, then pay $300$.
If you start to distribute you can see the pattern:
$d_m = ...\frac{241}{240}(\frac{241}{240}^2(24000) - \frac{241}{240}300-300)-300...$
$d_m = ...\frac{241}{240}(\frac{241}{240}^3(24000) - \frac{241}{240}^2300-\frac{241}{240}300)-300)...$
So I hope you can see that the final equation would look somthing like this:
$d_m=\frac{241}{240}^m24000 - 300\frac{241}{240}^{m-1} - 300\frac{241}{240}^{m-2}...$
which is the same as
$d_m=\frac{241}{240}^m24000 - 300(\frac{241}{240}^{m-1} +\frac{241}{240}^{m-2}...)$
switched around:
$d_m=\frac{241}{240}^m24000 - 300(\frac{241}{240}^{1} +\frac{241}{240}^{2}...\frac{241}{240}^{m-1})$
Ok, lets consider the series (lets call it S) in the middle:
$S = \frac{241}{240}^{1} +\frac{241}{240}^{2}...\frac{241}{240}^{m-1}$
if we multiply by $\frac{241}{240}$ we get
$S*\frac{241}{240} = \frac{241}{240}^{2} +\frac{241}{240}^{3}...\frac{241}{240}^{m}$
subtracting $S*\frac{241}{240}$ from $S$ we get:
$S-(S*\frac{241}{240}) = \frac{241}{240}^1 - \frac{241}{240}^m$
and the right side equals $S(1-\frac{241}{240})$ because of the distributive property.So
$S=\frac{\frac{241}{240} - \frac{241}{240}^m}{ 1-\frac{241}{240}}$
$S=\frac{\frac{241}{240} - \frac{241}{240}^m}{ \frac{-1}{240}}$
$S=-240(\frac{241}{240} - \frac{241}{240}^m)$
And finally...
$S=-240\frac{241}{240} + 240\frac{241}{240}^m$
Back to our original equation:
$d_m=\frac{241}{240}^m24000 - 300(\frac{241}{240}^{1} +\frac{241}{240}^{2}...\frac{241}{240}^{m-1})$
We now know that the middle series = $-240\frac{241}{240} + 240\frac{241}{240}^m$, so we can substitute:
$d_m=\frac{241}{240}^m24000 - 300(-240\frac{241}{240} + 240\frac{241}{240}^m)$
now we can plug in $5*12$ months for m, and see if his debt is payed off:
$d_{60} = 10698.78343$
obviously not, so now we have to pay $200$ a month, which means we have to change the "$-300$" to a "$-200$" and now that the debt is $10698.78343$, change $24000$ to $10698.78343$.
Our new equation looks like this:
$d_m=\frac{241}{240}^m10698.78343 - 200(-240\frac{241}{240} + 240\frac{241}{240}^m)$
Now we just have to set $d_m$ to zero and solve:
$0=\frac{241}{240}^m10698.78343 - 200(-240\frac{241}{240} + 240\frac{241}{240}^m)$
$0=\frac{241}{240}^m10698.78343 + \frac{241*-240*-200}{240} + -200*240\frac{241}{240}^m$
$0=\frac{241}{240}^m10698.78343 + 48200 -48000\frac{241}{240}^m$
$-48200=\frac{241}{240}^m(10698.78343 -48000)$
$\frac{-48200}{10698.78343 -48000}=\frac{241}{240}^m$
$m = log_{\frac{241}{240}}\frac{-48200}{10698.78343 -48000}$
we get $m=61.648$ this means that it took 61 months to complete the payments AFTER 5 years.
So the total dollars he spent was $(5*12)*300 + 61.648*200 = 30329.60334$
So the total interest he paid was $30329.60334 - 24000 = 6329.60332$ dollars in interest
It took him 5 years + $\frac{61.648}{12} = 10.137$ years.
Whew. If you are looking for more help, this is a great kahn academy video.


text:
Q: Can two network cards on the same computer have the same IP address? If a laptop is connected both via WiFi and Ethernet to the same network, can the two network cards share the same IP address?
That way, requests for that computer can go to one IP only, and, in case any of the two connections are disconnected, no connection is interrupted.
What I'm imagining is this:
On a 255.255.255.0 subnet, if the WiFi would have IP address x.x.x.101 and the Ethernet would have IP address x.x.x.102, someone connecting to the computer via .101 would be disconnected if the WiFi is interrupted, and someone connecting to the computer via .102 would be disconnected if the Ethernet cable is unplugged. If both network cards would have the same IP, as long as at least one of them is connected to the network at a time, all connections would stay up.
I have close to no experience with networking. I imagine such a thing would likely exist, but I'm not sure how easy it would be to do it or if it would be worth it.

A: No, the same IPs on two different network interfaces on one network will cause an IP conflict and connections will sometimes work and sometimes not, depending on the capability of the devices being able to detect and avoid those conflicts.


text:
Q: GraphicsMagick montage with border with rotation I'm attempting to use GraphicsMagick's montage tool to rotate 2 images, place a border around each one individually and set the background color to blue.  However, I can only successfully rotate the image OR set a border, but not both at the same time.  Is this per design? or a bug? Or am I just calling it wrong?
Here's the command I'm running
gm montage -background blue -borderwidth 5 -bordercolor white -rotate 15 <input1>.jpg <input2>.jpg <output>.jpg

A: This is how you could do it with ImageMagick, but GraphicsMagick doesn't, indeed, seem to want to do rotation and borders.
1.png is a red square
2.png is a blue square
{ convert -background cyan -bordercolor lime  1.png -rotate 15 -border 5 miff:-; convert -background yellow -bordercolor magenta  2.png -rotate 15 -border 5 miff:-; } | montage -background blue miff:- result.jpg

Another option for ImageMagick is like this:
convert -background cyan -bordercolor lime  1.png -rotate 15 -border 5 \( -background yellow -bordercolor magenta  2.png -rotate 15 -border 5 \) +append result.png

or this:
convert -background cyan -bordercolor lime  1.png -rotate 15 -border 5 \
 \( -background yellow -bordercolor magenta  2.png -rotate 15 -border 5 \) \
 -append result.png


text:
Q: I am able to capture the TAB in a jtable, but how do I capture the SHIFT+TAB? I have a JTable that I need to change the traversal inside such that a TAB keystroke advances row by row.  (Normally, the TAB keystroke advances cell by cell.)  I was able to change the forward traversal on the TAB keystroke.  I tried the same thing for reverse traversal on SHIFT+TAB.  I can't capture the SHIFT+TAB.
    InputMap im = myTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    ActionMap am = myTable.getActionMap();

    // make shift+tab row to row instead of cell to cell
    Action shiftTabActionmyTable = new AbstractAction("SHIFT+TAB")
    {
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!inside");
            int rowView = myTable.getSelectedRow();
            int numRows = myTable.getRowCount();

            if (0 < numRows)
            {
                if ((-1 == rowView) || (0 == rowView))
                {
                    // Move to last row
                    rowView = numRows - 1;
                }
                else
                {
                    // Move to prev row
                    rowView--;
                 }

                myTable.changeSelection(rowView, 0, false, false);
                myTable.scrollRectToVisible(myTable.getCellRect(rowView, COL_ICON, true));
            }
        }
    };
    KeyStroke VK_Shift_Tab = KeyStroke.getKeyStroke("SHIFT+TAB");
    im.put(VK_Shift_Tab, shiftTabActionmyTable.getValue(Action.NAME));
    am.put(shiftTabActionmyTable.getValue(Action.NAME), shiftTabActionmyTable);

    System.out.println("!!!!!!!!!!!!!!!!!!!!!!Name " + shiftTabActionmyTable.getValue(Action.NAME));

    // Make tab row to row instead of cell to cell
    Action tabActionmyTable = new AbstractAction("TAB")
    {
        public void actionPerformed(ActionEvent e)
        {
            int rowView = myTable.getSelectedRow();
            int numRows = myTable.getRowCount();

            if (0 < numRows)
            {
                if ((-1 == rowView) || ((numRows - 1) == rowView))
                {
                    // Move to first row
                    rowView = 0;
                }
                else
                {
                    // Move to next row
                    rowView++;
                }

                myTable.changeSelection(rowView, 0, false, false);
                myTable.scrollRectToVisible(myTable.getCellRect(rowView, COL_ICON, true));
            }
         }
    };
    KeyStroke VK_Tab = KeyStroke.getKeyStroke("TAB");
    im.put(VK_Tab, tabActionmyTable.getValue(Action.NAME));
    am.put(tabActionmyTable.getValue(Action.NAME), tabActionmyTable);

How do I capture SHIFT+TAB in a JTable?

A: use
KeyStroke VK_Shift_Tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
            InputEvent.SHIFT_DOWN_MASK);

or use
KeyStroke VK_Shift_Tab = KeyStroke.getKeyStroke("shift TAB");

instead of
KeyStroke VK_Shift_Tab = KeyStroke.getKeyStroke("SHIFT+TAB");

And it should work.
The documentation of KeyStroke.getKeyStroke(String s) states

Parses a string and returns a KeyStroke. The string must have the
  following syntax:
<modifiers>* (<typedID> | <pressedReleasedID>)

modifiers := shift | control | ctrl | meta | alt | altGraph
typedID := typed <typedKey>
typedKey := string of length 1 giving Unicode character.
pressedReleasedID := (pressed | released) key
key := KeyEvent key code name, i.e. the name following "VK_".

If typed, pressed or released is not specified, pressed is assumed.
  Here are some examples:
 "INSERT" => getKeyStroke(KeyEvent.VK_INSERT, 0);
 "control DELETE" => getKeyStroke(KeyEvent.VK_DELETE, InputEvent.CTRL_MASK);
 "alt shift X" => getKeyStroke(KeyEvent.VK_X, InputEvent.ALT_MASK | InputEvent.SHIFT_MASK);
 "alt shift released X" => getKeyStroke(KeyEvent.VK_X, InputEvent.ALT_MASK | InputEvent.SHIFT_MASK, true);
 "typed a" => getKeyStroke('a');


text:
Q: Why do type annotations make Python code slower? These are results of my tests in ipython.
For int:
In [2]: %time for _  in range(1000): exec('a: int = 4')
CPU times: user 12.2 ms, sys: 12 µs, total: 12.2 ms
Wall time: 12.2 ms

In [3]: %time for _  in range(1000): exec('a = 4')
CPU times: user 9.5 ms, sys: 0 ns, total: 9.5 ms
Wall time: 9.54 ms

And for str:
In [4]: %time for _  in range(1000): exec('a: str = "hello"')
CPU times: user 13.3 ms, sys: 0 ns, total: 13.3 ms
Wall time: 13.4 ms

In [5]: %time for _  in range(1000): exec('a = "hello"')
CPU times: user 10.4 ms, sys: 0 ns, total: 10.4 ms
Wall time: 10.4 ms

And also for list:
In [6]: %time for _  in range(1000): exec('a: list = [1,2, "hello"]')
CPU times: user 19.1 ms, sys: 0 ns, total: 19.1 ms
Wall time: 21.5 ms

In [7]: %time for _  in range(1000): exec('a = [1,2, "hello"]')
CPU times: user 15.8 ms, sys: 0 ns, total: 15.8 ms
Wall time: 15.8 ms

I know theorically there should not be any difference in list or int annotations, while there is no functionality regarding to them. But I just tested these types to make sure that using type hints slows down the execution by about 25 percent. Why is this? As far as I know type hints do nothing with executing. Just spending more time to parse them and adding them to the __annotations__ dictionary makes this huge difference in execution time?

A: Your method is testing the compilation time of interpreting the raw string version of the python code into something that is executable. If you were to instead use timeit with fucntions, you wouldn't see a noticeable difference:
import timeit

def method1():
    for _ in range(1000): a: int = 4

def method2():
    for _ in range(1000): a = 4

print(timeit.timeit(method1, number=200000))
print(timeit.timeit(method2, number=200000))

2.8046581
2.8103205999999994


text:
Q: How can I apply multiple conditions to decide what values are written from an array to a target destination? In an effort to streamline my efforts for a data transfer macro, I have moved to arrays. I have limited experience with them, let alone vba. But I was able to build it, and have it write. The last hurdle I have is that I am unable to specify which values to write, as I only need them transferred if they are over or under a certain amount; i.e. array(dem2, 6) = >300 write, array(dem2, 6) = <300 don't write.
Long story short, I want to be able to write data for rows where that value is either >300 or <-300.
I spent several hours reading posts, trying various loops and conditions including do, do while, goto, elseif but none seem to work and cause errors to pop up.
Public wbFr As Workbook
Public wbTo As Workbook
Public wsFr As Worksheet
Public wsTo As Worksheet
Option Explicit
Public Sub MoveToLogBookArray()
'==================================
' Macro to put data in array      '
' Then write to separate workbook '
'==================================
Dim FromArr() As Variant
Dim Dem1 As Long, Dem2 As Long  'Multi-dimensional
Dim lastRow As Long
Dim LR As Long
Dim i As Long
Dim j As Long
Dim test As Boolean
'==================
'Workbook with data
Set wbFr = Workbooks("Book1useV2.xlsm")
'====================
'Destination workbook
Set wbTo = Workbooks("Book2V2.xlsm")
'============
'Source sheet
Set wsFr = wbFr.Worksheets("test")
'=================
'Destination sheet
Set wsTo = wbTo.Worksheets("Sheet7")

With wsFr               'Attempt at setting bounds of array
Dem1 = Range("A2:A10").Cells.Count - 1  '# of rows
Dem2 = Range("A2:A10").Cells.Count - 3  '# of columns
    ReDim FromArr(0 To Dem1, 0 To Dem2)
        For Dem1 = LBound(FromArr, 1) To UBound(FromArr, 1)
            For Dem2 = LBound(FromArr, 2) To UBound(FromArr, 2)
                FromArr(Dem1, Dem2) = wsFr.Range("A2").Offset(Dem1, Dem2)
            Next Dem2
        Next Dem1
    End With
    'Successfully builds array
    '=========================
    'Find last row of destination sheet to go to next empty row
With wsTo
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        lastRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).row
    Else
        lastRow = 1
    End If
End With
'================================================================
With wsTo
    j = lastRow + 1
      For i = LBound(FromArr) To UBound(FromArr)

        test = True

        If FromArr(Dem2, 6) <= 300 Then test = False    'Inputting .value gives error
            'do nothing                                 '"Object required"
        If FromArr(Dem2, 6) >= 300 Then test = True

        If test = False Then
            wsTo.Cells(j, 1) = FromArr(i, 0)
            wsTo.Cells(j, 2) = FromArr(i, 1)
            wsTo.Cells(j, 3) = FromArr(i, 2)
            wsTo.Cells(j, 4) = FromArr(i, 3)
            wsTo.Cells(j, 10) = FromArr(i, 4)
            wsTo.Cells(j, 13) = FromArr(i, 5)
            wsTo.Cells(j, 17) = FromArr(i, 6)
            j = j + 1
        End If              '=======================================================
        Next i              'I'm unable to write only values over 300 or under -300]
End With                    '=======================================================

Exit Sub

End Sub

As mentioned above, I want to be able to specify rows of values input into an array in one workbook, then write them to a separate workbook based on conditions of column 6.
With wsTo   'set break here
    j = lastRow + 1
      For i = LBound(FromArr) To UBound(FromArr)
        test = (FromArr(Dem2, 6) <= -300) And (FromArr(Dem2, 6) >= 300) '= True/False
                                        'tried both false/true and commented out^^^^^
                                        'and flipping <, >
            If test = True Then
                'do nothing
            End If
                    'When it writes, it writes all values or no values at all
                    '````````````````````````````````````````````````````````
            If test = False Then          'values for 4&5 include decimals
                wsTo.Cells(j, 1) = FromArr(i, 0)    'type= variant/double
                wsTo.Cells(j, 2) = FromArr(i, 1)    'type= variant/string
                wsTo.Cells(j, 3) = FromArr(i, 2)    'type= variant/string
                wsTo.Cells(j, 4) = FromArr(i, 3)    'type= variant/string
                wsTo.Cells(j, 10) = FromArr(i, 4)   'type= variant/double
                wsTo.Cells(j, 13) = FromArr(i, 5)   'type= variant/double
                wsTo.Cells(j, 17) = FromArr(i, 6)   'type= variant/double
                j = j + 1    'On 4th iteration, value is 285 but is written anyway
            End If
                            '=======================================================
        Next i              'I'm unable to write only values over 300 or under -300]
End With                    '=======================================================

Exit Sub
'Values in test Column
'517.34
'733.68
'312.26
'285.00 writes regardless
'297.00 ""
'312.00
'333.00
'250.00 ""
'500.00
End Sub

And here is my finished working project thanks to Robert and Patrick.
Public wbFr As Workbook
Public wbTo As Workbook
Public wsFr As Worksheet
Public wsTo As Worksheet
Option Explicit
Public Sub MoveToLogBookArray()
'==================================
' Macro to put data in array      '
' Then write to separate workbook '
'==================================
Dim FromArr() As Variant
Dim lastRow As Long
Dim i As Long
Dim j As Long
Dim test As Boolean
'==================
'Workbook with data
Set wbFr = Workbooks("Book1useV2.xlsm")
'====================
'Destination workbook
Set wbTo = Workbooks("Book2V2.xlsm")
'============
'Source sheet
Set wsFr = wbFr.Worksheets("test")
'=================
'Destination sheet
Set wsTo = wbTo.Worksheets("Sheet7")
'========================================================================
With wsFr               'Attempt at setting bounds of array
    FromArr = Range("adjRange")
End With

With wsTo
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        lastRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).row
    Else
        lastRow = 1
    End If
End With
'===================================================================
'Be sure to verify parameters
'Check for errors
On Error GoTo ErrHandler
With wsTo
    j = lastRow + 1
      For i = LBound(FromArr) To UBound(FromArr)

      test = False

        If FromArr(i, 6) >= 300 And FromArr(i, 6) <= -300 Then test = False
        If FromArr(i, 6) < 299.99 And FromArr(i, 6) > -299.99 Then test = True

            If test = False Then
                wsTo.Cells(j, 1) = FromArr(i, 1)
                wsTo.Cells(j, 2) = FromArr(i, 2)
                wsTo.Cells(j, 3) = FromArr(i, 3)
                wsTo.Cells(j, 4) = FromArr(i, 4)
                wsTo.Cells(j, 10) = FromArr(i, 5)
                wsTo.Cells(j, 13) = FromArr(i, 6)
                wsTo.Cells(j, 17) = FromArr(i, 7)
                j = j + 1
            End If
        Next i
End With
On Error GoTo 0
'===================================================================
Exit Sub
ErrHandler:
    MsgBox "An error has occurred! Please check values are in correct column. " & Err.Description
    Exit Sub
End Sub

A: This should work. You had a typo in the index to the FromArr(). I could not run it, so let me know if it does not work.
With wsTo
    j = lastRow + 1
    For i = LBound(FromArr, 1) To UBound(FromArr2, 1)

        If FromArr(i, 6) <= 300 Then test = False
        If FromArr(1, 6) > 300 Then test = True

        If test = False Then
            wsTo.Cells(j, 1) = FromArr(i, 0)
            wsTo.Cells(j, 2) = FromArr(i, 1)
            wsTo.Cells(j, 3) = FromArr(i, 2)
            wsTo.Cells(j, 4) = FromArr(i, 3)
            wsTo.Cells(j, 10) = FromArr(i, 4)
            wsTo.Cells(j, 13) = FromArr(i, 5)
            wsTo.Cells(j, 17) = FromArr(i, 6)
            j = j + 1
        End If
    Next i
End With


text:
Q: How to send some objects of case class to another computer by ip and port easily? I want to exchange some objects of case class to another computer, by ip and port. There are several possible approaches (e.g. Plain socket server, http server, RMI...)
But I want to know is there any simple solution can do this job, in Scala?

A: There is a nice project named scala/pickling which make  serialization/deserialization very easy.
From the pickling site:
"Scala Pickling is an automatic serialization framework made for Scala. It's fast, boilerplate-free, and allows users to easily swap in/out different serialization formats (such as binary, or JSON), or even to provide your own custom serialization format."
It support serialization/deserialization from both Json and binary formats, so it makes it very easy to transfer to another machine, either using Web-service, or using binary communication.


text:
Q: How to add li to ul using an str? I am making a Overwatch Lootbox simulator and I am just adding "Item Log" to it. I have made it show and not show this area (ul) where the items will go once you got them. This may sound confusing and probably is but all I want to do is add a bullet point (li) to a (ul) and the content inside the bullet point will be what items you got and that is already defined as str (line 92 in the JS).
JAVASCRIPT:
var crate
var openSound = new Audio('open-box.ogg');
var results = [];
var isRunning = false;

$.fn.extend({
    animateCss: function (animationName) {
        var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
        $(this).addClass('animated ' + animationName).one(animationEnd, function() {
            $(this).removeClass('animated ' + animationName);
        });
    }
});

function itemLog(btn) {
  var hide = document.getElementById("itemlog")
  if (btn.id.match("plus")) {
      btn.id = "minus";
      hide.style.display = "block";
  }
  else {
    btn.id = "plus";
    hide.style.display = "none";
  }
}

function openBox(){

  if(isRunning == false){
    //Reset Crate
    results = [];
    setTimeout(delay,1750);
    setTimeout(hideBox,750);
    setTimeout(deleteCards,1050);
    openSound.play();
    $('#box').animateCss('bounceOutUp');
    $('#item0').animateCss('bounceOutUp');
    $('#item1').animateCss('bounceOutUp');
    $('#item2').animateCss('bounceOutUp');
    $('#item3').animateCss('bounceOutUp');

    isRunning = true;
  }
}

function deleteCards(){
  $( "#item0" ).remove();
  $( "#item1" ).remove();
  $( "#item2" ).remove();
  $( "#item3" ).remove();
}

function hideBox(){
  $( "#box" ).remove();
}

function delay(){
  setTimeout(setBox,250);

}

function setBox(){

  for(i = 0; i < 3; i++){
    //Randomize Loot
    crate = chance.weighted(loot, weights);
    results.push(crate);
    console.log(crate);
  }

  cratespec = chance.weighted(specloot, specweights);
  results.push(cratespec);

  endresults = chance.shuffle(results);
  displayBox();

}

function displayBox(){
  //Add to list
  for(i = 0; i < endresults.length; i++){
    var ul = document.getElementById("crate");
    var li = document.createElement("li");
    var span = document.createElement("span");
    span.appendChild(document.createTextNode(endresults[i]));
    li.setAttribute("id", "item" + i);
    ul.appendChild(li);
    li.appendChild(span);

    //Check Quality and Strip
    var str = $("#item" + i).text();
    console.log(str);
     if(endresults[i].indexOf("Normal") !=-1){
      $("#item" + i).addClass("normal animated bounceInDown");
      $("#item" + i ).find('span').text(str.substring(7));
    }
    if (endresults[i].indexOf("Rare") !=-1){
      $("#item" + i).addClass("rare animated bounceInDown");
      $("#item" + i).find('span').text(str.substring(5));
    }
    if(endresults[i].indexOf("Epic") !=-1){
      $("#item" + i).addClass("epic animated bounceInDown");
      $("#item" + i).find('span').text(str.substring(5));
    }
    if(endresults[i].indexOf("Lgnd") !=-1){
      $("#item" + i).addClass("legendary animated bounceInDown");
      $("#item" + i).find('span').text(str.substring(5));
    }

    //Check Hero
    //Generic
    if(endresults[i].indexOf("Spray") || endresults[i].indexOf("Coins") !=-1){
      $("#item" + i).addClass("generic");
    }
    //orisa
    if(endresults[i].indexOf("Orisa") !=-1){
      $("#item" + i).addClass("orisa");
    }

    //sombra
    if(endresults[i].indexOf("Sombra") !=-1){
      $("#item" + i).addClass("sombra");
    }
    //ana
    if(endresults[i].indexOf("Ana") !=-1){
      $("#item" + i).addClass("ana");
    }
    //bastion
    if(endresults[i].indexOf("Bastion") !=-1){
      $("#item" + i).addClass("bastion");
    }
    //dva
    if(endresults[i].indexOf("D.Va") !=-1){
      $("#item" + i).addClass("dva");
    }
    //genji
    if(endresults[i].indexOf("Genji") !=-1){
      $("#item" + i).addClass("genji");
    }
    //hanzo
    if(endresults[i].indexOf("Hanzo") !=-1){
      $("#item" + i).addClass("hanzo");
    }
    //junkrat
    if(endresults[i].indexOf("Junkrat") !=-1){
      $("#item" + i).addClass("junkrat");
    }
    //lucio
    if(endresults[i].indexOf("Lucio") !=-1){
      $("#item" + i).addClass("lucio");
    }
    //McCree
    if(endresults[i].indexOf("McCree") !=-1){
      $("#item" + i).addClass("mccree");
    }
    //Reaper
    if(endresults[i].indexOf("Reaper") !=-1){
      $("#item" + i).addClass("reaper");
    }
    //Mei
    if(endresults[i].indexOf("Mei") !=-1){
      $("#item" + i).addClass("mei");
    }
    //Mercy
    if(endresults[i].indexOf("Mercy") !=-1){
      $("#item" + i).addClass("mercy");
    }
    //Pharah
    if(endresults[i].indexOf("Pharah") !=-1){
      $("#item" + i).addClass("pharah");
    }
    //Reinhardt
    if(endresults[i].indexOf("Reinhardt") !=-1){
      $("#item" + i).addClass("reinhardt");
    }
    //Roadhog
    if(endresults[i].indexOf("Roadhog") !=-1){
      $("#item" + i).addClass("roadhog");
    }
    //Solider76
    if(endresults[i].indexOf("Soldier: 76") !=-1){
      $("#item" + i).addClass("soldier");
    }
    //Symmetra
    if(endresults[i].indexOf("Symmetra") !=-1){
      $("#item" + i).addClass("symmetra");
    }
    //Torbjorn
    if(endresults[i].indexOf("Torbjorn") !=-1){
      $("#item" + i).addClass("torbjorn");
    }
    //Tracer
    if(endresults[i].indexOf("Tracer") !=-1){
      $("#item" + i).addClass("tracer");
    }
    //Widowmaker
    if(endresults[i].indexOf("Widowmaker") !=-1){
      $("#item" + i).addClass("widowmaker");
    }
    //Winston
    if(endresults[i].indexOf("Winston") !=-1){
      $("#item" + i).addClass("winston");
    }
    //Zarya
    if(endresults[i].indexOf("Zarya") !=-1){
      $("#item" + i).addClass("zarya");
    }
    //Zenyatta
    if(endresults[i].indexOf("Zenyatta") !=-1){
      $("#item" + i).addClass("zenyatta");
    }

  }
  isRunning = false;
}

function shakeBox(){
  $("#box").addClass("shakebox");
  setTimeout(removeShake,820);
}

function removeShake(){
  $("#box").removeClass("shakebox");
  setTimeout(shakeBox,1820);
}

HTML:
<!DOCTYPE html>

<title>Home |OWLBS</title>
<link rel="icon" type="image/png" href="favicon.png">
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="css/animate.css" rel="stylesheet" type="text/css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type=text/css>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300,400,500,600,700' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Raleway:400,600,700' rel='stylesheet' type='text/css'>

            OWLBS
            This is not made by me, I edited another file!

About

Changelog

        OPEN LOOT BOX
        Item Log

 Only for overwatch fans!

Hope that is enough.


text:
Q: How can I store clicked QPushbuttons I created a bunch of Qpushbuttons with QT designer, after click more than one button I Want to take these buttons and transfer other function to change these buttons' lets say the color properties. Is it possible to store these clicked buttons and use them? If possible, how?

A: You could add pointers to the clicked buttons to a QList, QVector or some other container type, and pass that to the code that needs to change them.
Without more details about your actual code, it's hard to be more specific than this, sorry.


text:
Q: MySQL: "check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 14" Here is my SQL code (that I've been testing with SQL Fiddle) for an assignment. The error I keep getting says there's a problem with ) in line 14 ("REFERENCES Department(Dnumber)"), but it says that even when there isn't a parentheses there. What's wrong with this code's syntax?
The error message says:

"You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near ')' at line 14"

#Create the table definitions

CREATE TABLE Employee(
Fname       VARCHAR(20) NOT NULL,
Minit       VARCHAR(1),
Lname       VARCHAR(20) NOT NULL,
Ssn         CHAR(9)     PRIMARY KEY,
Bdate       DATE,
Address     VARCHAR(30),
Sex         CHAR(1),
Salary      NUMERIC(10,2),
Super_ssn   CHAR(9)     REFERENCES Department(Mgr_ssn),
Dno         INTEGER     REFERENCES Department(Dnumber),
);

CREATE TABLE Department(
Dname       VARCHAR(15) NOT NULL,
Dnumber     INTEGER     PRIMARY KEY,
Mgr_ssn     CHAR(9),
Mgr_start_date  DATE,
);

CREATE TABLE Dept_Locations(
Dnumber     INTEGER     REFERENCES Department,
Dlocation   VARCHAR(20),

PRIMARY KEY (Dnumber, Dlocation)
);

CREATE TABLE Project(
Pname       VARCHAR(20) NOT NULL,
Pnumber     INTEGER     PRIMARY KEY,
Plocation   VARCHAR(20),
Dnum        INTEGER     REFERENCES Department,
);

CREATE TABLE Works_On(
Essn    CHAR(9)     REFERENCES Employee(Ssn),
Pno     INTEGER     REFERENCES Project(Pnumber),
Hours   NUMERIC(2,1),

PRIMARY KEY(Essn, Pno)
);

CREATE TABLE Dependent(
Essn        CHAR(9)     REFERENCES Employee(Ssn),
Dependent_name  VARCHAR(20) NOT NULL,
Sex     CHAR(1),
Bdate       DATE,
Relationship    VARCHAR(20),

PRIMARY KEY(Essn, Dependent_name)
);

#Insert records into the tables

INSERT INTO Employee
Values
('John',    'B','Smith',  '123456789','1965-01-09','731 Fondren, Houston,     TX','M',30000,'333445555',5),
('Franklin','T','Wong',   '333445555','1955-12-08','638 Voss, Houston, TX',       'M',40000,'888665555',5),
('Alicia',  'J','Zelaya', '999887777','1968-01-19','3321 Castle, Spring,     TX', 'F',25000,'987654321',4),
('Jennifer','S','Wallace','987654321','1941-06-20','291 Berry, Bellaire, TX', 'F',43000,'888665555',4),
('Ramesh',  'K','Narayan','666884444','1962-09-15','975 Fire Oak, Humble, TX','M',38000,'333445555',5),
('Joyce',   'A','English','453453453','1972-07-31','5631 Rice, Houston, TX',  'F',25000,'333445555',5),
('Ahmad',   'V','Jabbar', '987987987','1969-03-29','980 Dallas, Houston, TX', 'M',25000,'987654321',4),
('James',   'E','Borg',   '888665555','1937-11-10','450 Stone, Houston, TX',  'M',55000, NULL,      1);

INSERT INTO Department
Values
('Research',      5,'333445555','1988-05-22'),
('Administration',4,'987654321', '1995,01,01'),
('Headquarters',  1,'888665555','1981-06-19');

INSERT INTO Dept_Locations
Values
(1,'Houston'),
(4,'Stafford'),
(5,'Bellaire'),
(5,'Sugarland'),
(5,'Houston');

INSERT INTO Project
Values
('ProductX',        1,'Bellaire', 5),
('ProductY',        2,'Sugarland',5),
('ProductZ',        3,'Houston',  5),
('Computerization',10,'Stafford', 4),
('Reorganization', 20,'Houston',  1),
('Newbenefits',    30,'Stafford', 4);

INSERT INTO Works_On
Values
('123456789', 1,32.5),
('123456789', 2, 7.5),
('666884444', 3,40.0),
('453453453', 1,20.0),
('453453453', 2,20.0),
('333445555', 2,10.0),
('333445555', 3,10.0),
('333445555',10,10.0),
('333445555',20,10.0),
('999887777',30,30.0),
('999887777',10,10.0),
('987987987',10,35.0),
('987987987',30, 5.0),
('987654321',30,20.0),
('987654321',20,15.0),
('888665555',20,NULL);

INSERT INTO Dependent
Values
('333445555','Alice',    'F','1986-04-05','Daughter'),
('333445555','Theodore', 'M','1983-10-25','Son'),
('333445555','Joy',      'F','1958-05-03','Spouse'),
('987654321','Abner',    'M','1942-02-28','Spouse'),
('123456789','Michael',   'M','1988-01-04','Son'),
('123456789','Alice',    'F','1988-12-30','Daughter'),
('123456789','Elizabeth','F','1967-05-05','Spouse');

#Show values in all tables

SELECT *
FROM Employee;

SELECT *
FROM Department;

SELECT *
FROM Dept_Locations;

SELECT *
FROM Project;

SELECT *
FROM Works_On;

SELECT *
FROM Dependent;

#Implement queries from Exercise 8.16
#a)
SELECT  E.Fname, E.Lname
FROM    Employee E, Works_On W, Project P
WHERE   E.Ssn = W.Essn  and
        P.Pnum = W.Pno  and
        E.Dno = 5       and
        P.Pname = 'ProjectX' and
        W.Hours > 10.0;

#b)
SELECT  E.Fname, E.Lname
FROM    Employee E, Dependent D
WHERE   E.Ssn = D.Essn  and
        E.Fname = D.Dependent_name;

#c)
SELECT  Fname, Lname
FROM    Employee
WHERE   Super_ssn = (SELECT  Ssn
             FROM    Employee
             WHERE   Fname = 'Franklin' and
                     Lname = 'Wong');

#d)
SELECT   SUM(W.Hours)
FROM     Project P, Works_On W
WHERE    P.Pnumber = W.Pno
GROUP BY P.Pname;

#e)
SELECT  E.Fname, E.Lname
FROM    Employee E
WHERE   NOT EXISTS
    (SELECT  P.Pnumber
     FROM    Project P
     WHERE   P.Pnumber NOT IN
             (SELECT  W.Pno
              FROM    Works_On W
              WHERE   W.Essn = E.Ssn));

#f)
SELECT  E.Fname, E.Lname
FROM    Employee E
WHERE   EXISTS
        (E.Essn

         MINUS

         SELECT  [Distinct] W.Essn
         FROM    Works_On W
        );

#g)
SELECT   AVG(E.Salary)
FROM     Employee E, Department D
WHERE    E.Dno = D.Dnumber
GROUP BY D.Dname;

#h)
SELECT   AVG(Salary)
FROM     Employee
WHERE    Sex = 'F'
GROUP BY Sex;

#i)
SELECT  E.Fname, E.Lname, E.Address
FROM    Employee E
WHERE   EXISTS
        (SELECT  P.Pnumber
         FROM    Project P, Works On W
         WHERE   P.Pnumber = W.Pno     and
                 W.Essn = E.Ssn        and
                 Plocation = 'Houston' and
                 NOT EXISTS
                 (SELECT  Dl.Dnumber
                  FROM    Dept_Locations Dl
                  WHERE   Dl.Dlocation = 'Houston' and
                          E.Dno = Dl.Dnumber));

#j)
SELECT  E.Lname
FROM    Employee E, Department De
WHERE   De.Mgr_ssn = E.Ssn and
        NOT EXISTS
        (SELECT  Dp.Essn
         FROM    Dependent Dp
         WHERE   Dp.Essn = E.Ssn);

#Drop all tables

DROP TABLE Dependent      RESTRICT;
DROP TABLE Works_On       RESTRICT;
DROP TABLE Project        RESTRICT;
DROP TABLE Dept_Locations RESTRICT;
DROP TABLE Department     RESTRICT;
DROP TABLE Employee       CASCADE;

A: You have a comma after Dno   INTEGER     REFERENCES Department(Dnumber), remove that comma so it looks like this
CREATE TABLE Employee(
Fname       VARCHAR(20) NOT NULL,
Minit       VARCHAR(1),
Lname       VARCHAR(20) NOT NULL,
Ssn         CHAR(9)     PRIMARY KEY,
Bdate       DATE,
Address     VARCHAR(30),
Sex         CHAR(1),
Salary      NUMERIC(10,2),
Super_ssn   CHAR(9)     REFERENCES Department(Mgr_ssn),
Dno         INTEGER     REFERENCES Department(Dnumber)
);

In fact, do that for all the tables you are creating.
CREATE TABLE Department(
Dname       VARCHAR(15) NOT NULL,
Dnumber     INTEGER     PRIMARY KEY,
Mgr_ssn     CHAR(9),
Mgr_start_date  DATE
);

CREATE TABLE Project(
Pname       VARCHAR(20) NOT NULL,
Pnumber     INTEGER     PRIMARY KEY,
Plocation   VARCHAR(20),
Dnum        INTEGER     REFERENCES Department
);


text:
Q: how to open the kendo angular datepicker popup using javascript i cant find a way to open the kendo angular(2+) datepicker from JS.
i want to have my own datepicker icon , hiding the default controller ( input field and icon using visibility: hidden; )
and to open the popup when my icon is clicked.
in the api doc i can find only blur and focus Methods
https://www.telerik.com/kendo-angular-ui/components/dateinputs/api/DatePickerComponent/#toc-blur
thanks

A: You can use following code to toggle the visibility of the date-picker (use this code in your icon click event);
datepicker.toggle()

example;
 <button (click)="datepicker1.toggle()">toggle date picker</button>
 <kendo-datepicker #datepicker1></kendo-datepicker>


text:
Q: How to format and serve an apple-app-site-association file correctly I'm trying to set up an apple-app-site-association file for several apps that share a common set of paths. There are two sets of documentation from Apple that conflict. Firstly, this doc says that each app should have its own section and then there is a paths element that contains mappings:
{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appID": "9JA89QQLNQ.com.apple.wwdc",
                "paths": [ "/wwdc/news/", "/videos/wwdc/2015/*"]
            },
            {
                "appID": "ABCD1234.com.apple.wwdc",
                "paths": [ "*" ]
            }
        ]
    }
}

Then there is this doc for XCode which shows a quite different format:
{
  "applinks": {
      "details": [
           {
             "appIDs": [ "ABCDE12345.com.example.app", "ABCDE12345.com.example.app2" ],
             "components": [
               {
                  "#": "no_universal_links",
                  "exclude": true,
                  "comment": "Matches any URL whose fragment equals no_universal_links and instructs the system not to open it as a universal link"
               },
               {
                  "/": "/buy/*",
                  "comment": "Matches any URL whose path starts with /buy/"
               },
               {
                  "/": "/help/website/*",
                  "exclude": true,
                  "comment": "Matches any URL whose path starts with /help/website/ and instructs the system not to open it as a universal link"
               },
               {
                  "/": "/help/*",
                  "?": { "articleNumber": "????" },
                  "comment": "Matches any URL whose path starts with /help/ and which has a query item with name 'articleNumber' and a value of exactly 4 characters"
               }
             ]
           }
       ]
   },
   "webcredentials": {
      "apps": [ "ABCDE12345.com.example.app" ]
   },

    "appclips": {
        "apps": ["ABCED12345.com.example.MyApp.Clip"]
    }
}

Neither document has any date or version information, so I can't tell which is more recent or correct.
The appIDs themselves are also confusing because there are apparently multiple sources of these identifiers, but not all of them will work, though I can't tell if that's my problem now.
I'm serving my document from /.well-known/apple-app-site-association, but I find a validator gives odd validation failures such as not being able to get the file (though fetching it with curl or a browser works fine), and a complaint that it can't be verified with openssl, which makes no sense because it contains nothing that's even vaguely related to certificates or signatures. Why does the document need to be delivered with a application/pkcs7-mime MIME type when it's neither MIME nor PKCS7 format?
Looking at Apple's own AASA, I see that it uses both of these formats! It also fails validation in all of the validators I tried, including Apple's own! This is very confusing.
How exactly should this document be formatted?


text:
Q: Drop down menu with ASP.NET MVC 4 and EF I'm trying to create drop down menu in MVC4 (Entity Framework, code first). My aim is to prepare value in classes so I don't need additional programing on control page.
public class Prefix
{
    [Key]
    public int PrefixID { get; set; }

    [StringLength(20)]
    public string PrefixName { get; set; }
}
public class People
{
    [Key]
    public int PersonID { get; set; }

    [StringLength(20)]
    public string FirstName { get; set; }

    [StringLength(20)]
    public string LastName { get; set; }

    [ForeignKey("PrefixID")]
    public Prefix Prefix { get; set; }

    [Required]
    public int PrefixID { get; set; }

    public string FullName // this isn't working
    {
        get
        {
            return Prefix.PrefixName +" " + FirstName + " " + LastName;
        }
    }
}

public class PersonSalary
{
    [Key]
    public int SalaryId { get; set; }
    //...

    [ForeignKey("EmployeeID")]
    public Person HEmployee {get;set;}

    public int EmployeeID { get; set; }
}

Code in SalaryController:
ViewBag.EmployeeID = new SelectList(db.People, "PersonID", "FullName", personsalary.EmployeeID);

On SalaryController I can get drop down menu with values "Name Surname" but I want "Prefix.Name Name Surname". For example "Mr John Doe", etc. Current code returns error:

Object reference not set to instance of object.

How to do that?

A: Make sure you have eagerly initialized the Prefix property of your model:
ViewBag.EmployeeID = new SelectList(
    db.People.Include(p => p.Prefix),
    "PersonID",
    "FullName",
    personsalary.EmployeeID
);

A: In People class, mark the property Prefix as virtual. If you do so, the value of corresponding prefix will be loaded when you try accessing this value.
Answer suggested by Darin will also work. This is an alternative approach.


text:
Q: Characterization of ${\rm PSU}(4,2)$ by its order $|{\rm PSU}(4,2)|$ and the number $n_5({\rm PSU}(4,2))$ of its Sylow $5$-subgroups? We know that $|{\rm PSU}(4,2)|=25920=2^6\cdot3^4\cdot5$, and the number $n_5({\rm PSU}(4,2))$ of Sylow $5$-subgroups of ${\rm PSU}(4,2)$ is $1296=2^4\cdot3^4$.
In Theorem 3.2 of the paper Two new characterizations for sporadic simple groups, Khosravi and Khosravi prove that every sporadic simple group $S$ is uniquely determined by its order $|S|$ and the number of its Sylow $p$-subgroups $n_p(S)$, where $p$ is the largest element of $$\pi(S)=\{p\mid p~{\rm is~a~divisor~of}~|S|\}.$$ I just want to prove the same result for ${\rm PSU}(4,2)$. But I cannot follow the proof of Theorem 3.2. In particular, in the first paragraph of the proof of Theorem 3.2 it says that "... and so $|G/K|$ is a divisor of $n_p(G)$". I cannot catch the idea of this sentence. May someone give me a more detailed explanation?

A: Recalling the definition that $n_p(G)=|N_G(P)|$ where $P\in\operatorname{Syl}_p(G)$ we have $$N_G(P)/N_G(K)\cong G/K\implies \left|N_G(P)/N_G(K)\right|=|G/K|$$ and the result follows as $\left|N_G(P)/N_G(K)\right|$ divides $|N_G(P)|$.


text:
Q: Obtaining a measurement very indirectly While answering a question I came to reflect on the fact that in science experimental setups measure things indirectly.
Example: the setup of the Pound-Rebka experiment.
The amount of absorption was assessed by obtaining a measure of the flux of gamma rays that were not absorbed. The gamma rays were registered using a scintillation counter.
As an historical contrast:
When Rutherford set out to measure deflections of alpha particles, the setup involved direct visual observation of scintillation. In order to see the scintilations an assistent would spend something like 20 minutes in total darkness, so that his eyes would be at maximum sensitivity to light. That is how a measure of number of alpha particles hitting the scintillation screen was obtained.
Example: The Gravity probe B experiment.
I saw the animations of the how the spheres had been moving around. They were all over the place. There were classical mechanics effect going on, on a scale that swamped the sought after signals by many orders of magnitude. To subtract those classical effects they had to be modeled to a new level of sophistication. That work delayed public announcement of the results by something like a year. Getting out the goods took a huge data-mining effort.

Experiments probe deeper and deeper, the setups become more and more elaborate. Often supporting measurements are made for the purpose of subtracting other effects signal from the sought after data.
Out of sheer curiosity: can you think of other examples where it took even more steps, extensive data-mining, etc. to produce the goods?

A: I'm not sure this is the exact type of answer you were looking for, but without getting into specific experiments, most experiments in many fields must be done indirectly. One of these such fields is Astrophysics, although I would say most of the things here are more of measurements than an experiment in a lab. Even so, the measurements are often made indirectly, especially with topics such as dark energy.
Another such field would be quantum mechanics, where many behaviors were predicted mathematically much before they could be experimentally proven. This is because of the difficulty in conducting experiments about things that are on such a small scale.
This list could go on and on, but the point is, planning an experiment is all about what data can easily and accurately be obtained and what relations can be made with that data to get to a desired point.
Also experiments must obviously conform to what is possible; with your example of the gamma rays, the gamma rays on one side of a material can be measured as well as the gamma rays on the other side of the material, but there's no real way to measure the absorption of the gamma rays into the materials. Likewise, people can't go up into space with a dark energy measurement device, or at least not at this time. But the presence of dark energy can be theoretically shown by other measurements.
To add to my answer, the Millikan oil drop experiment is one famous example of an experiment that indirectly measures something, in this case the specific charge of an electron. Without indirect measurement, it would be pretty much impossible to measure the charge of a single electron.


text:
Q: ViewController.Type does not have a member names 'answerOne' - SWIFT I am making a swift app. It is a trivia app for fun and I have run into an issue that I havent seen before. (I am new to swift and ios development errors)
import UIKit

class TriviaViewController: UIViewController {

@IBOutlet var myQuestionCounter: UILabel!
@IBOutlet var myQuestion: UILabel!
@IBOutlet var firstAnswer: UIButton!
@IBOutlet var secondAnswer: UIButton!
@IBOutlet var thirdAnswer: UIButton!
@IBOutlet var fourthAnswer: UIButton!

var timer = NSTimer() //TO-DO
var count = 0
var questionCounter = 0

var firstQuestion = "What was the first planet to be discovered using the telescope, in 1781?"
var answerOne = "Mercury"
var answerTwo = "Uranus"
var answerThree = "Venus"
var answerFour = "Jupiter"

var firstCorrectAnswer = 2

//This next line gives the ERROR
let questionOneArray = [answerOne, answerTwo, answerThree, answerFour, firstCorrectAnswer]

}

When I declare the "questionOneArray", it says "TriviaViewController does not have a member named 'answerOne'"
Please explain to me what this error is and how I can fix it.
Thank you.

A: Solution 1 : Your code is not inside a method, you have to wrap it inside the method. Check this stackoverflow answer
Solution 2 : Keep your questions and answers inside struct and access them, if you don't want to wrap it inside a function.
struct firstQuestion {
    static var question = "What was the first planet to be discovered using the telescope, in 1781?"
    static var answerOne = "Mercury"
    static var answerTwo = "Uranus"
    static var answerThree = "Venus"
    static var answerFour = "Jupiter"
    static var correctAnswer = "Correct Answer"
}

var questionOneArray = [firstQuestion.answerOne, firstQuestion.answerTwo, firstQuestion.answerThree, firstQuestion.answerFour, firstQuestion.correctAnswer]


text:
Q: Why does C# 4.5 async/await WebClient require lambda methodology when using StreamReader ReadToEndAsync? Given:
    public async Task<string> SendRequest(this string url)
    {
        var wc = new WebClient();
        wc.DownloadDataCompleted += (s, e) =>
        {
            var buffer = e.Result;
            using (var sr = new StreamReader(new MemoryStream(buffer)))
            {
                var result = await sr.ReadToEndAsync();
            };
        };
        wc.DownloadDataAsync(new Uri(url));
    }
}

The statement:
var result = await sr.ReadToEndAsync();

Shows an error in the designer as follows: "The await operator can only be used within an async lambda expression"

I don't understand why this message is happening, when I look at all ReadToEndAsync examples they look exactly like this code.
Please advise...

A: When using a WebClient with the TPL, you should be using the methods with Task in the name, to get Task returning methods rather than using the event based mode (which you then would need to transform into tasks):
public static async Task<string> SendRequest(this string url)
{
    using (var wc = new WebClient())
    {
        var bytes = await wc.DownloadDataTaskAsync(url);
        using (var reader = new StreamReader(new MemoryStream(bytes)))
            return await reader.ReadToEndAsync();
    }
}

A:     public static Task<string> SendRequest(this string url)
    {
        return (new WebClient()).DownloadStringTaskAsync(new Uri(url));
    }


text:
Q: When embedding CPython in Java, why does this hang? I'm embedding CPython into a JVM using Jepp, but when I run
import numpy; numpy.finfo(float)

the process hangs.  gdb says something's blocking a semaphore/lock acquisition, and the stack trace suggests something floating point-related:
$ LD_PRELOAD=/usr/lib/libpython2.6.so gdb --args java -jar jepp.jar -i /tmp/go.py
GNU gdb (GDB) 7.1-ubuntu
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /usr/bin/java...(no debugging symbols found)...done.
(gdb) r
Starting program: /usr/bin/java -jar jepp.jar -i /tmp/go.py
[Thread debugging using libthread_db enabled]
process 20736 is executing new program: /usr/lib/jvm/java-6-sun-1.6.0.26/jre/bin/java
[Thread debugging using libthread_db enabled]
[New Thread 0x7ffff58fd700 (LWP 20739)]
[New Thread 0x7ffff16ca700 (LWP 20740)]
[New Thread 0x7ffff15c9700 (LWP 20741)]
[New Thread 0x7ffff14c8700 (LWP 20742)]
[New Thread 0x7ffff13c7700 (LWP 20743)]
[New Thread 0x7ffff0bf5700 (LWP 20744)]
[New Thread 0x7ffff0af4700 (LWP 20745)]
[New Thread 0x7ffff09f3700 (LWP 20746)]
[New Thread 0x7ffff08b3700 (LWP 20747)]
[New Thread 0x7ffff07b2700 (LWP 20748)]
[New Thread 0x7ffff06b1700 (LWP 20749)]
[New Thread 0x7ffff05b0700 (LWP 20750)]
[New Thread 0x7ffff04af700 (LWP 20751)]
>>> import numpy; numpy.finfo(float)
^C
Program received signal SIGINT, Interrupt.
0x00007ffff771703d in pthread_join () from /lib/libpthread.so.0
(gdb) bt
#0  0x00007ffff771703d in pthread_join () from /lib/libpthread.so.0
#1  0x000000004000591c in ContinueInNewThread ()
#2  0x0000000040001ef4 in main ()
(gdb) i threads
  14 Thread 0x7ffff04af700 (LWP 20751)  0x00007ffff771abc9 in pthread_cond_timedwait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  13 Thread 0x7ffff05b0700 (LWP 20750)  0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  12 Thread 0x7ffff06b1700 (LWP 20749)  0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  11 Thread 0x7ffff07b2700 (LWP 20748)  0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  10 Thread 0x7ffff08b3700 (LWP 20747)  0x00007ffff771cb50 in sem_wait ()
   from /lib/libpthread.so.0
  9 Thread 0x7ffff09f3700 (LWP 20746)  0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  8 Thread 0x7ffff0af4700 (LWP 20745)  0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  7 Thread 0x7ffff0bf5700 (LWP 20744)  0x00007ffff771abc9 in pthread_cond_timedwait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  6 Thread 0x7ffff13c7700 (LWP 20743)  0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  5 Thread 0x7ffff14c8700 (LWP 20742)  0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  4 Thread 0x7ffff15c9700 (LWP 20741)  0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  3 Thread 0x7ffff16ca700 (LWP 20740)  0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
  2 Thread 0x7ffff58fd700 (LWP 20739)  0x00007ffff771cb50 in sem_wait ()
   from /lib/libpthread.so.0
* 1 Thread 0x7ffff7ed8700 (LWP 20736)  0x00007ffff771703d in pthread_join ()
   from /lib/libpthread.so.0
(gdb) thread 2
[Switching to thread 2 (Thread 0x7ffff58fd700 (LWP 20739))]#0  0x00007ffff771cb50 in sem_wait () from /lib/libpthread.so.0
(gdb) bt
#0  0x00007ffff771cb50 in sem_wait () from /lib/libpthread.so.0
#1  0x00007ffff7a4db28 in PyThread_acquire_lock ()
   from /usr/lib/libpython2.6.so
#2  0x00007ffff7a1cbb4 in PyEval_RestoreThread () from /usr/lib/libpython2.6.so
#3  0x00007ffff7a41008 in PyGILState_Ensure () from /usr/lib/libpython2.6.so
#4  0x00007fffeb1e1ff6 in _error_handler (method=-334489136, errobj=0x80,
    errtype=0x0, retstatus=-1, first=0x0)
    at numpy/core/src/umath/ufunc_object.c:95
#5  0x00007fffeb1e2379 in PyUFunc_handlefperr (errmask=521,
    errobj=0x7fffec502950, retstatus=4, first=0x7ffff58fa5fc)
    at numpy/core/src/umath/ufunc_object.c:189
#6  0x00007fffeb1e7cd1 in PyUFunc_GenericFunction (self=<value optimized out>,
    args=<value optimized out>, kwds=<value optimized out>, op=0x7ffff58faaa0)
    at numpy/core/src/umath/ufunc_object.c:2734
#7  0x00007fffeb1e7ff0 in ufunc_generic_call (self=0x7fffec1df790,
    args=<value optimized out>, kwds=<value optimized out>)
    at numpy/core/src/umath/ufunc_object.c:4180
#8  0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#9  0x00007ffff797ed9f in _PyObject_CallFunction_SizeT ()
   from /usr/lib/libpython2.6.so
#10 0x00007ffff797c9aa in ?? () from /usr/lib/libpython2.6.so
#11 0x00007ffff797d698 in PyNumber_Multiply () from /usr/lib/libpython2.6.so
#12 0x00007ffff7a1f2bc in PyEval_EvalFrameEx () from /usr/lib/libpython2.6.so
#13 0x00007ffff7a22928 in PyEval_EvalFrameEx () from /usr/lib/libpython2.6.so
#14 0x00007ffff7a23d60 in PyEval_EvalCodeEx () from /usr/lib/libpython2.6.so
#15 0x00007ffff79a9d60 in ?? () from /usr/lib/libpython2.6.so
#16 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#17 0x00007ffff798dcef in ?? () from /usr/lib/libpython2.6.so
#18 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#19 0x00007ffff79e2cd0 in ?? () from /usr/lib/libpython2.6.so
#20 0x00007ffff79d8f98 in ?? () from /usr/lib/libpython2.6.so
#21 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#22 0x00007ffff7a21771 in PyEval_EvalFrameEx () from /usr/lib/libpython2.6.so
#23 0x00007ffff7a23d60 in PyEval_EvalCodeEx () from /usr/lib/libpython2.6.so
#24 0x00007ffff7a220ab in PyEval_EvalFrameEx () from /usr/lib/libpython2.6.so
#25 0x00007ffff7a23d60 in PyEval_EvalCodeEx () from /usr/lib/libpython2.6.so
#26 0x00007ffff79a9d60 in ?? () from /usr/lib/libpython2.6.so
#27 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#28 0x00007ffff79d928d in ?? () from /usr/lib/libpython2.6.so
#29 0x00007ffff79d8f53 in ?? () from /usr/lib/libpython2.6.so
#30 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#31 0x00007ffff7a21771 in PyEval_EvalFrameEx () from /usr/lib/libpython2.6.so
#32 0x00007ffff7a23d60 in PyEval_EvalCodeEx () from /usr/lib/libpython2.6.so
#33 0x00007ffff7a23e32 in PyEval_EvalCode () from /usr/lib/libpython2.6.so
#34 0x00007ffff7a41d1c in PyRun_StringFlags () from /usr/lib/libpython2.6.so
#35 0x00007ffff019d1e7 in pyembed_eval (env=0x401121d0,
    _jepThread=140737154335376,
    str=0x7fffec117390 "import numpy; numpy.finfo(float)") at pyembed.c:929
#36 0x00007ffff019c29a in Java_jep_Jep_eval (env=0x401121d0,
---Type <return> to continue, or q <return> to quit---
    obj=<value optimized out>, tstate=140737154335376, jstr=0x7ffff58fbdf8)
    at jep.c:137
#37 0x00007ffff1a67d6e in ?? ()
#38 0x0000000000000000 in ?? ()
(gdb) thr 10
[Switching to thread 10 (Thread 0x7ffff08b3700 (LWP 20747))]#0  0x00007ffff771cb50 in sem_wait () from /lib/libpthread.so.0
(gdb) bt
#0  0x00007ffff771cb50 in sem_wait () from /lib/libpthread.so.0
#1  0x00007ffff600eea5 in check_pending_signals(bool) ()
   from /usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib/amd64/server/libjvm.so
#2  0x00007ffff600745c in signal_thread_entry(JavaThread*, Thread*) ()
   from /usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib/amd64/server/libjvm.so
#3  0x00007ffff61170f1 in JavaThread::run() ()
   from /usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib/amd64/server/libjvm.so
#4  0x00007ffff600eadf in java_start(Thread*) ()
   from /usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib/amd64/server/libjvm.so
#5  0x00007ffff77159ca in start_thread () from /lib/libpthread.so.0
#6  0x00007ffff726e70d in clone () from /lib/libc.so.6
#7  0x0000000000000000 in ?? ()

From delta debugging, it appears the following loop runs 9 times (should run max_iterN=10000 times), and then things halt on the temp = z*t line:
   for _ in xrange(max_iterN):
       y = z
       z = y*y
       a = z*one # Check here for underflow
       temp = z*t
       if any(a+a == zero) or any(abs(z)>=y):
           break
       temp1 = temp * betain
       if any(temp1*beta == z):
           break
       i = i + 1
       k = k + k
   else:
       print 'baz'
       raise RuntimeError, msg % (_, one.dtype)

Any ideas? To fully reproduce:
mkdir /tmp/test/

cd /tmp/test/

wget 'http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/numpy-1.6.1.tar.gz'

tar xzf numpy-1.6.1.tar.gz

cd numpy-1.6.1/

python setup.py install --prefix=/tmp/test/env

cd

git clone https://github.com/mrj0/jepp.git

cd jepp/jep/

export JAVA_HOME=/usr/lib/jvm/java-6-sun/

./configure --prefix=/tmp/jepp && make && make install

touch /tmp/go.py

PYTHONPATH=/tmp/test/env/lib/python2.6/site-packages/
LD_PRELOAD=/usr/lib/libpython2.6.so java -jar jepp.jar -i /tmp/go.py

>>> import numpy
>>> numpy.finfo(float)

I've been able to reproduce this on my machines, which are Ubuntu x86_64 boxes.  It's been a while but IIRC I don't experience this with the Ubuntu numpy package, only with a from-source build as instructed above.
Thanks in advance. This has been driving me up the wall.

A: See this post by John Wright who ran into the same problem: http://mail.scipy.org/pipermail/numpy-discussion/2009-July/044046.html
Basically, numpy is using the Python C api in a way that's incompatible with Jep. Jep uses sub interpreters to allow multiple interpreter environments. It could be possible to change Jep so that it uses the GIL state functions, but that would really limit Jep's functionality in Java.

A: Is there any particular reason you cant use Jython ? My understand is that is pretty much a real subsitute for the real thing.

A: If you have more than one thread calling into CPython, and one of those threads is "busy", then the global lock will probably be locked, and CPython has no choice except to hang until that lock is released.
What threads do you have calling into python - additionally - what is python doing in those threads?


text:
Q: Extract number before and after character I need to extract a certain number from my 'TblA' from column 'Input' in sql.
I have the following example input and desired output 1 and 2.

Input
Desired Output 1
Desired Output 2

20 x 88 nc.
20
88

100 x 300 nc
100
300

200x 88 nc.
200
88

5x 300 nc
5
300

ol (200x 88nc.)
200
88

ol (100x 300nc)
100
300

90dfa (45x65)
45
65

90dfa (45 x 65)
45
65

5,5 x 30 nc
5,5
30

5.5 x 30 nc
5.5
30

Could you please help me with this code?
Thank you in advance.
I have worked in the past with Left and right functions to the the Nth character.
But I don't know where to start with this code.
I am using sql server 2019

A: Assuming that you have only one 'x' in your string (as in all your examples), then the following works:
select *
from t cross apply
     (select stuff(col1, 1, len(col1) - patindex('%[^0-9,.]%', reverse(col1) + ' ') + 1, '') as col1,
             left(col2, patindex('%[^0-9,.]%', col2 + ' ') - 1) as col2
      from (values (replace(left(t.input, charindex('x', t.input) - 1), ' ', ''),
                    replace(stuff(t.input, 1, charindex('x', t.input), ''), ' ', '')
                   )
           ) v(col1, col2)
     ) v;

Here is a db<>fiddle.


text:
Q: Two different React Contexts, want to call the other but not re-render component I have a problem with my component re-rendering. I have tried to separate the contexts in an App-context and a Player-context so that Player-context can change without updating my Epg-component below that uses the App-context solely.
But I need to set a value inside my Epg-component for the Player-context. So I tried with a callback function called "setPlayerAsset" inside my App.js, and send it through to the Epg-component.
Problem is that when I update the player-context the Epg-component re-renders, claiming that the setPlayerAsset-prop has changed.
Any ideas how this could be fixed?
I have two context files:
appContext.js
import React, {
  createContext, useMemo, useReducer, useContext,
} from 'react';
import { v4 as uuidv4 } from 'uuid';

const AppContext = createContext();

const appReducer = (state, action) => {
  switch (action.type) {
  case 'ADD_SHOW_ERROR_POPUP':
    return {
      ...state,
      showErrorPopup: true,
      errorPopupProps: action.payload,
    };
  default:
    throw new Error(`Unsupported action type: ${action.type}`);
  }
};

const INITIAL_STATE = {
  showErrorPopup: false,
};

export function AppProvider(props) {
  const [state, dispatch] = useReducer(appReducer, INITIAL_STATE);
  const value = useMemo(() => [state, dispatch], [state]);
  return <AppContext.Provider value={value} {...props} />;
}

export function useAppState() {
  const context = useContext(AppContext);
  if (!context) {
    throw new Error('useAppState must be used within a AppProvider');
  }
  const [state, dispatch] = context;
  const addShowExitModal = () => dispatch({ type: 'ADD_SHOW_EXIT_MODAL' });

  return {
    state,
    dispatch,
    addShowExitModal,
  };
}

And an playerContext.js
import React, {
  createContext, useMemo, useReducer, useContext,
} from 'react';

const PlayerContext = createContext();

const playerReducer = (state, action) => {
  switch (action.type) {
  case 'ADD_PLAYER_ASSET':
    return {
      ...state,
      playerAsset: action.payload,
    };
  default:
    throw new Error(`Unsupported action type: ${action.type}`);
  }
};

const INITIAL_STATE = {
  playerAsset: null,
};

export function PlayerProvider(props) {
  const [state, dispatch] = useReducer(playerReducer, INITIAL_STATE);
  const value = useMemo(() => [state, dispatch], [state]);
  return <PlayerContext.Provider value={value} {...props} />;
}

export function usePlayerState() {
  const context = useContext(PlayerContext);
  if (!context) {
    throw new Error('useAppState must be used within a PlayerProvider');
  }
  const [state, dispatch] = context;

  const addPlayerAsset = (payload) => dispatch({ type: 'ADD_PLAYER_ASSET', payload });

  return {
    state,
    dispatch,
    addPlayerAsset,
  };
}

In index.js
import { AppProvider } from './context/appContext';
import { PlayerProvider } from './context/playerContext';

const queryClient = new QueryClient();

ReactDOM.render(
  <AppProvider>
    <PlayerProvider>
      <Router>
        <QueryClientProvider client={queryClient}>
          <App />
          <ReactQueryDevtools initialIsOpen={false} />
        </QueryClientProvider>
      </Router>
    </PlayerProvider>
  </AppProvider>,
    document.getElementById('root'),
);

And in App.js
import React, {
  useEffect, useState, useCallback, useMemo,
} from 'react';
import { useAppState } from './context/appContext';
import { usePlayerState } from './context/playerContext';

const App = () => {
  const {
    state: {
      showErrorPopup,
    },
    addShowErrorPop,
  } = useAppState();

  const {
    state: {
      playerAsset,
    },
    addPlayerAsset,
  } = usePlayerState();

  const setPlayerAsset = (value) => {
    addPlayerAsset(value);
  };

  return (
      <Epg
        setPlayerAsset={(value) => setPlayerAsset(value)}
      />
    );
  };

export default App;

A: I think you should add useCallback for setPlayerAsset to avoid function re-rendering.
const setPlayerAsset = useCallback((value) => {
    addPlayerAsset(value);
  }, []);

You should modify this as well
<Epg
    setPlayerAsset={setPlayerAsset}
/>

With this way setPlayerAsset={(value) => setPlayerAsset(value)}, it will create a new function instance every time when your component gets re-rendered.


text:
Q: However, this package itself specifies a `main` module field that could not be resolved - React Native I have installed the 'react-native-auto-scrolling` package and I get the following error:
error: Metro has encountered an error: While trying to resolve module 'react-native-auto-scrolling' from file '.....\Home.js', the package '......\node_modules\react-native-auto-scrollinge\package.json' was successfully found. However, this package itself specifies a 'main' module field that could not be resolved ('......\node_modules\react-native-auto-scrollinge\dist\index.js'.

I have tried to fix this by adding in the metro.config.js the following code:
resolver: {
      sourceExts: ['jsx', 'js', 'ts', 'tsx'],
},

under module.exports (as I found that the Metro doesn't know how to compile by default .tsx) but I still cannot use the package, as it returns me the same error when trying to run react-native run-android. As I checked node-modules for the package, I have discovered that the package is created using typescript. Any help would be appreciated. I've seen a snack that works: Exemple auto-scrolling so I guess it should also work with a bare workflow react native app.