text:
Q: How do I write an "Automation" using Shortcuts to stop my workout? I often forget to stop my "Workout" that is running on my watch.  I'd like an automation something like:
if workout is running AND
   in the area of the gym (Geofence) AND
   iPhone connects to my car (Bluetooth) THEN
  stop Workout or at least remind me to stop the Workout

This is partly a "is this even possible" type question because the Shortcut (I assume) will be running on my phone while the workout is running on my watch.

A: The simple solution would be to create an automation that runs when you leave the gym that sends a notification asking if your workout is still running.
If you use a specific focus while you work out, you can also get the current focus and check against that as well.
The only thing you can do regarding workouts/fitness in Shortcuts is start them; you can't end them. You also can't check for open apps. The best you can do is a notification reminder to manually end the workout.


text:
Q: How to get category of sub items defined as a separate row in the same table I have a table in SQL Server 2017 like below:
Type Description
H    General Income
H    Property Income
R    Rent
R    Parking
R    Storage
H    Cash Flow
H    Other Income
R    Specials

Here, H refers to Header and R refers to Role. The roles belong to the header defined above them. For example, General Income has no role defined yet but Property Income has three roles under it - rent, parking and storage.
My expected output is:
Header             RoleDescription
General Income
Property Income    Rent
Property Income    Parking
Property Income    Storage
Cash Flow
Other Income       Specials

How can I get this, I couldn't find it. Any help would be appreciated.
Edit: I have an ID column, yes, I believe I can use it for ordering.

A: Assuming your table has an ordering column, you can approach this by using a cumulative conditional sum to define the groups.
Then there is a trick.  Use conditional aggregation for the role and conditional aggregation with a window function for the header:
select max(max(case when type = 'H' then description end)) over (partition by grp) as header,
       max(case when type = 'R' then description end) as role
from (select t.*,
             row_number() over (partition by type, grp order by <ordering col) as seqnum
      from (select t.*,
                   sum(case when type = 'H' then 1 else 0 end) over (order by <ordering col>) as grp
            from t
           ) t
     ) t
group by seqnum
order by grp, seqnum;

redpajama_set_name: RedPajamaStackExchange


text:
Q: SVN overwrites local copy of XML file rather than displaying a conflict I have an SVN repository managing our project and we have a config file for the app that has been committed to the base so that every developer can get the format. He/she is then required to modify that file to match their system's settings. I recently committed my copy of the config file (by mistake) and on the next update, everyone else was automatically updated to my copy rather than SVN declaring a conflicted state. The following line particularly intrigues me:
<Address>http://192.168.1.136:8080/FeatureServer</Address>

This is my local IP address and each developer has to modify this line to point it to their IP address. Once I committed my file, SVN now just updates everyone else's config files to my copy on an 'Update'. Why is that so? Is it because this is not a code file and SVN somehow knows it ? I do get conflicts in code files so I don't think SVN is somehow messed up. What's special in this case?
I use TortoiseSVN 1.7.4 over Windows 7 on a 64 bit machine.
Thanks

A: Turns out if the developer hasn't changed the file on his/her end, they will receive the update from the server. A conflict does show up when I change my copy and then do an update.


text:
Q: Xamarin Android Binding ReferenceJar equivalent in aar? I trying to bind an .aar library that depends on other .aar library. In the ".jar" world, I would set the library I want to create the binding as "InputJar" and the dependencies as "ReferenceJar".
In ".aar", the equivalent for "InputJar" is "LibraryProjectZip", but... what would be the equivalent for "ReferenceJar"? EmbeddedNativeLibrary? Or "LibraryProjectProperties"?
Thanks!

A: You have to create two binding projects, one for your .aar library (Library1) and another one for your .aar dependency (Library2). Please note that both .aar binding projects require buildAction set to LibraryProjectZip. Afterwards just add Library2 as a dependency as Library1. In the Xamarin world that means add the binding project of Library2 as a reference to the Library1 binding project.
Jar dependencies can be added directly thru BuildAction = ReferenceJar.
Other common dependencies can be added via the nuget package manager.

A: The answer seems to be explain Here, the settings describe inside works for me.
the .aar file require a build action set to LibraryProjectZip


text:
Q: Запись происходит не в ту строку listbox в которую должна записаться UPD: Пока не справился - проблема осталась
По какой причине в многопоточном режиме может происходить запись не в ту строку listbox ?
Вот так запускаю выполнение одного и того же алгоритма разных потоках
    var algoritmRaboti0 = new Thread(() => Algoritm(0, 3));
    algoritmRaboti0.Start();

    var algoritmRaboti1 = new Thread(() => Algoritm(1, 3));
    algoritmRaboti1.Start();

    var algoritmRaboti1 = new Thread(() => Algoritm(2, 3));
    algoritmRaboti1.Start();

Вот так из алгоритма заполняю строки в listBox
    private void Algoritm(int num1, int num2)
    {
        ...
        for (int i = num1; i < length; i += num2)
        {
           int j = i;
           string nomer;
           ...
           listBoxNomer.BeginInvoke(new Delegate(ListBoxNomerChange), j, nomer);
           ...
        }
        ...
    }

        public delegate void Delegate(int num,string text);
        public void ListBoxNomerChange(int num, string text)
        {
            listBoxNomer.Items.Insert(num, text);
        }

Воспроизвести не получается и найти почему, тоже, но я отслеживаю значение i и вижу что оно равно допустим 4, а данные записываются в 6 строку listBox, хотя должны записаться в 5 строку.
Почему такое может происходить ?


text:
Q: Solving basic system of equations $x, y$ are positive reals such that $y\sqrt{x^2 - y^2} = 48$ and $x + y + \sqrt{x^2 - y^2} = 24$. How to find $x$ and $y$? Squaring equations leads to complicated equations with polynomials of high degrees. Is there any way to omit it and solve it smarter?

A: Call $x^2-y^2=z^2 \quad (1)$ then:
$yz=48 \quad(2)$ and $x+y+z=24 \quad(3)$
From $(1)$ we have:
$$x^2=y^2+z^2=(y+z)^2-2yz$$
and using $(2)$ and $(3)$ we get:
$$x^2=(24-x)^2-2.48 \Rightarrow x=10$$
and then $y=8$ or $y=6$


text:
Q: Open exe file using VBA I wanted to open a file by VBA and I've written this code:
ShellExecute ("explorer.exe C:\FY20 CPM\HS-HO-OPG\B -  SQL INDIRECT BUSINESS\FP 201801\sde.exe")

And for every file it works if I give there notepad or something like this, it will work, for example:
ShellExecute ("explorer.exe C:\FY20 CPM\HS-HO-OPG\B -  SQL INDIRECT BUSINESS\FP 201801\Test.txt")

But for that first code, I'm getting this error:

Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'C:\WINDOWS\System32\sde-query.log' is denied.

What I want to underline is that I can normally open this file manually. This file is something like SQL making some queries.
So it is probably a problem with UnauthorizedAccess.
Is there any stronger function than shell? For exmaple open as administator or something?
Or maybe someone has a better idea on how to handle it?

A: Based on the error message, it appears that the executable that you're trying to run generates its log files in the working directory.
Now, the code that you posted doesn't make much sense. It looks like you're launching Explorer.exe and passing the path of the target file as an argument. In which case, your code should probably be ShellExecute "explorer.exe", "C:\FY20..." instead of ShellExecute "explorer.exe C:\FY20...".
Anyway, the problem with this is that because ShellExecute is actually launching Explorer.exe, not sde.exe, the working directory becomes the system32 directory which the sde.exe process doesn't have permission to access, hence, the UnauthorizedAccessException. To prevent this, you should launch sde.exe directly without Explorer.exe. Here's a complete example:
Dim filePath As String
filePath = "C:\FY20 CPM\HS-HO-OPG\B -  SQL INDIRECT BUSINESS\FP 201801\sde.exe"

Dim objShell: Set objShell = CreateObject("shell.application")
objShell.ShellExecute filePath, "", "", "open", 1
Set objShell = Nothing

And you can even change the working directory by passing a path to the third parameter:
Dim customWorkingDir As String
customWorkingDir = "C:\FY20 CPM\HS-HO-OPG\B -  SQL INDIRECT BUSINESS\FP 201801"
objShell.ShellExecute filePath, "", customWorkingDir , "open", 1

References:

*

*ShellExecute method.


text:
Q: How can I stub a Node.js MongoDB chained fn call to mock my end result? I am trying to test (with Sinon.JS Stubs) the following call with the Node.js MongoDB driver...
collection.find({mood: 'happy'}).toArray((err, result) => {

  // array result

  cb(null, result);
});

What is hanging me up here is the .toArray() chained function. The above call returns result as the expected Array.

To demonstrate my struggle - and to contrast - I am able to stub the following call which is not chained as such...
collection.findOne({id: 'id'}, (err, result) => {

    // single result

    cb(null, result);
  });

stubb'd =>
findOneStub.yields(null, {username: 'craig'});

Is there a straightforward way to stub my .find call, which returns a function with .toArray on it to finally mock my results?

A: What I usually do when I want to stub methods of complex nested object like with the Mongo driver case, is to mock an object that mimics the call chain like so:
Stubbing toArray() using callback
let mockDbCollection = {
  find: function() {
    return {
      toArray: function(cb) {
        const results = [{
          username: 'craig'
        }];

        cb(null, results);
      }
    };
  }
};

sinon.stub(db, 'collection')
  .returns(mockDbCollection);

db.collection('users').find({
  id: 'id'
}).toArray((err, docs) => {
  console.log(docs);
  done();

});

Stubbing toArray() using promise
let mockDbCollection = {
  find: function() {
    return {
      toArray: function() {
        return Promise.resolve([{
          username: 'craig'
        }]);
      }
    };
  }
};

sinon.stub(db, 'collection')
  .returns(mockDbCollection);

db.collection('messages').find({
  id: 'id'
}).toArray().then((docs) => {
  console.log(docs);
  done();
});

This paradigm can be used in any case that you want to mock a sequence of calls on a complex object, focusing only on the response of the last call in the chain.  You can go as deep as you want without any issues.
If you want something more advanced like setting behavior of the stub or counting calls, etc you can find out some other techniques in this article.  The author showcases some examples using complex DOM objects.
Adapting the technique from the tutorial in our example, we could easily do the following:
// here we stub the db.collection().findOne() method
// and fabricate a response
let stubFindOne = this.sandbox.stub().resolves({
  _id: 'id'
});

// now, we can set the stub
// function in our mock object
let mockDb = {
  collection: () => {
    return {
      findOne: stubFindOne
    };
  }
};

This way, we can manipulate and inspect the stubbed method as we would normally do, e.g.
const args = stubFindOne.firstCall.args;

would return the arguments list of the first call, etc.


text:
Q: Filling an empty sequence after clearing I have written code to determine the average number of recursive calls made to a function quickselect, and while my quickselect code works and my main function works if I only have one trial, I am unable to run any successive trials. I am getting the IndexError cannot choose from an empty sequence. I have tried moving hold.clear() to different locations in the loop but it is not repopulating no matter where I put it. Any suggestions would be welcomed.
import numpy
import numpy as np
import random

def main(trials,k):
    i = 0;
    hold = []
    calls = -1;
    while i < trials:
        print(hold)
        hold.clear()
        generate(hold, k)
        print(hold)
        quickselect(hold, k, calls)
        i = i + 1
    print(calls/trials)

def generate(l,n):
    for i in range(n):
        r=random.randint(0,n)
        if r not in l:
            l.append(r)

def quickselect(l, k, calls) :

    calls = calls + 1
    length = len(l)

    pivot = random.choice(l)

    l_small = []
    l_big = []

    smalltrack = 0
    bigtrack = 0
    i = 0
    ispivot = 0
    while i < length:

        compare = l[i]
        if compare < pivot:
            l_small.append(compare)
            smalltrack = smalltrack + 1

        elif l[i] > pivot:
            l_big.append(compare)
            bigtrack = bigtrack + 1
        else:
            ispivot = ispivot + 1

        i = i + 1

    checker = len(l_small) + len(l_big)

    checker = checker + ispivot

    assert(length == checker)

    if k <= len(l_big):

    # kth largest must be in l_big

        res = quickselect(l_big, k, calls)

        return res
    elif k > len(l_big) + 1:

    # kth largest must be in l_small

        res = quickselect(l_small, k - len(l_big) - 1, calls)

        return res
    else:

        print(calls)
        return calls


text:
Q: Capturing text from one dynamic text field to another dynamic text field a few frame later in Flash using AS3 Basically i have a dynamic text field (txtarea)on a frame and the text inside is inserted by an XML file. this frame also has two buttons allowing you to flick between data in the xml file. I also have a button(btn) going to frame 10 which has another dynamic text field (txtarea2).
What i want to happen is when the user has the desired piece of information in txtarea they press the btn and that information is shown in txtarea2. so basically mirroring the previous dynamic text field.
this is the code i have but it doesnt return anything in the other dynamic text field.
(i have deleted the XML code as it is working)
stop();
btn.addEventListener(MouseEvent.CLICK, frame5);
function frame5(evt: MouseEvent): void {
gotoAndStop(5);
}

this.storedtxt = txtarea.text

txtarea2.text = this.storedtxt;

Ive also tried
this.storedtxt = txtarea.text;
txtarea2.text = txtarea.text;

What is the correct code for this?
Thanks

A: Does txtarea exists in the timeline in the destination frame? If not then
this.storedtxt = txtarea.text
doesn't get anything because txtarea doesn't exists. For the most part, stage display objects get cleared when they are no longer present in the timeline.
When you do
function frame5

you could store the value of txtarea.txt in a variable in the frame5 function for use later in frame 5.
Try trace statements to check the value of txtarea.txt.

A:
What is the correct code for this?

Correct way - store data before you leave current frame. From your current logic, you store textfield content instantly user visits frame. And if your field doesn't have a text you will have empty string.
Correct way:
function frame5(evt: MouseEvent): void {
    //Store text before user leaves current frame
    this.storedtxt = txtarea.text
    gotoAndStop(5);
}

Frame 5 code (I assume you have txtarea2 TextArea in 5-th frame):
txtarea2.text = this.storedtxt;


text:
Q: How accurate are the values produced by aruco.estimatePoseSingleMarkers()? I will be using the values produced by this function as a ground-truth labels for a computer vision task, where I will train a model using simulation data and test it using ArUco's real world ones.
I calibrated my smartphone camera with a chess board and got a reprojection error of 0.95 (I wasn't able to get less than this, tried all the possible options like ArUco and ChAruco, captured tens of images, filtered the bad ones, and none has improved the error) I read somewhere that this is expected from smartphones, if not, please let me know.
Now I placed my ArUco marker somewhere in the environment and captured images of it, produced its pose relative to the camera using  estimatePoseSingleMarker .
Upon drawing the axis, everything looks perfect and it's accurate. However, when I compare the pose values with the ones generated from simulating the same environment with the same object and camera. The values are actually quite different, especially the z value.
I'm 100% sure that my simulation environment has no error, so I presume this gap is caused by ArUco.
Do you suggest any solution? how can I predict the error of ArUco?
Is there any other possible solution to collected ground-truth labels?


text:
Q: How to get a td value using SimpleHTMLDOM? I have the following table which I'm trying to scrape with SimpleHtmlDom.
How would I reference/access the date value of "application received" and put it in to a variable. I've tried using the plain text approach, but this produces all the text in all of the td's.

                                Reference

                             LA01/2018/0235/F

                                Application Received

                                Fri 23 Feb 2018

                                Address

                       206 Straid Road Bushmills.

                                Proposal

                          Alterations to existing car showroom.

                                Status

                            Application Received

                                Authority Decision

                        Not Available

                                Authority Decision Date

                              Not Available

                                PAC Decision

                           Not Available

                                PAC Decision Date

                              Not Available

Using the following code I'm able to echo out each listing.
curl_setopt($ch, CURLOPT_URL,$item);
                 $output = curl_exec($ch);
                 $html = str_get_html($output);
                 $table = $html->find('table',0);
                 $rowdata = array();
                 foreach($table->find('tr') as $row){
                  foreach($row->find('td') as $cell){
                        $listing = $cell->plaintext;

                     echo $listing,'
';
                        //echo '
'; print_r($listing);echo'
';
                        }
                     }

which produces the following result;
LA01/2018/0254/O
Tue 27 Feb 2018
39 Lyttlesdale Garvagh.
Proposed new dwelling and proposed new paired access to include demolition of existing garage.
Application Received
Not Available
Not Available
Not Available
Not Available
LA10/2018/0265/F
Tue 27 Feb 2018
45 Glen Road Killyculla Tempo BT94 3JU
Replacement dwelling-amended position,house type (split level) and domestic garage from previous approval LA10/2017/0529/RM for same
Application Received
Not Available
Not Available
Not Available
Not Available
Can anyone put me right on what it is I should be doing?


text:
Q: Removing Kubuntu from External Drive and Reformating For some obscure reason, which seemed like a good idea at the time, I installed Kubuntu onto an external USB 1TB drive. It never worked.
Now, I would like to use that drive as storage but cannot delete any of the installation or boot files. I also cannot upload any other files onto it.
How would I reformat the whole drive so it can be used as general storage which can be read by linux, android and windows devices
Many thanks

A: Gparted
In most cases it would work to use the graphical program gparted. It is available in Ubuntu live (booted from USB or DVD), and it can be installed in installed systems,
sudo apt install gparted

Start gparted

*

*Prepare by unmounting and swapping off all partitions on the drive and (you see lock symbols at mounted partitions and swapped on swap partitions).

*The next step would be to select the dropdown menu
Device - Create partition table
to create a new partition table (GPT is the new partition table and MSDOS is the old partition table).

*Now you can use the graphical interface or the dropdown menus to create partitions.
Wipe the first mibibyte
If gparted does not work, you can wipe the first mibibyte to remove data, that might cause confusion. You can use mkusb for this purpose.
help.ubuntu.com/community/mkusb
help.ubuntu.com/community/mkusb/wipe
and after that gparted should work.
Check the S.M.A.R.T. status
If there are still problems we can suspect that the drive is physically damaged, and you should check the S.M.A.R.T. status with Disks alias gnome-disks. See this link,
FSCK reports that filesystem still has errors - what should I do now?
Select file system
Depending on where and how you want the drive to work, you should select different file systems. If you want it to work easily 'everywhere' you can have a FAT32 file system, but then the maximum file size is 4 GB. If you want to manage bigger files, you should select another file system, for example NTFS or exFAT or UDF.
See the following link with detailed descriptions of how to select and create these alternative file systems.
How do I copy a file larger than 4GB to a USB flash drive?


text:
Q: Accessing MySQL from Internet I'm using Ngrok to link my development website locally to Internet but it doesn't work with MySQL server.
This is the code from the config.inc.php:
$cfg['Servers'][$i]['host']          = 'localhost'; // MySQL hostname or IP address
$cfg['Servers'][$i]['port']          = '8889';      // MySQL port - leave blank for default port
$cfg['Servers'][$i]['socket']        = '';          // Path to the socket - leave blank for default socket
$cfg['Servers'][$i]['connect_type']  = 'tcp';       // How to connect to MySQL server ('tcp' or 'socket')
$cfg['Servers'][$i]['extension']     = 'mysql';     // The php MySQL extension to use ('mysql' or 'mysqli')

And this is the code of my Ngrok config:
authtoken: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
tunnels:
  server:
    proto: http
    addr: 8888
  Db1:
    proto: tcp
    addr: 8889

I can access to the Apache Server but not to the MySQL database (it works in local so it's obviously a forwarding problem but I can't be able to solve).
EDIT :
This is my Ngrok running :
Forwarding                    tcp://0.tcp.ngrok.io:16097 -> localhost:8889
Forwarding                    http://b342784fc9ec.ngrok.io -> http://localhost:8888
Forwarding                    https://b342784fc9ec.ngrok.io -> http://localhost:8888

My pdo for local configuration :
<?php
    $user = 'root';
    $pass = 'root';
    $dbname = 'dbtest';
    $host = 'localhost';
    $port = '8889';

    $pdo = new PDO('mysql:host=' . $host . ';dbname=' . $dbname . ';port' . $port . ';charset=utf8', $user, $pass);
?>

And my pdo for online configuration :
<?php
    $user = 'root';
    $pass = 'root';
    $dbname = 'dbtest';
    $host = 'tcp://0.tcp.ngrok.io';
    $port = '16097';

    $pdo = new PDO('mysql:host=' . $host . ';dbname=' . $dbname . ';port' . $port . ';charset=utf8', $user, $pass);
?>

So basically, the local one is running but not the online one, but maybe I'm doing something wrong as networking is not a specialist.


text:
Q: QLineEdit being deleted after a couple of screens I'm using a QLineEdit and then needing to refer to it after 2 screens in PyQt. However I consistently keep getting this error when I refer to it
Traceback (most recent call last):
  File "[filename]", line 227, in passwordmissing2ndscreenverify
    P1=self.entrypasswordmissingscreen1.text()
RuntimeError: wrapped C/C++ object of type QLineEdit has been deleted
This is my first time using Qt to create complex programs that refer to things from several screens before so if anyone can help that'll be appreciated.
Heres the code for that section as well:
def passwordmissing1stscreen(self):
    #layouts
    self.mainLayout=QtWidgets.QVBoxLayout()
    self.secondaryLayout=QtWidgets.QHBoxLayout()

    #Labels
    self.passwordMissing1stScreenlabel= QtWidgets.QLabel("Please enter the new password")

    #buttons
    self.cancelbutton=QtWidgets.QPushButton("Cancel", self)
    self.okButton=QtWidgets.QPushButton("OK", self)
    #input
    self.entrypasswordmissingscreen1 = QtWidgets.QLineEdit()
    P1 = self.entrypasswordmissingscreen1.text()
    #conections
    self.cancelbutton.clicked.connect(self.exit)
    self.okButton.clicked.connect(self.passwordmissing2ndscreen)

    #add to layouts
    self.mainLayout.addWidget(self.passwordMissing1stScreenlabel)
    self.mainLayout.addWidget(self.entrypasswordmissingscreen1)
    self.secondaryLayout.addWidget(self.okButton)
    self.secondaryLayout.addWidget(self.cancelbutton)
    self.mainLayout.addLayout(self.secondaryLayout)

    #display screen#
    self.mainViewWidget = QtWidgets.QWidget()
    self.mainViewWidget.setLayout(self.mainLayout)
    self.setCentralWidget(self.mainViewWidget)

def passwordmissing2ndscreen(self):
    #layouts
    self.mainLayout=QtWidgets.QVBoxLayout()
    self.secondaryLayout=QtWidgets.QHBoxLayout()

    #Labels
    self.passwordMissing2ndScreenlabel= QtWidgets.QLabel("Please enter the new password again")

    #buttons
    self.cancelbutton=QtWidgets.QPushButton("Cancel", self)
    self.okButton=QtWidgets.QPushButton("OK", self)

    #input
    self.entrypasswordmissingscreen2=QtWidgets.QLineEdit()

    #add to layouts
    self.mainLayout.addWidget(self.passwordMissing2ndScreenlabel)
    self.mainLayout.addWidget(self.entrypasswordmissingscreen2)
    self.secondaryLayout.addWidget(self.okButton)
    self.secondaryLayout.addWidget(self.cancelbutton)
    self.mainLayout.addLayout(self.secondaryLayout)
    #conections
    self.cancelbutton.clicked.connect(self.exit)
    self.okButton.clicked.connect(self.passwordmissing2ndscreenverify)

    #display screen#
    self.mainViewWidget = QtWidgets.QWidget()
    self.mainViewWidget.setLayout(self.mainLayout)
    self.setCentralWidget(self.mainViewWidget)

def passwordmissing2ndscreenverify(self):
    P1=self.entrypasswordmissingscreen1.text()
    P2=self.entrypasswordmissingscreen2.text()
    print (P1)
    print (P2)

A: Ok so after some discussions with friends and other fellow programmers we came across a solution that works perfectly instead of having P1 = self.entrypasswordmissingscreen1.text() in passwordmissing1stscreen instead put self.P1.entrypasswordmissingscreen1.text() in passwordmissing2ndscreen and have all references to P1 changed to self.P1


text:
Q: PHP DateTime "Fails" with no apparent reason - PHP 7 I have an extremely weird behaviour in a few of my php7 servers (windows). Please follow me because it's a really weird one.
I have a few windows servers with php 7.0.2 and apache 2.4, both configured correctly. I run a php framework called Yii to render a webapp.
At random intervals (sometimes a day, sometimes a few days, sometimes as little as a few hours) the dateTime object of php starts behaving like it's not a dateTime anymore.
When I instantiate it with $var = new DateTime(); it doesn't give any error; However, if I apply any date-related method to it, or even if I try to print it it gives an error that looks like this one:

[27-Nov-2017 19:48:12 Europe/Rome] PHP Catchable fatal error:  Object
  of class 8 could not be converted to string in
  C:\KRIA\htdocs\yii-1.1.18.018a89\framework\db\schema\CDbColumnSchema.php
  on line 146

The only thing that changes constantly is the class ASCII code displayed.
The incriminated line is this:
switch($this->type)
    {
        -->case 'string': return (string)$value;
        case 'integer': return (integer)$value;
        case 'boolean': return (boolean)$value;
        case 'double':
        default: return $value;
    }

Nothing fancy, just a cast. But it gets worst: if I put a print_r, I get the messed up ASCII value but the type is Object, containing three keys: date, timezone, timezone_type. Exactly like a date object.
But this is really messed up part. If I restart the Apache service, everything gets back to normal.
This is driving me nuts. I've tried countless things but nothing seems to work.
Before blaming Yii, I tried just instantiating a new DateTime object and doing both echo and print_r, with the same result.
What do you guys think? I've never had this problem under CentOS or Debian (with which i usually work).
Is it possible that it's a php version thing?
Thanks a lot
EDIT AFTER A NEW OCCURENCE OF THE BUG
Ok, i was (un)lucky enough to catch this bug again. This time the entire system lasted 5 days without showing the behaviour.
I made a few more tests. I've created the simplest php page possible to test this:
<?php
 $dt = new DateTime();
 echo $date->format('Y-m-d H:i:s');

This works as intended. I've then added a print_r($dt), and got:
Object ( [date] => 2018-02-02 16:14:30.000000 [timezone_type] => 3 [timezone] => Europe/Rome )

Which differs from what i was expecting. The same exact code on my system produces this output:
DateTime Object ( [date] => 2018-02-02 16:15:36.000000 [timezone_type] => 3 [timezone] => Europe/Rome )

Which is what i was expecting. It seems that the object is no longer recognized as a DateTime obj.
Now, functions like modify or format works, but casting it to string (for example) produces the error shown before.
This application runs on a windows server machine, but the DB is on another one, so i'm able to connect to the latter by different clients.
With my own pc (that produces the "correct" print_r) the system works perfectly. On the faulty one it doesn't work.
The apache config is literally the same.
But now comes the really weird part: on the same machine, after a graceful restart of apache, running the same php code gives me the "correct" output i get on my machine.
It seems to me that there is something that "changes" the background code for the DateTime class in a transient way and completely at random, so when i reboot apache i reset this change and everything goes back to normal.
Last point: i did a clear install of apache and php before the second to last occurrence of this error, just to avoid any file corruption problem.
Is it possible that there is some external factor or something like that that screws me at random intervals?
Thanks a lot!

A: After a few months of suffering, i found a solution not to the cause underneath but to the sympthom at least.
The problem is some kind of component, hidden in all the different review made by god knows who (it's kinda of a messy organization) that corrupts the memory. Following this you get the error, sometimes accompanied by a "zend_heap memory corrupted", sometimes no.
Enabling the mod_fcgi in apache solves the problem. Following the logs I learned that this way the container is able to shut down any problematic php thread.
I hope this helps someone else!


text:
Q: how to get the distance from RSSI in veins? I found how to get the RSSI value in veins in this link: how to record rssi in veins (omnet++)
I want to know now how to get the distance between two nodes based on the RSSI value?

A: Referring to another post (links below), you could generate a simple look-up table: have one vehicle drive past another one, record distance and RSSIs, and you have a table that can map RSSI to distance. For details check
https://stackoverflow.com/a/54270962/7215379.
https://stackoverflow.com/a/39468731/7215379.


text:
Q: Why I am getting "return props.href || props.onClick;" after moving to browserify? I had everything working in one .jsx file, but I lost in that long file. So I have divided everything in multiple .jsx and and used browserify/watchify to transform to .js
    watchify -t reactify marek.jsx -o 'exorcist bundle.js.map > bundle.js' -d -v

And now I am getting:
    TypeError: props is undefined in Firefox
    Uncaught TypeError: Cannot read property 'href' of undefined in Chrome

For line:
    ListGroup.js:75
    return props.href || props.onClick;

What I have done wrong?
bundle.jsx
       var React = require('react/addons');
       var Adresy = require('./Adresy.jsx');

        var App = React.createClass({
       displayName: "App",

       getInitialState: function() {
       return {data: []};
       },

       loadCommentsFromServer: function() {
       $.ajax({
       url: this.props.url,
       dataType: 'json',
       success: function(data) {
       this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err)
        {console.error(this.props.url,status, err.toString());
        }.bind(this)});
       },

       componentDidMount: function() {
       this.loadCommentsFromServer();
       setInterval(this.loadCommentsFromServer, this.props.pollInterval);
       },

       render: function() {
          return (

       <Adresy data={this.state.data.adresy}/>

       );
       }
       });
       React.render(
       <App url={res} pollInterval={20000} />,
       document.getElementById("content")
       );

Adresy.jsx

       var React = require('react');

       var Panel = require('react-bootstrap/lib/Panel');
       var ListGroup = require('react-bootstrap/lib/ListGroup');
       var ListGroupItem = require('react-bootstrap/lib/ListGroupItem');
       var ButtonToolbar = require('react-bootstrap/lib/ButtonToolbar');
       var ButtonGroup = require('react-bootstrap/lib/ButtonGroup');

       var Adresy = React.createClass({

           getInitialState: function() {
             return {data: []};
           },

           getDefaultProps: function() {
           return {data: []};
           },

         render: function() {
           return (
             <Panel collapsible defaultCollapsed header='Adresy' className="TTemplate">
               <ListGroup fill>
                 {
                 this.props.data.map(function(value) {
                   return
                     <ListGroupItem key={value.adres_id} >

{value.st}

              </ListGroupItem>
            })
          }
              </ListGroup>
             </Panel>
           );
         }
       });

       module.exports = Adresy;

A: You mentioned that this code is auto-generated, but the formatting looks very off. There is a bug in the code you've posted, but I'm not sure if it's a copy/paste/formatting thing, or something actually wrong in your code:
           <ListGroup fill>
             {
             this.props.data.map(function(value) {
               return
                 <ListGroupItem key={value.adres_id} >

{value.st}

          </ListGroupItem>
        })
      }
          </ListGroup>

The map function will return undefined because return is on a line by itself:

function test() {
  return
    "testing";
}

alert(test());

Furthermore, I don't think the code as shown will even execute; if you line up the indentation, you can see you're missing a closing
 JSX tag:
<ListGroup fill>
{this.props.data.map(function(value) {
  return (
    <ListGroupItem key={value.adres_id} >

{value.st}

      {/* missing div here */}
    </ListGroupItem>
  );
})}
</ListGroup>

I suspect that one of these issues, or something related, is causing ListGroup to not get the right children property, causing it to fail in its isAnchor method:
isAnchor(props){
  return (props.href || props.onClick);
}

which is called with the child's props:
let child = this.props.children;

childrenAnchors = this.isAnchor(child.props);

(and more; see the source for details).


text:
Q: Import XLS file from GCS to BigQuery I have some .xls datas in my Google Cloud Storage and want to use airflow to store it to GCP. Can I export it directly to BigQuery or can i use additional library (such a pandas and xlrd) to convert the files and store it into BigQuery?
Thanks

A: Bigquery don't support xls format. The easiest way is to transform the file in CSV and to load it into big query.
However, I don't know your xls format. If it's multisheet you have to work on the file.


text:
Q: How can I force ld to link against static library I'm trying to create a shared library object (which will be loaded into R using dlopen) which links to the static rather than the dynamic version of a third-party library.  (The goal is to have one rather than two shared libraries that the user needs to move in place.)
Here is the call used to link the final executable:
gcc -std=gnu99 -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -flto=auto -Wl,-z,relro -o RNetica.so Cases.o Continuous.o Edges.o Experience.o Inference.o Networks.o Node.o Random.o Registration.o Session.o -dn -L/home1/ralmond/Projects/RNetica/src/Netica/Netica_API_607/lib -lnetica -dy -lstdc++ -L/usr/lib/R/lib -lR

This produces libRNetica.so which is designed to be loaded into R using dlopen.
Inside the Netica_API_607/lib directory, I have both libnetica.a and libnetica.so.  I thought that the -dn and -dy switches would hint to the linker to use libnetica.a instead of libnetica.so.  However, when I try to load libRNetica.so using dlopen I get the following error message:
 unable to load shared object '/home/ralmond/R/x86_64-pc-linux-gnu-library/4.1/00LOCK-RNetica/00new/RNetica/libs/RNetica.so':
  libnetica.so: cannot open shared object file: No such file or directory

The problem is that there are a limited number of places (e.g., /usr/local/lib) that R will look for the shared library.  I can move libnetica.so one of these places, but that requires root access so people without admin privileges can't install the program.  (I've read how using the shared library is better, but in this case, the lack of admin access is a problem.  Also, the Netica library is fairly specialized, so the performance hit will be small.)
Is there some flag I can pass to the linker to link statically instead of dynamically?

A:
Inside the Netica_API_607/lib directory, I have both libnetica.a and libnetica.so

This should work:
gcc -shared ... -L/home1/.../Netica_API_607/lib -Wl,-Bstatic -lnetica -Wl,-Bdynamic ...

Alternatively, you should be able to do this:
gcc -shared ... /home1/.../Netica_API_607/lib/libnetica.a ...

I thought that the -dn and -dy switches would

These switches are "global"; that is: -dn sets a boolean inside the linker to "never use shared libraries", and the -dy flips that boolean back to default, regardless of where on the command line these switches occur.


text:
Q: Java: Expanding array size, can't seem to keep all values in original locations For my current homework, I'm trying to sort my array through a generic class as the user inserts values into its locations. When the size reads as fully loaded, the array class calls in an expansion method that increases the size of the array while retaining its values in proper locations, which I followed from my Professor's note. For some reason, all my values except for location[0] seem to either be misplaced or erased from the array. I'm leaning that the problem originates in the expansion method but I have no idea how to fix this.
For example, the initial size is currently set to 5 but increments by 3 when expansion method is called. The user can input values 1,2,3,4,5 perfectly. But expansion is called when user inputs new value 6 that outputs an array of 1, 6, null, null, null, null.  Any further will lead to the error "Exception in thread "main" java.lang.NullPointerException"
Here is my Sorted Array class:
public class SortedArray {
private int size;
    private int increment;
    private int top;
    Comparable[] a;

public SortedArray(int initialSize, int incrementAmount)
{
        top = -1;
        size = initialSize;
        increment = incrementAmount;
        a = new Comparable [size];
}
public int appropriatePosition(Comparable value)
{
        int hold = top;
        if(hold == -1)
        {
            hold = 0;
        }
        else
        {
            for(int i = 0; i <= top; i++)
            {
               if(value.compareTo(a[i]) > 0)
               {
                   hold = i + 1;
               }
            }
        }
        return hold;
}
public Comparable smallest()
    {
        return a[0];
    }
public Comparable largest()
    {
        return a[top];
    }
public void insert(Comparable value)// the method that my driver calls for.
{
        int ap = appropriatePosition(value);
        //Expansion if full
        if(full() == true)
        {
            expansion();
        }
        //Shifting numbers to top
        for(int i = top; i >= ap ; i--)
        {
            {
                  a[i + 1] = a[i];
            }
        }
        a[ap] = value;
        top++;

    }
public boolean full()
{
    if(top == a.length -1)
    {
        return true;
    }
    else
    {
        return false;
    }
}
public void expansion()//here's where the expansion begins
    {
        int newSize = a.length + increment;
            Comparable[] tempArray = new Comparable[newSize];
            for(int i= 0; i < a.length; i++)
            {
                tempArray[i]= a[i];
                a  = tempArray;
            }
    }

Here's my driver class that calls for the insert method in SortedArray class.
public class IntDriver {
 public static void main(String[] args)
 {
     Scanner keyboard = new Scanner(System.in);
     //Creating variables
     int data;
     boolean check = false;
     int choice;
     int size = 5;
     int increment = 3;
     SortedArray b = new SortedArray(size, increment);
     //Creating Menu
     System.out.println("Please choose through options 1-6.");
     System.out.println("1. Insert\n2. Delete\n3. Clear\n4. Smallest\n5. Largest\n6. Exit\n7.Redisplay Menu");
     while(check == false)
     {
     choice = keyboard.nextInt();
     switch(choice)
         {
         case 1:
             System.out.println("Type the int data to store in array location.");
             data = keyboard.nextInt();
             Integer insertObj = new Integer(data);
             b.insert(insertObj);
             System.out.println("The value " + data + " is inserted");
             b.print();
            break;

A: In the expansion method, you're replacing a too soon.  The replacement should happen after the for loop:
public void expansion()//here's where the expansion begins
    {
        int newSize = a.length + increment;
            Comparable[] tempArray = new Comparable[newSize];
            for(int i= 0; i < a.length; i++)
            {
                tempArray[i]= a[i];
            }
            a  = tempArray;
    }


text:
Q: How can i use my ID from $_GET in $_POST to insert into table? So in the start of my file i am get the Id of my product, so i can differ between products and store data correctly. Thats my php:
<?php
if(isset($_GET['dish_did']))
{
    //get food id
    $dish_did = $_GET['dish_did'];

    //get data
    $sql = "SELECT * FROM dish WHERE did=$dish_did";

    //execute
    $res = mysqli_query($link, $sql);

    //count rows
    $count = mysqli_num_rows($res);

    //check whether the data is available or not
    if($count==1)
    {
        //we have data
        //get from database
        $row = mysqli_fetch_assoc($res);
        $nom = $row['nom'];
        $description = $row['description'];
        $last_rating = $row['last_rating'];
        }
    else{
        //not availible
        header("location: error.php");
    }
}
else{
    header("location: rate.php");
}
?>

After some HTML i have the following POST. I use this to save the data entered by the user in an other table (different table than dish).
<?php

//check whether submit clicked
if(isset($_POST['submit']))
{
    //get all details

    $dish_id = $_POST['dish.did'];

    $review_date = date("Y-m-d h:i:sa"); //Rating Date

    $user_review = $_POST['RatingLong'];

    //save in database
    //Create SQL to save data

    $sql2 = "INSERT INTO review SET
    user_review = '$user_review',
    review_date = '$review_date',
    dish_id = '$dish_id'
    ";

    //Execute the Query
    $res2 = mysqli_query($link, $sql2);

    //check wether query executed successfully or not

    if($res2==true)
    {

        //Query Executed and Review Saved
        $_SESSION['review'] = "
Review Successfull.
";
        // header('location:'.SITEURL);
    }
    else{
        //Failed to save review
        $_SESSION['review'] = "
Error.
";
        // header('location:'.SITEURL.'about.php');
    }

}

?>

Without the dish_id i am able to store data, but they aren´t assigned (so useless).
I am not sure how i can link the id correct, to be saved. I have seperate links for every product by id: http://localhost/Project/index.php?dish_did=2  for example.
What i have to change, that user_review and review_date is stored correctly with the same dish_id (table review) as dish_did (table dish).
ADDITIONAL QUESTION:
how can i comment  ?
edit:
added rate.php code and database
<?php

                $sql = "SELECT * FROM dish WHERE hide ='1'";

                $res = mysqli_query($link, $sql);

                $count = mysqli_num_rows($res);

                if($count>0)
                {
                    echo'
';

                    while($row=mysqli_fetch_assoc($res))
                    {
                        $did = $row['did'];
                        $nom = $row['nom'];
                        $description = $row['description'];
                        $last_rating = $row['last_rating'];

                    ?>

<?php echo $nom; ?>

<?php echo $description; ?>

                                    <a href="<?php echo SITEURL; ?>index.php?dish_did=<?php echo $did; ?>" class="btn btn-success" role="button">Jetzt Bewerten!

                            <?php
                    }

                }
                else{

                    echo "
Food not available.
";
                }
                ?>

Here my database:
create table users
(
uid int primary key AUTO_INCREMENT,
username varchar(25),
password varchar(25),
created_at date,
score int
);
create table dish
(
did int primary key AUTO_INCREMENT,
nom varchar(25),
description varchar(250),
last_rating int,
hide int DEFAULT 0 NOT NULL
);
create table review
(
review_id int primary key AUTO_INCREMENT,
user_id int ,
dish_id int ,
user_rating int ,
user_reveiw varchar(100),
review_date datetime,
foreign key (user_id) references users(uid),
foreign key (dish_id) references dish(did)
);

A: I found the issue.
It has to be this GET:
$dish_did = $_GET['dish_did'];
And this is the correct sql Statement:
$sql2 = "INSERT INTO review SET
    dish_id = '$dish_did',
    user_review = '$user_review',
    review_date = '$review_date'
    ";

In summary, I was in trouble because of my designations. I took the wrong ID, it must be $dish_did


text:
Q: Pass information from Windows Form Text box to Get-ChildItem Or something similar I have a directory of music that I created a GUI in Powershell to display and select certain songs.
The problem is the directory contains over 1,000 songs, so I want to be able to search the directory from the Windows Form I wrote. I wrote every part I needed, the only thing I can't do is get the auto complete to work properly.
When I try to run the script, a window pops up that says Unhandled exception has occurred in a component in your application. If you click Continue, the application will ignore this error and attempt to continue. Specified cast is not valid.
Included is the appropriate code (I left out the Go and Cancel buttons, along with a label, for brevity's sake). What am I missing?
Code:
# Dependencies
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

# Form Skeleton
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Select a Song"
$objForm.Size = New-Object System.Drawing.Size(400,300)
$objForm.StartPosition = "CenterScreen"

# Use Enter/Escape in addition to GO/Cancel
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
     {$UserInput=$objListBox.SelectedItem;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
    {$objForm.Close()}})

# Search Bar
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
$objTextBox.Size = New-Object System.Drawing.Size(300,160)
$objTextBox.Text = "Search..."
$objTextBox.AutoCompleteSource = 'CustomSource'
$objTextBox.AutoCompleteMode='SuggestAppend'
$objTextBox.AutoCompleteCustomSource=$autocomplete
$objForm.Controls.Add($objTextBox)

# Box the files appear in
$objListBox = New-Object System.Windows.Forms.ListBox
$objListBox.Location = New-Object System.Drawing.Size(40,70)
$objListBox.Size = New-Object System.Drawing.Size(260,20)
$objListBox.Height = 150

# Listing the songs in the directory
Get-ChildItem 'C:\Users\adammcgurk\Desktop\Songs' | % {$objTextBox.AutoCompleteCustomSource.AddRange($_) }
$objForm.Controls.Add($objTextBox)

# Just some style
$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

A: Note: The following works in PSv5.1, but not in PSv2. PSv2 compatibility is what the OP needs.
Replace:
Get-ChildItem 'C:\Users\adammcgurk\Desktop\Songs' |
  % {$objTextBox.AutoCompleteCustomSource.AddRange($_) }

with this:
($autocomplete = New-Object System.Windows.Forms.AutoCompleteStringCollection).
  AddRange((Get-ChildItem 'C:\Users\adammcgurk\Desktop\Songs' | % { $_.Name }))
$objTextBox.AutoCompleteCustomSource = $autocomplete

The above is merely a more efficient variation of the OP's own code (assuming that the OP actually initialized his $autocomplete variable to a [System.Windows.Forms.AutoCompleteStringCollection] instance).
It doesn't work in v2 for two reasons:

*

*syntactically: placing whitespace between member accessor . and the member name (AddRange) breaks in v2 - that's easily remedied by removing that whitespace, however.

*more importantly, presumably due to a bug, passing the [System.Windows.Forms.AutoCompleteStringCollection] to $objForm.Controls.Add breaks due to an unavailable COM interface, it seems. Interacting with the COM types directly - which is much more cumbersome - may offer a solution.


text:
Q: Manhattan Matrix by 2 Matrices is non symmetric but should be I created two matrices that have random integers as components, the dimension of the matrix doesn't matter. Then I want to calculate the distance matrix by the Manhattan method and frame it as a matrix. The matrix should be symmetric, but when I frame it as a matrix, the output is a non
symmetric distance matrix.
By that matrix (that should be the output) I want to calculate a cluster.
Where is my mistake?
Code:
a <- c(sample.int(30,6))

b <- c(sample.int(30,6))

c <- c(sample.int(30,6))

d <- c(sample.int(30,6))

e <- c(sample.int(30,6))

f <- c(sample.int(30,6))

V2 <- rbind(a,b,c,d,e,f)

V1 <- rbind(a,b,c,d,e,f)

d1MNR <- matrix(dist(Vorlage1,Vorlage2, method="manhattan"))              #### Is non symmetric

d1MR  <- matrix(dist(V1,V2,upper=TRUE, diag=TRUE ,method="manhattan"))    #### Should be symmetric, but is not

d1MR ### Generate output

hclust <- hclust(dist(d1MR), method = "single")                         ### Clustering

A: You can make a symmetrical distance matrix from V1 or a symmetrical matrix from V2, but the only way to make a symmetric matrix from both of them together is to combine them V12 <- rbind(V1, V2). The dist() function returns a dist object that hclus can use. You do not need to convert them to a matrix. In your example V1 and V2 are identical. We need them to be different:
set.seed(42)
V1 <- matrix(sample.int(30, 36, replace=TRUE), 6)
V2 <- matrix(sample.int(30, 36, replace=TRUE), 6)
V12 <- rbind(V1, V2)
rownames(V12) <- paste(rep(c("V1", "V2"), each=6), 1:6, sep=":")
colnames(V12) <- letters[1:6]
V12
#       a  b  c  d  e  f
# V1:1 17 18  4 18  4 28
# V1:2  5 26 25 15  5  8
# V1:3  1 17  5  3 13  3
# V1:4 25 15 14  9  5 26
# V1:5 10 24 20 25 20  1
# V1:6  4  7 26 27  2 10
# V2:1 24  8 28  3 18 22
# V2:2 30  4  5 24  6 21
# V2:3 11  4  4 23  6  2
# V2:4 15 22  2 17  2 23
# V2:5 22 18 24 21 20  6
# V2:6 26 13 18 26  3 26
d1MNR <- dist(V12, method="manhattan")
hclust <- hclust(d1MNR, method = "single")
plot(hclust)

If you want to look at a symmetrical distance matrix:
print(d1MNR, upper=TRUE, diag=TRUE)
#      V1:1 V1:2 V1:3 V1:4 V1:5 V1:6 V2:1 V2:2 V2:3 V2:4 V2:5 V2:6
# V1:1    0   65   67   33   79   75   76   43   53   16   66   39
# V1:2   65    0   58   66   44   38   79   90   64   57   49   72
# V1:3   67   58    0   72   62   76   79   88   52   67   69   98
# V1:4   33   66   72    0   86   78   45   46   74   43   63   26
# V1:5   79   44   62   86    0   58   83   90   54   73   31   72
# V1:6   75   38   76   78   58    0   75   68   48   73   59   54
# V2:1   76   79   79   45   83   75    0   67   93   80   52   59
# V2:2   43   90   88   46   90   68   67    0   40   49   73   36
# V2:3   53   64   52   74   54   48   93   40    0   55   65   68
# V2:4   16   57   67   43   73   73   80   49   55    0   72   49
# V2:5   66   49   69   63   31   59   52   73   65   72    0   57
# V2:6   39   72   98   26   72   54   59   36   68   49   57    0


text:
Q: Python 3, add two dictionaries and adding item inside the list associated with a key both dictionaries have I have a long list of names with work/hours but there are given based on locations.
For example:
Giving : LOCATION, NAME, MON, TUES, WED, THURS, FRI
for rows in  data:
    print(rows)

This prints:
"location_1", "name_1", "0.0","0.0","0.0","4.1","2.2"
"location_2", "name_1", "8.0","8.0","8.0","0.0","3.0"
"location_1", "name_2", "8.4","7.3","7.2","4.0","2.0"
"location_1", "name_3", "7.0","7.0","5.0","6.0","3.0"

If you notice the first 2 row has the same name but different locations, I would like to combine them into one dict by adding their values.
i can make them into dictionaries like this one. (pay attention to name_1 and how will be modify)
location_1= {"name_1":["0.0","0.0","0.0","4.1","2.2"],
             "name_2":["8.4","7.3","7.2","4.0","2.0"],
             "name_3":["7.0","7.0","5.0","6.0","3.0"]}

location_2 = {"name_1":["8.0","8.0","8.0","0.0","3.0"]}

but i need add the two dictionaries by adding the values of the list associated with the keys with the same name. so the result should look like this (notice the last value of name_1 and how the last value was add for the previous dict):
result_dict = {"name_1":["8.0","8.0","8.0","4.1","5.2"],
               "name_2":["8.4","7.3","7.2","4.0","2.0"],
               "name_3":["7.0","7.0","5.0","6.0","3.0"]}

I'm new in Python so if anyone can show me an efficient way to do this, it will be great.
Thank you.

A: If you are happy using a 3rd party library, you can do this easily with numpy.
I have intentionally kept the output in numeric form. It is good practice to store numeric data in numeric types.
import numpy as np

d1= {"name_1":["0.0","0.0","0.0","4.1","2.2"],
     "name_2":["8.4","7.3","7.2","4.0","2.0"],
     "name_3":["7.0","7.0","5.0","6.0","3.0"]}

d2 = {"name_1":["8.0","8.0","8.0","0.0","3.0"]}

res = {k: np.array(d1.get(k, [0]*5), dtype=float) + \
          np.array(d2.get(k, [0]*5), dtype=float) \
       for k in d1.keys() | d2.keys()}

# {'name_1': array([ 8. ,  8. ,  8. ,  4.1,  5.2]),
#  'name_2': array([ 8.4,  7.3,  7.2,  4. ,  2. ]),
#  'name_3': array([ 7.,  7.,  5.,  6.,  3.])}

A: This solution doesn't need any external libraries, so might be easier if you're not familiar with Python.
location_1= {"name_1":["0.0","0.0","0.0","4.1","2.2"],
                       "name_2":["8.4","7.3","7.2","4.0","2.0"],
                       "name_3":["7.0","7.0","5.0","6.0","3.0"]}
location_2 = {"name_1":["8.0","8.0","8.0","0.0","3.0"]}

.
for key, value in location_2.items():
    if key not in location_1:
        location_1[key] = value
    else:
        for i in range(len(value)):  # each index in the list
            old = location_1[key][i]
            new = float(old)+float(value[i])
            location_1[key][i] = str(new)  # str optional

At the end, the value is converted back into a string, but I would recommend keeping it as a numerical value.
Also, a float stores a floating point number, which can have decimal places, and can be manipulated as a number rather than a string, if you're new to general coding. To leave the value as a float, replace the last line
    location_1[key][i] = str(new)

with
    location_1[key][i] = new


text:
Q: Poisson bracket useful formula Equation 1.2.10 of  Wolf's "Spaces of constant curvature" is:
$[fX,gY] = fg[X,Y]+f(Xg)Y -g(Yf)X$ where $X$ and $Y$ are vector fields, and $[-,-]$ is the Poisson bracket.
I assume $f$ and $g$ are real valued functions, so $Xg$ and $Yf$ are also real valued functions (at each point one takes the directional derivative of the function along the vector given by the vector field at that point) and that, for example, $fX$, is just pointwise multiplication of $f$ and the directional derivative along $X$. The proof is left unstated, presumably because it is obvious to anyone with a grip of the subject.
Unfortunately I am very rusty and getting lost in the detail.
By antisymmetry I can see it is enough to prove that $[fX, Y] =f[X,Y] -(Yf)X$.
In turn this comes down to showing that $Y(fX)= fYX +(Yf)X$, i.e. that $Y(fX)h= fYXh +(Yf)Xh$ for any real valued function $h$ defined on relevant portions of the manifold.
I think this is simply a consequence of the chain rule for differentiation, but am getting quite confused with notation and where the various derivatives are being taken. Can anybody help me out?

A: You have correctly interpreted the meaning of $Xg$, $Yf$, and $fX$. The remaining pieces of notation to decipher are the combinations of differential operators like $YX$ and $Y(fX)$. The key is to know that when differential operators are written in a sequence, the implied operation is composition. Thus when $YX$ and $Y(fX)$ are applied to $h$, what we get are $Y(Xh)$ and $Y(fXh)$.
Now that we know what $Y(fX) = f(YX)+(Yf)X$ means, we can prove it using the product rule (rather than the chain rule). Applied to $h$, the identity we want is really $Y(f\cdot Xh) = f\cdot Y(Xh) + (Yf)\cdot(Xh)$. This is true by differentiating $f\cdot (Xh)$ with $Y$ and applying the product rule.


text:
Q: how '.join()' worked in below Python code There're two dataframes 'left' and 'right'. I'm applying '.join' on dataframes, changing default value of parameters 'how' and 'on'. I'm not able to understand on what logic/how I am getting the below outcome.
import pandas as pd
left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
                     'B': ['B0', 'B1', 'B2']},
                      index=['K0', 'K1', 'K2'])

right = pd.DataFrame({'C': ['C0', 'C2', 'C3'],
                    'D': ['D0', 'D2', 'D3']},
                      index=['K0', 'K2', 'K3'])

left.join(right,how='outer',on='A')

actual output:
    A   B   C   D
K0  A0  B0  NaN NaN
K1  A1  B1  NaN NaN
K2  A2  B2  NaN NaN
K2  K0  NaN C0  D0
K2  K2  NaN C2  D2
K2  K3  NaN C3  D3

A: You are getting this output since you are specifying that the .join should be on column named A, which is not existent in the right DataFrame.
The on parameter should be a Column or index level name to join on the index of the other DataFrame, in your case, since A is not the index of the other DataFrame, there is no join happening, just concatenating the two dataframes based on the outer join.
Instead, you shouldn't use on since .join uses index by default.
import pandas as pd
left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
                     'B': ['B0', 'B1', 'B2']},
                      index=['K0', 'K1', 'K2'])

right = pd.DataFrame({'C': ['C0', 'C2', 'C3'],
                    'D': ['D0', 'D2', 'D3']},
                      index=['K0', 'K2', 'K3'])

left.join(right,how='outer')

    A   B   C   D
K0  A0  B0  C0  D0
K1  A1  B1  NaN NaN
K2  A2  B2  C2  D2
K3  NaN NaN C3  D3

If you would like to merge based on values in a column, use pd.DataFrame.merge instead.


text:
Q: regex pattern for integer with comma The pattern
$test =  preg_match('/^(?=.\d)\d(?:\.\d\d)?$/', $_float1);

matches
0.25
2.55
1253.36
45.55

How to modify this to accept a comma in between the integer part?
such as 1,253.36?

A: You could use this pattern:
/^\d*(,?\d{3})*(\.\d+)?$/

A: You can use this regex:
^\d+(?:,\d{3})*(?:\.\d\d)?$

RegEx Demo

A: I would've used this one:
/^\d{1,3}(?:(,?)\d{3}(\1\d{3})*)?(?:\.\d{2})?$/

Explained:

*

*^\d{1,3}: starts by 1 to 3 digits

*(?:(,?)\d{3}(\1\d{3})*)?: [optional] repeat XXX or ,XXX patterns (only one of them, to exclude numbers like 11,111111)

*(?:\.\d{2})?: [optional] exactly two decimal places

*$: That's all folks

Matches:
1 - 12 - 123 - 1234 - 12345
1,234 - 12,345 - 123,456 - 1,234,567
1.23 - 12.34 - 123.45 - 1234.56 - 12345.67
1,234.56 - 12,345.67 - 123,456.78 - 1,234,567.89
Doesn't match:
.1 - .12 - .123
1.2 - 1.234 - 1.2345
12,34 - 123,45 - 1,2345 - 1,2,345 - 1234,567
12,34.56 - 123,45.67 - 1,2345.78


text:
Q: When do you use *ngIf="isProductSearchEmpty" or [style.display]="displayProduct"? Some times I do NOT know when to use *ngIf="isProductSearchEmpty" or [style.display]="displayProduct".

  "{{searchStr}}" not found..

  <rb-categories></rb-categories>

I have the option to use:

  "{{searchStr}}" not found..

  <rb-categories></rb-categories>

In product-list.component.ts, isProductSearchEmpty is either true or false and displayProduct is either none or block.

A: Most often you will want to use  ngIf as it correctly processes (adds or removes) child host views (components) and embedded views in the component view. It means:

*

*updating the ViewChild and ViewChildren queries

*triggering ngOnDestroy
Here is an example:
@Component({
    selector: 'my-app',
    queries: [],
    template: `

Hello {{name}}

    `
})
export class AppComponent {
    name = `Angular! v${VERSION.full}`;
    @ViewChildren(AComponent) children;

    ngAfterViewInit() {
        console.log(this.children.length); // 0
    }
}

Whereas display.none simply doesn't renderer DOM nodes, but the child elements are still processed by Angular:
template: `

Hello {{name}}

`,

and the length is now  1:
ngAfterViewInit() {
    console.log(this.children.length); // 1
}

The ngOnDestroy is also not triggered for the a-comp when it's being hidden and it now thinks that it's still exists.
I would say that [style.display]="'none'" can be safely used when the element it's used on doesn't house child components or embedded views created using ViewContainerRef.

A: *ngIf :

Conditionally includes a template based on the value of an expression.

It will add and remove the element from the DOM. So when you use with *ngIf you should consider that your template rendering may change for other elements.
Additionally, *ngIf can be used to display a whole template with 'ngIf -then else' syntax. It's more used when applied to a 'big' block of markup or when there is a else if condition going on.
[style.display] will only trigger the css property 'display' change. It's more to change the display property of the element.
Often [hidden] is used in lieu of *ngIf which takes the reverse logic and doesn't remove the element from the DOM.


text:
Q: Cheap, compact 3.7VDC -> 400kVDC (continuous) converters I recently bought some inexpensive and compact (about the size of a 18560 battery) 3.7VDC -> 400kVDC converters. I can confirm they work, and based on the breakdown voltage of air, estimate the output voltage to be in the region of 400kV. Output is continuous and not pulsed.
In principle I guess it would probably be built around the following stages:

*

*DC to AC inverter

*Step up AC with a number of transformers in series

*Rectify AC to DC

Unfortunately the circuit is all epoxied up so I can not learn how they did it. My questions are as follows:

*

*Do you think the steps I mentioned above are correct?

*Did they use a cascade of transformers for voltage multiplication because of the continuous output?

*I would be grateful for even a rough pseudo circuit schematic to help me understand what is going on.

A: I do not think there is DC to AC conversion. Most probably they are just stepping up the voltage step by step like in the classic Cockroft-Walton circuit. A clock is needed for that, but i would not consider it as AC conversion. A step-up or boost converter could be used as well, where the idea is that if we charge up an inductor and switch off its output load (= generating an open-circuit), than its output voltage could be in theory infinitely high, since the current of the inductor can not flow anywhere. In reality there are always leakage paths and a voltage limit where the some isolating material (even air) breaks through. Such a configuration is seen in this tear-down video.
There was a small series about charge pumps in the IEEE's SSC Magazine and also an overview in Circuit and Systems Magaizin. They are really good reads. Check it out if you have access to it. (Universities and libraries usually have)
T. Tanzawa, "Innovation of Switched-Capacitor Voltage Multiplier: Part 1: A Brief History," IEEE Solid-State Circuits Magazine, vol. 8, no. 1, pp. 51–59, winter 2016, doi: 10.1109/MSSC.2015.2495678.
G. Palumbo and D. Pappalardo, "Charge pump circuits: An overview on design strategies and topologies," IEEE Circuits Syst. Mag., vol. 10, no. 1, pp. 31–45, 2010, doi: 10.1109/MCAS.2009.935695.
About the step up or boost converter, just google it. There are many explanations.


text:
Q: C++: matching pipe-delimited strings with wildcards using boost::regex Suppose I would like to match for the following pipe-delimited strings:
std::string re("a|*|c");
std::string x("a|b|c");
std::string y("a|c|d");

does_match( re, x );  // want to return TRUE
does_match( re, y );  // want to return FALSE

what is the best way to implement does_match() using boost::regex?
I think I may be running into issues with escaping pipes and stars.  Note that I don't care about the actual matches: I just want an easy-to-use interface to does_match() to tell me if I have a match.
In particular, I hope to get this working without having to use a ton of escapes for pipes and stars.  I don't care about other more general uses of regex - if I can use pipe-delimiters and * for wildcards, that's sufficient.
Maybe I should do a transform inside does_match to make boost::regex happy?  Or perhaps my entire approach is bad (like I should be using some kind of strsplit() instead?).

A: I think your regex has to be like this a\\|.*?\\|c in order to match what you want. | has special meaning (logical or). And * has a special meaning (zero or more times). If the middle part is mandatory then use a\\|.+?\\|c.

A: The default pattern for what you're trying to do would require
"a\\|.*\\|c".  If your compiler supports C++11, you could use a raw
string to specify this: R"(a\|.*\|c)".  Otherwise, you can use a syntax
in which|was not a meta-character; Boost supports the Posix basic
syntax, for example, which doesn't support the or-operator, so you could
write"a|.*|c"`:
boost::regex pattern("a|.*|c", boost::regex::basic);

(You could use sed or grep instead of basic.)

A: Ok, I think I'm barking up the wrong tree by attempting to solve this with boost::regex() - boost::split() is probably more appropriate.
#include <string>
#include <vector>

#include <boost/algorithm/string.hpp>

bool does_match( const std::string& fmt, const std::string& str )
{
    std::vector<std::string> strs, fmts;
    boost::split( strs, str, boost::is_any_of( "|" ));
    boost::split( fmts, fmt, boost::is_any_of( "|" ));
    if ( strs.size()!=fmts.size() )
        return false;
    size_t n = strs.size();
    for( size_t i=0; i<n; ++i )
        if ( fmts[i].compare("*")  && fmts[i].compare( strs[i] ))
            return false;
    return true;
}


text:
Q: Shortcut keys of Clover do not work,why? I installed Clover on Win7.But it's shortcut keys(for example Ctrl+T,Ctrl+W,...) does not work.
I re-installed it, then search in Google. Only thing that may be correspond is ExplorerWatcher class that adds on to IE. But it is enable.
How I can solve this problem?

A: I began using Clover in Windows XP this past weekend and had no problems with it, but when I tried it in Windows 7, I experienced the hotkey problems you mentioned.
The problems I had were because I had extracted it from the installer and was running just the program. This was fine in Windows XP, but in Windows 7 with its different architecture and increased security and access restrictions, some of the hotkeys didn't work correctly. I fixed it by registering Clover's .dll and now all the hotkeys work as expected. Yay!
You can fix that by re-installing, making sure to run the installer as admin. Alternately, you can register just the extension:

*

*Open the Start menu

*Type cmd

*Press Ctrl+⇧Shift+Enter↵

*Use the cd command to navigate to the clover folder (defaults to C:\Program Files (x86)\Clover)

*Register it with the following command: regsvr32 TabHelper64.dll (on a 32-bit system, use regsvr32 TabHelper32.dll)


text:
Q: Need comments on MySQL events SET GLOBAL event_scheduler = ON;

CREATE TABLE question(
    qid INT AUTO_INCREMENT PRIMARY KEY,
    name CHAR(30) NOT NULL,
    text CHAR(100) NOT NULL,
    variation BOOLEAN NOT NULL,
    url CHAR(100) NOT NULL UNIQUE,
    expired TIMESTAMP NOT NULL
);

CREATE TABLE alternativ(
    aid INT AUTO_INCREMENT PRIMARY KEY,
    name CHAR(30) NOT NULL,
    text CHAR(50) NOT NULL,
    number_chosen INT,
    qid INT NOT NULL
);

ALTER TABLE alternativ
    ADD FOREIGN KEY (qid)
    REFERENCES question(qid);

CREATE EVENT delete_expired
    ON SCHEDULE
    EVERY 1 DAY
    DO
    DELETE FROM alternativ WHERE alternativ.qid IN (SELECT qid FROM question WHERE question.expired<CURRENT_TIMESTAMP)
    DELETE FROM question WHERE question.expired < CURRENT_TIMESTAMP;

My question is: Should this event work with the specified database? I have tried, but it dosen't seem to work. The idea is that the database itself will delete questions that has expired. Help would much be appreciated.

A: If you want to specify multiple statements within the event body, you will need to wrap them within a compound statement block such as BEGIN ... END (in order to make such a command work, one must configure one's client to use an alternative statement delimiter in order that it does not think the first encountered semicolon terminates the CREATE EVENT statement—in the mysql command-line tool, one can use the DELIMITER command):
DELIMITER ;;

CREATE EVENT ... DO BEGIN
  DELETE  ... ;
  DELETE  ... ;
END ;;

DELIMITER ;

That said, one can delete from multiple tables with a single DELETE command using the multiple-table syntax:
DELETE alternativ, question
FROM   alternativ JOIN question USING (qid)
WHERE  question.expired < CURRENT_TIMESTAMP

However, all that said, you might fare better specifying foreign key constraints that cascade record deletions:
FOREIGN KEY (qid) REFERENCES question(qid) ON DELETE CASCADE

Then, one only need DELETE the referenced record (i.e. in the question table) and MySQL will delete the referencing records (i.e. in the alternativ table) for you.


text:
Q: Android Studio - how to find methods from APIs higher than min and what to do with them? I am writing an app using AndroidStudio, targetting API 19, but with min API 14. I discovered that some of the methods I use are available from API 16+.
Is there a way in AndroidStudio to find all methods available from APIs higher than current minimum?
And what should I do with such calls? When I change them to compatibile with lower APIs, AS tells me that those methods are deprecated. So what can I do to support the older versions?

A: For finding uses of apis above minimal SDK api use lint, with gradle this should be by default unless you have:
lintOptions {
    abortOnError false
}

in your build.gradle
If you want to use api that is from ie. KITKAT for given object then write it like that:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
   obj.kitkatAndAboveApi().
}

if you want to use some class from ie. KITKAT and above then you would have to write a wrapper class to avoid exceptions while loading unaviable class. This class would be responsible for loading this kitkat class and would be used by your app only on kitkat+.
You can sometimes also use reflection for querying if method exist and then call it.
Also you can take a look how its done in support library, ie. for backward compatible MenuItem:
http://androidxref.com/4.4.4_r1/xref/frameworks/support/v4/java/android/support/v4/view/MenuItemCompat.java

some clarifications:

*

*Under Android Studio 0.8.9 to see all uses of unaviable api's, use menu Analyze -> Inspect Code. In results you will have Android Lint -> 'Calling new methods on older versions'. This is where you will have a list of errors you should fix.

*Build will fail if there are lint errors only if done from command line, ie.:
$ gradlew build
and only if you have not added abortOnError false. I dont know how to make AS fail on lint errors.


text:
Q: Error: vector memory exhausted (limit reached?) while merging list in R I am trying to merge three list using library(tidyverse)in R Studio in Mac. However, I get Error: vector memory exhausted (limit reached?).
In addition, I tried also using merge function, it still does not work. I followed different available suggestions such as R on MacOS Error: vector memory exhausted (limit reached?) and vector memory exhausted. This did not help. I am using Mac, OS Mojave 16 GB RAM. Is this happening because of merging large number of rows. Below is the code which I am running to merge lists. Please assist me with this.
MSP_Counts_Ensembl_Normalized <- read.csv(file = "./MSP_Counts_Ensembl_Normalized.csv", stringsAsFactors = FALSE, check.names = FALSE)
dim(MSP_Counts_Ensembl_Normalized)
1] 60639   115
class(MSP_Counts_Ensembl_Normalized)
[1] "data.frame"

Normalized_counts_trim_CSV <- read.csv(file = "./Normalized_counts_trim_CSV.csv", stringsAsFactors = FALSE, check.names = FALSE)

dim(Normalized_counts_trim_CSV)
[1] 32388    46
class(Normalized_counts_trim_CSV)
[1] "data.frame"

Normalized_counts_notrims_CSV <- read.csv(file = "./Normalized_counts_notrims_CSV.csv", stringsAsFactors = FALSE, check.names = FALSE)
dim(Normalized_counts_notrims_CSV)
[1] 52419    50
class(Normalized_counts_notrims_CSV)
[1] "data.frame"

library(tidyverse)
Combined_full_join_v1 <- list(MSP_Counts_Ensembl_Normalized, Normalized_counts_trim_CSV, Normalized_counts_notrims_CSV) %>% reduce(full_join, by = "hgnc_symbol")

sessionInfo()
R version 4.0.0 (2020-04-24)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Mojave 10.14.6

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] forcats_0.5.0   stringr_1.4.0   dplyr_1.0.2     purrr_0.3.4     readr_1.3.1     tidyr_1.1.1
[7] tibble_3.0.3    ggplot2_3.3.2   tidyverse_1.3.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.5       cellranger_1.1.0 pillar_1.4.6     compiler_4.0.0   dbplyr_1.4.4
 [6] tools_4.0.0      jsonlite_1.7.0   lubridate_1.7.9  lifecycle_0.2.0  gtable_0.3.0
[11] pkgconfig_2.0.3  rlang_0.4.7      reprex_0.3.0     cli_2.0.2        DBI_1.1.0
[16] rstudioapi_0.11  haven_2.3.1      xfun_0.16        withr_2.2.0      xml2_1.3.2
[21] httr_1.4.2       fs_1.5.0         generics_0.0.2   vctrs_0.3.2      hms_0.5.3
[26] grid_4.0.0       tidyselect_1.1.0 glue_1.4.1       R6_2.4.1         fansi_0.4.1
[31] readxl_1.3.1     modelr_0.1.8     blob_1.2.1       magrittr_1.5     backports_1.1.9
[36] scales_1.1.1     ellipsis_0.3.1   rvest_0.3.6      assertthat_0.2.1 colorspace_1.4-1
[41] tinytex_0.25     stringi_1.4.6    munsell_0.5.0    broom_0.7.0      crayon_1.3.4

Thank you,
Toufiq


text:
Q: PyQgis display vertex marker when in editing mode Documentation says when issue the following command on a vector layer (polygon), the vertex marker will be displayed in editing mode:
layer.startEditing()

But it is not displaying the vertex markers.
I found that there is a static drawVertexMarker method on QgsVectorLayer class, but do I have to manually call it to draw a marker on each vertex? Also, if I am moving vertex in editing mode, do I have to constantly re-draw all vertices?
Additionally, there is the editBuffer() property that returns the QgsVectorLayerEditBuffer reference, is it possible to display that buffer layer in editing mode for visual aid?

A: Perhaps you're just missing a call to
iface.mapCanvas().refresh()

after you call startEditing() from the layer object. Doing so you can visualize vertex markers from your layer features.


text:
Q: Interprocess file system communication without sockets I'm running a network emulator called MiniNet Wifi that allows for emulating network topologies including APs and UEs (hence the wifi). The emulation software is the only process that can access some key variables, e.g. 'in range APs' of an UE (i.e. mobile device).
The UEs and APs are running in seperate linux network namespaces (netns). The emulation is running in the host (regular) namespace. This means that no communication between the host and device network stack is possible. And this is also how I need it to be, for unrelated reasons.
Long story short, I need to spawn a thread in the emulation process that will allow other processes to pass messages (to and from). Thus I need to use the file system and not the network stack. So my question boils down to what the 'best' way of doing this in python is. Named pipes, just a simple file etc?
What also could be mentioned is that its ideal if the message passing is rather quick (ish) since the tasks are somewhat time critical.
Thanks.
Ps. Everything is obviously running on the same physical machine and share file system, i.e. not to be confused with docker.

A: Thanks to @Useless for pointing me in the right direction. I found this link and it solves my problem perfectly!


text:
Q: Define Azure APIM Definitions in Bicep For a project I'm working on, I need to define an entire Azure APIM in Bicep.
Now I want to define the request/response definitions for the developer portal, see the attached screenhot.
I've tried looking through the Azure documentation but found nothing to define these using Bicep. I have also tried exporting the APIM to ARM JSON, converting it to Bicep using az bicep decompile --file template.json, and reverse-engineering the definitions but the contents of the field Schema aren't included in the export output.
Does anyone know how to define the definitions in Bicep?

A: First define an schema sub-resource as defined here: https://learn.microsoft.com/en-us/azure/templates/microsoft.apimanagement/service/apis/schemas then use the schema's resourceID in operations' schemaId property.


text:
Q: From finitely additive to countably additive Given a finitely additive measure $\mu : \mathcal{B} \rightarrow [0,\infty]$. If we want to show that it is also countably additive, finite additivity implies
$$\mu(E) \geq \sum_{n=1}^\infty \mu(E_n)$$
where $\cup E_n = E$ with $E_n$ disjoint automatically.
For the inequality in the other direction, clearly countably subadditive is sufficient. I was wondering if there are weaker conditions that would also be sufficient. (Just take $\mathcal{B}$ to be the Borel $\sigma$-algebra on $\mathbb{R}$)
I know for fact that if $\mu$ is a Radon measure would also be enough (maybe $\sigma$-finite with some regularity properties).

A: There are several easy criterions other than those you have mentioned that,
together with finite additivity,
imply countable additivity (but they all end up implying countable subadditivity in the end).
Here are two examples:
1. If $\mu$ is finitely additive and continuous from below
(that is,
if $A_1\subset A_2\subset\cdots$ and $A=\bigcup_nA_n$,
then $\mu(A_n)\to A$),
then $\mu$ is countably additive: Take $\{A_n\}$ disjoint,
and define $B_n=A_1\cup\cdots\cup A_n$.
Then,
$B_1\subset B_2\subset\cdots$ and $\bigcup_nB_n=\bigcup_nA_n$,
and thus,
finite additivity implies that
$$\lim_{n\to\infty}\sum_{i=1}^n\mu(A_i)=\lim_{n\to\infty}\mu(B_n)=\mu\left(\bigcup_{n}A_n\right).$$
2. If $\mu$ is finitely additive and continuous from above at $\varnothing$ (that is,
if $A_1\supset A_2\supset\cdots$ and $\bigcap_nA_n=\varnothing$,
then $\mu(A_n)\to0$),
then $\mu$ is countably additive:
Take $\{A_n\}$ disjoint,
and define $B_n=A_1\cup\cdots\cup A_n$.
Then,
$\bigcup_nB_n=\bigcup_nA_n$,
and for every $m$,
we have by finite additivity that
$$\mu\left(\bigcup_nA_n\right)=\mu\left(B_m\cup\left(\bigcup_nA_n\right)\setminus B_m\right)=\mu\left(B_m\right)+\mu\left(\left(\bigcup_nA_n\right)\setminus B_m\right).$$
Now,
we see that $\left(\bigcup_nA_n\right)\setminus B_1\supset\left(\bigcup_nA_n\right)\setminus B_2\supset\cdots$,
and that $\bigcap_m\left(\left(\bigcup_nA_n\right)\setminus B_m\right)=\varnothing$.
Thus,
$$\mu\left(\bigcup_nA_n\right)=\lim_{m\to\infty}\left[\mu\left(B_m\right)+\mu\left(\left(\bigcup_nA_n\right)\setminus B_m\right)\right]=\lim_{m\to\infty}\mu(B_m)+0.$$
Since $\mu(B_m)=\sum_{i=1}^m\mu(A_i)$ for each $m$,
this implies countable additivity.

A: user78270's answer is good, but leaves out some details. The following is from Measure Theory by F. R. Halmos, first edition, section 9, page 38. Remark on notation
$
\text{Let $\{E_{n}\}$ be a sequence, then}\\
$
$$
\lim\limits_{n\rightarrow\infty}E_{n} = \bigcap\limits_{n=1}^{\infty}\bigcup\limits_{m\geq n}^{\infty}E_{m} = \bigcup\limits_{n=1}^{\infty}\bigcap\limits_{m\geq n}^{\infty}E_{m}
$$
$\text{i.e. } \lim\limits_{n\rightarrow\infty}E_{n}=\liminf\limits_{n\rightarrow\infty}E_{n}=\limsup\limits_{n\rightarrow\infty}E_{n}$
Theorem:
$\quad$If $\mu$ is a measure on a ring $\mathcal{R}$, and if $\{E_{n}\}$ is an increasing sequence of sets in $\mathcal{R}$ such that $\lim\limits_{n\rightarrow\infty}E_{n} \in \mathcal{R}$, then $$\mu(\lim\limits_{n\rightarrow\infty}E_{n}) = \lim\limits_{n\rightarrow\infty}\mu(E_{n})$$
Theorem:
$\quad$If $\mu$ is a measure on a ring $\mathcal{R}$, and if $\{E_{n}\}$ is an decreasing sequence of sets in $\mathcal{R}$ of which at least one has finite measure and for which $\lim\limits_{n\rightarrow\infty}E_{n} \in \mathcal{R}$, then $$\mu(\lim\limits_{n\rightarrow\infty}E_{n}) = \lim\limits_{n\rightarrow\infty}\mu(E_{n})$$


text:
Q: Invalid Content Type when calling a POST api from azure logic app I have created a Web API using .net core to POST file (excel).
When attaching the file from the post man it is working as expected but now I am trying to do the same using Azure logic app.
I am using a FTP connector and reading the file from it and then calling the REST api, the end point is getting hit but however I am unable to get the file data.
I am very much new to logic apps and tried to find a lot but no luck.
Web API
[HttpPost("x")]
public async Task<IActionResult> MigrateHistoricalData()
{
    int filesCount = HttpContext.Request.Form.Files.Count;
    if (filesCount > 0)
    {
        var file = HttpContext.Request.Form.Files[0];
        if (file != null && file.Length > 0)
        {
            // other logic
        }
     }
    else
    {
         return new BadRequestObjectResult("No files found in the request.");
    }

   return null;
}

Error Image:

A: You could update your browser to the latest version and have a try.
It's a MVC bug, and on 13th of September 2018 Microsoft has implemented a fix for this issue, and it will be released with in ASP.NET Core 2.2.

A: Set content-type of the HTTP request header to multipart/form-data in the Logic App and see if that helps Logic App Http Connector Header


text:
Q: Javascript - Table data from column to column I want to use Javascript (using react.js also) to make a simple converter program with preset values.
I need to:

*

*Find a value in the first column matching the inputted value

*Go along the row by one and take the value from this cell.

For example with this table,

I would like to enter "4" and get the values of Color, and maybe the other columns.
How could I do this and is there any easier way?

A: this is a function that takes 2 parameters. The first one is the value you want to compare with first cell in each row. The second one is the number of a column in which is the value you want to get.
function getCellByFirstRowValue(yourValue, columnNumber) {
    var table = document.getElementById("tableID");
    for (var i = 0, row; row = table.rows[i]; i++) {
        if(row.cells[0].innerHTML == yourValue) {
            return row.cells[columnNumber].innerHTML;
        }
    }
}

alert(getCellByFirstRowValue(1, 2)); // alerts "tests2"
alert(getCellByFirstRowValue(2, 1)); // alerts "tests3"
alert(getCellByFirstRowValue(3, 1)); // alerts "tests5"

Here is a link to a working JSfiddle: https://jsfiddle.net/Lxc7ut3u/


text:
Q: clone git repository in gitlab runner I need help about gitlab runner. I would need to clone an other repository of gitlab where the runner is launched.
For example: CI runner runner-repo-a executed in the repo-a and I need to clone repo-b in runner-repo-a.
Now I have:
GO_CHEF: git.developers.mycompany.com/chef/myrepo-chef-repo.git
[...]
Update databags:
  stage: update
  script:
    - git config --global url."https://gitlab-ci-token:${CI_JOB_TOKEN}@git.developers.mycompany.com:".insteadOf "https://git.developers.mycompany.com"
    - go get -u ${GO_CHEF}

and this is the error:
package git.developers.mycompany.com/chef/myrepo-chef-repo.git: cannot download,
git://git.developers.mycompany.com/chef/myrepo-chef-repo uses insecure protocol

Regards,

A: This error could be due to the https protocol being used in your environment. An easier way would be to just use the SSH version of git clone.
You need to generate an SSH key in the machine from which you are cloning and add that key into GitLab. Please refer this to generate SSH Key , once that is done, refer this to understand how the rsaxxxx.pub is to be added to into GitLab.


text:
Q: How to do a recursive query I have a database table looks like this:
EVENT_ID TEXT_FRO TEXT_TO
55001              05
55001    05        10
55001    10        15
55001    15        20
55001    20        30
56215    06        11
56215    11        22

I need to write a query (or a SP) to produce a result set to list all movements for each distinct event_ID which looks like this:
Event ID Movements
55001    05 10 15 20 30
56215    06 11 22

How can I do that?
*Edit to simplify the example

A: It is pretty straight forward if you use a function and a cursor:
use tempdb
go

create table tmp (
  EVENT_ID int,
  TEXT_FRO varchar(10),
  TEXT_TO varchar(10)
)
go

insert into tmp values
(55001, NULL, '05'),
(55001, '05', '26'),
(55001, '26', '28'),
(55001, '28', '27'),
(55001, '27', '26'),
(55001, '26', '27'),
(55001, '27', '28'),
(55001, '28', '30'),
(55001, '30', '40'),
(56215, '06', '11'),
(56215, '11', '22')
go

You have to create a function to assemble the concatenated string:
create function fnConcat (@id int) returns varchar(255) as
begin
  declare @rtn varchar(255) = '', @fro varchar(10), @to varchar(10), @cnt int = 1

  declare cr cursor local for
    select TEXT_FRO, TEXT_TO
    from   tmp
    where  EVENT_ID = @id

  open cr
  fetch next from cr into @fro, @to

  while @@fetch_status = 0
  begin
    if @cnt = 1 and @fro is not null
      set @rtn = @rtn + @fro + ' '

    set @rtn = @rtn + @to + ' '

    set @cnt = @cnt + 1
    fetch next from cr into @fro, @to
  end

  close cr
  deallocate cr

  set @rtn = left(@rtn, datalength(@rtn) - 1)

  return @rtn
end
go

It is more efficient if you only call the function one time per unique EVENT_ID, so we select the distinct EVENT_ID in a sub-query:
select x.EVENT_ID as [Event ID], dbo.fnConcat(x.EVENT_ID) as Movements
from (
  select distinct EVENT_ID
  from tmp
) as x
go

And then cleanup:
drop table tmp
go
drop function fnConcat
go

This is the result looks like this:
Event ID    Movements
----------- ---------------------------
55001       05 26 28 27 26 27 28 30 40
56215       06 11 22

A: You can do this with a recursive common table expression.
For testing purposes I added a column to the test table that identifies the order of the events in order to be able to identify the first one:
create table movements
(
  event_id   INTEGER,
  text_fro   VARCHAR(10),
  text_to    VARCHAR(10),
  sort_ord   INTEGER
);

insert into movements (event_id, text_fro, text_to, sort_ord)
values
(55001,null,'05',1),
(55001,'05','10',2),
(55001,'10','15',3),
(55001,'15','20',4),
(55001,'20','30',5),
(56215,'06','11',1),
(56215,'11','22',2)
;

with mvt as (
   select m1.event_id as root_id,
          m1.event_id,
          cast(coalesce(m1.text_fro,'') + ' ' + m1.text_to as varchar(8000)) as path,
          m1.text_fro,
          m1.text_to,
          m1.sort_ord
   from movements m1
   where m1.text_fro is null
   or m1.sort_ord = (select min(sort_ord) from movements m2 where m1.event_id = m2.event_id)

   union all

   select p.root_id,
          c.event_id,
          p.path + ' ' + c.text_to,
          c.text_fro,
          c.text_to,
          c.sort_ord
   from movements c
     join mvt p on p.text_to = c.text_fro
)
select root_id, max(ltrim(path)) as movements
from mvt
group by root_id;

Here is a SQLFiddle demo
I'm not sure how to deal with cycles in your event loops though.


text:
Q: Get last battery charge date time from BatterManager How do I get the last charge date/time from Android BatteryManager?
Well maybe it's not BatteryManager but some other API to use for this.
I want to display something like "Charged 2 hours ago".

A: Register a broadcast reciever for ACTION_POWER_DISCONNECTED intent and then you could store the time at which power was disconnected.


text:
Q: "Any linear map near an isomorphism remains an isomorphism", what does this mean? I'm studying a part of Bott-Tu, and I stumbled upon this mystic sentence in the proof of the homotopy property of vector bundles (Theorem 6.8). The "near" part should be intended in the sense of a continuous transformation between linear maps, but does this mean that to be an isomorphism is a somehow stable property for linear maps? It's not something I've dealt with before...
Any help on this is really appreciated.

A: If $V,W$ are a pair of isomorphic vector spaces, the set $GL(V,W)$ of isomorphisms $V \to W$ is open in the space $\mathrm{Hom}(V,W)$ of linear maps $V \to W$, and thus any sufficiently small perturbation of an isomorphism is an isomorphism.
One way to prove this is to fix bases for $V,W$ so that $GL(V,W) \subset \mathrm{Hom}(V,W)$ becomes the set $GL(n,\mathbb R) \subset \mathbb R^{n\times n}$ of matrices (here $n$ is the common dimension of $V,W$), and note that $GL(n,\mathbb R)$ is the preimage under the continuous function $\det$ of the open set $\mathbb R \setminus \{0\}$.


text:
Q: Bash built-in "history" can be executed, but is not in $PATH I know shell builtins are loaded into memory and thought I could find all builtins in /usr/bin or somewhere in echo $PATH. I was trying to find out how the history command works. My assumption was that it is reading from ~/bash_history. So I tried objdump -S $(which history)
which history
echo $?

1

This did not return the path of the command which makes me where the binary for history is located.
type -t which
builtin

I assume this means that it is loaded onto memory. So does a shell process load builtins that are stored outside of echo $PATH

A: A shell builtin is literally built into the shell executable itself. It is invoked by the shell not as a separate process, but simply as a regular function call within the shell process. So if you want to find its source code, you need to look in the source code of bash.
For many builtins, such as cd, the main reason for it being a builtin is that it modifies the state of the shell itself. It would be pointless to have cd be a separate process, as that process would only change its own current directory, not that of the shell process. In the case of history, the reason is presumably that ~/.bash_history is only written when the shell exits, so the command also needs access to the in-memory history of the current session, which is contained within the running bash process. For other builtins, such as echo, the reason is performance: the command is assumed to be so frequently used that we want to avoid spawning a new process every time it is invoked (but if you really do want a process, there is also /bin/echo, which may behave differently).


text:
Q: iOS Local Notification - Callback when in Background Context:
My iOS App uses local notifications
I schedule local notifications and then I get a call back via didRecieveLocalNotifications when the notifications fire.
This works fine when the app is in foreground however when the App goes in the background I get the iOS notification but no call back.
My Question:
How can I get a callback from iOS when the app is in background.
Here is the call back code -
- (void)application:(UIApplication *)application didReceiveLocalNotification:    (UILocalNotification *)notification
{

    //call your method that you want to do something in your app
    NSLog (@"Received Notification");
    [UIApplication sharedApplication].applicationIconBadgeNumber = 1;
    [myRootController HandleLocalNotifications:notification];

}

A: You are describing application:didReceiveLocalNotification:. This is deprecated in iOS 10. You should be updating to the UserNotification framework.
Now then.
If you app is frontmost, the user gets no alert. Instead, you get application:didReceiveLocalNotification:.
If your app is not frontmost, the user gets an alert. Therefore, you do not get application:didReceiveLocalNotification: because the notification fired. But you do get it if the user received the notification and summoned your app by tapping the notification alert. If the user does that, you will get application:didReceiveLocalNotification: even in the background.
If your app was terminated in the background, however, you will get application:didFinishLaunchingWithOptions: (and you can check the options to learn that you're being launched because of the notification).
If your app was in the background or not running, and the user does not tap the notification and summon your app, you will get nothing at all and will have no way to know that the notification fired. This is because notifications are not for your benefit but are a way of sending a message to the user. (It sounds, from your question, as if you may be misusing local notifications as a way of sending a message to yourself. That is not what they are for.)


text:
Q: Chef with rails: Handling asset precompiling during deploy If you're using rails with Sprockets and Opscode Chef, how are you handling asset precompilation during deployment? I want to keep my git history clean, so I don't want do precompile them locally and then commit them to the repository.
The easiest way seems to be to add them to the application cookbook's migration command, but that seems nasty to me. Asset precompilation should be separate from database migrations. Any other suggestions on how to handle this?

A: If you are using the deploy_revision resource, you can stick the rake task to do the asset precompiling into the before_restart block.
Here is the snippet of code that is in my deploy_revision resource. Since I am using RVM, I have installed Fletcher Nichol's amazing RVM cookbook of awesomeness. You could replace this with a ruby-block resource.
Checkout a more complete example in my gist.
 app = node[:rails][:app_name]
 before_restart do
   rvm_shell "assets precompile" do
     ruby_string "#{app[:ruby_ver]}@#{app[:gemset]}"
     cwd release_path
     user app[:deploy_user]
     group app[:deploy_user]

     # TODO I could not set the environment via the builtin command. Does not look like it is getting passed to popen4
     # So instead of `environment "RAILS_ENV" => app[:environment]` I have it in the code block
     code %{
       export RAILS_ENV=#{app[:environment]}
       bundle exec rake assets:precompile
     }
   end
 end


text:
Q: Similar questions scroll sticky/overlap On the Ask A Question page, the Similar Questions sometimes has a visual bug that the initially displayed content remains in place when scrolling, and the scrolled content is superimposed.  Examples (Firefox 70.0.1 64-bit on Windows 10):

I can't quite nail down the specific conditions that cause this to occur, but it might have something to do with clicking away from the Ask A Question page and then clicking back to it.


text:
Q: What is the benefit of setting android:constantSize to 'true' in a StateListDrawable? If you have ever had to make you own custom buttons for Android then you will have used a StateList Drawable; or you should have. Now if you look at the Android documentation for StatList Drawables then you will see that there is an option called "android:constantSize" that is said to behave like this:

Boolean. "true" if the drawable's reported internal size remains constant as the state changes (the size is the maximum of all of the states); "false" if the size varies based on the current state. Default is false.

Now that is all well and good. I think it is telling me that if the size of the image does not change in any of the states then you should set this to true. My question would be: what benefit does setting this value to true have? Does it speed up rendering times? Is it more efficient in the background?
Essentially, what benefit will setting this attribute to true give me?

A: When the flag is set, the drawable computes a constant size once and uses that for all queries about its size. When the flag is not set, it queries the current drawable each time for its intrinsic width.