text:
Q: Stuck at converting/implementing Qt (.ui) files to Qtjambi(.jui) files Edit 01.02.2012:

FWIW: 4.7.0 linux packages are broken AFAIK, they
     can be fixed or 4.6 packages used   instead...
     No need to use
     custom Qt for Jambi – Smar 2 days ago
Thanks to SMAR, I was finally able to resolve this
   issue by downloading the an older version of
   qtjambi 4.6.3 ( http://qt-jambi.org/downloads/ ). The only problem was that the
   designer did not know where to find my jvm which
   I solved by adding these two entries to /etc/bash.bashrc:

  # custom PATH exports
    export JAVA_HOME=/usr/lib/jvm/java-6-sun
    PATH=$PATH:$JAVA_HOME/bin

Then I just had to run (everything was in the qtjambi-folder):
  designer.sh --> save it as .jui --> convert it with juic into a .java file --> and load it with netbeans :)
Hope this is somehow helpful to others too.
Thanks for the great and fast help!

Original post:
Good evening,
I am not completely sure if this topic is enough about programming but I am having some problems setting up Qtjambi. I have followed a lot of "howtos" and instructions so I am a little confused about what to do next. Qtjambi works as I have written a example program with netbeans. Although I have created some ui files that I want to implement which doesnt work.
I am trying to get this to run for like a week and I really need this because of my finals in 2 months. I try to give as much useful  details as possible.
I am using LinuxMint (ubuntu derivate), downloaded qtjambi v 4.7.0
after trying out
bash qtjambi.sh

I got an error of mismatching versions
Cannot mix incompatible Qt library (version 0x40704) with this library (version 0x40700)

So I downloaded, compiled and installed
qt-everywhere-opensource-src-4.7.0  to   /usr/local/Trolltech/Qt-4.7.0/
I know that I have to tell the system where to find all the binarys so I added to the /etc/bash.bashrc
    #custom PATH exports
    PATH=$PATH:/home/michi/Scripts
    PATH=$PATH:/usr/local/Trolltech/Qt-4.7.0/bin/

    export LD_LIBRARY_PATH=/usr/local/Trolltech/Qt-4.7.0/lib
    export QT_PLUGIN_PATH=/usr/local/Trolltech/Qt-4.7.0/plugins

    JAVA_DIR=/usr/lib/jvm/java-6-sun-1.6.0.26/
    export JAMBI_PATH=/usr/local/lib/qtjambi-linux64-community-4.7.0/

I followed through the instructions of:
    http://www.davidlauzon.net/2010/01/getting-started-with-qt-jambi-on-linux/
    Which generally talks about getting jambi-designer to work.

    http://jpnurmi.kapsi.fi/blog/2008/03/16/how-to-switch-qt-version-in-ubuntu/
    How to manage multiple Qt versions.. These commands worked but had no effect

I finally gave up on trying to run the designer and tried to "convert" the .ui files to .jui files with the program juic which is located in the qtjambi/bin folder. But also here I get an error:
    michi@BALMORA ~/Documents/unterlagen/pr_scw/Qt/Qtrainer/test $ which juic
    /usr/local/bin/juic
    michi@BALMORA ~/Documents/unterlagen/pr_scw/Qt/Qtrainer/test $ juic -cp .
    juic: no .jui files found in CLASSPATH

     michi@BALMORA ~/Documents/unterlagen/pr_scw/Qt/Qtrainer/test $ /usr/locallib/qtjambi-linux64-community-4.7.0/bin/juic -cp .
    juic: no .jui files found in CLASSPATH

It would be great if you could help/guide or redirect me to "better" instructions.
Michael Kargl


text:
Q: Does $P[X_j\in I_n]=0$ imply that $\delta_{X_j}(I_n)=0$? Does $$P[X_j\in I_n]=F(I_n)=0, j=1,...n$$
imply that
$$\hat F_n(I_n)=\frac{1}{n}\sum_{i=1}^n\delta_{X_i}(I_n)=0$$,
here $I_n$ are open intervals $(a_n,b_n)$ on which $F(a_n)=F(b_n)$ and $\delta _X$ denotes the dirac measure.
What if we have that $X_j\in I_n$ for a countable number of $\omega$; then the measure of the set would be zero, right? But but $\delta _{X_j}(I_n)$ would equal 1. Is something wrong with my reasoning?
Thanks in advance!

A: Note that $E[\hat F_n(A)]=\frac1n\sum\limits_{k=1}^nF_k(A)$ and that $\hat F_n(A)\geqslant0$ almost surely. Hence, if $F_n(A)=0$ for every $n$, then $\hat F_n(A)=0$ almost surely. Thus, $\delta_{X_n}(A)=n\hat F_n(A)-(n-1)\hat F_{n-1}(A)=0$ almost surely, for every $n$.
(Of course, this does not prevent $\delta_{X_n}(A)(\omega)=\mathbf 1_{X_n(\omega)\in A}$ to be nonzero for some $\omega$ in $\Omega$ and some $n$ but these $\omega$ would be exceptional in the sense that the set $\{\omega\in\Omega\mid\exists n,\,X_n(\omega)\in A\}$ has measure zero.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compute function to create variable that meets multiple conditions I'm trying to write syntax in SPSS that uses the compute variable command to create a new variable that looks at 5 other scale variables and finds the minimum variable among the five with a value greater than or equal to 0.80.
For example,
        CAT1 CAT2 CAT3 CAT4 CAT5
CASE 1  0.75 0.82 0.85 0.90 0.95
CASE 2  0.65 0.75 0.82 0.87 0.95

For case 1, the computed variable would return a value of 2.  For case 2, it would return a value of 3.
I'm stumped -- originally I thought it would work with a conditional MIN statement, but it's not working.  Thinking it might need an IF/THEN, but I'm hoping someone has a more efficient solution.  Thanks.

A: Several answers were already provided on the SPSSX-L list.

A: this syntax will leave a zero in NewVar if all the categories are less than 0.8:
*creating sample data.
data list  list/ CAT1 to CAT5.
begin data
0.75 0.82 0.85 0.90 0.95
0.65 0.75 0.82 0.87 0.95
end data.

*calculating NewVar: the index number of the minimum category that is GE 0.8.
compute NewVar=0.
compute #tmp=max( CAT1 to CAT5)+1.
DO REPEAT cat=cat1 to cat5 / VL= 1 to 5.
  do if cat>=0.80 .
      if cat<#tmp NewVar=VL.
      compute #tmp=cat.
  end if.
END REPEAT.
EXECUTE.


text:
Q: How to create azure backup policy using CLI? I can't find a way to create my custom backup policy via CLI https://learn.microsoft.com/en-us/cli/azure/backup/policy?view=azure-cli-latest
However, this can be done via REST API call https://learn.microsoft.com/en-us/azure/backup/backup-azure-arm-userestapi-createorupdatepolicy

A: Actually it supports, but the official doc is missing instructions, also the REST API indicates the create and update uses the same api.

You could try the command as below, it works fine on my side.
az backup policy set --policy '{
  "name": "testpolicy3",
  "properties": {
    "backupManagementType": "AzureIaasVM",
    "instantRpRetentionRangeInDays": 2,
    "protectedItemsCount": 0,
    "retentionPolicy": {
      "dailySchedule": {
        "retentionDuration": {
          "count": 180,
          "durationType": "Days"
        },
        "retentionTimes": [
          "2019-07-09T07:30:00+00:00"
        ]
      },
      "monthlySchedule": {
        "retentionDuration": {
          "count": 60,
          "durationType": "Months"
        },
        "retentionScheduleDaily": null,
        "retentionScheduleFormatType": "Weekly",
        "retentionScheduleWeekly": {
          "daysOfTheWeek": [
            "Sunday"
          ],
          "weeksOfTheMonth": [
            "First"
          ]
        },
        "retentionTimes": [
          "2019-07-09T07:30:00+00:00"
        ]
      },
      "retentionPolicyType": "LongTermRetentionPolicy",
      "weeklySchedule": {
        "daysOfTheWeek": [
          "Sunday"
        ],
        "retentionDuration": {
          "count": 12,
          "durationType": "Weeks"
        },
        "retentionTimes": [
          "2019-07-09T07:30:00+00:00"
        ]
      },
      "yearlySchedule": {
        "monthsOfYear": [
          "January"
        ],
        "retentionDuration": {
          "count": 10,
          "durationType": "Years"
        },
        "retentionScheduleDaily": null,
        "retentionScheduleFormatType": "Weekly",
        "retentionScheduleWeekly": {
          "daysOfTheWeek": [
            "Sunday"
          ],
          "weeksOfTheMonth": [
            "First"
          ]
        },
        "retentionTimes": [
          "2019-07-09T07:30:00+00:00"
        ]
      }
    },
    "schedulePolicy": {
      "schedulePolicyType": "SimpleSchedulePolicy",
      "scheduleRunDays": null,
      "scheduleRunFrequency": "Daily",
      "scheduleRunTimes": [
        "2019-07-09T07:30:00+00:00"
      ],
      "scheduleWeeklyFrequency": 0
    },
    "timeZone": "UTC"
  },
  "resourceGroup": "joywebapp",
  "tags": null,
  "type": "Microsoft.RecoveryServices/vaults/backupPolicies"
}' --resource-group 'joywebapp' --vault-name 'joyvault'


text:
Q: No match for 'operator=' in sort function I'm trying to have a program write out all permutations of a string. Here is my code:
#include <stdio.h>
#include <string>
#include <iostream>
#include <algorithm>

using namespace std;

int main () {
    string input;
    int length;
    cin >> input;
    input = sort(begin(input), end(input));
    length = input.length();
    do {
        cout << input;
        cout << "\n";
    } while (next_permutation(input,input+length));
}

However, I get the following error:
[path removed]\PermutIO.cpp|12|error: no match for 'operator=' in 'input = std::sort<__gnu_cxx::__normal_iterator<char*, std::basic_string<char> > >(std::begin<std::basic_string<char> >((* & input)), std::end<std::basic_string<char> >((* & input)))'|

I am using Code::Blocks with g++ and have set it to use the C++11 standard. What seems to be the problem?

A: This line is malformed because std::sort returns void.
input = sort(begin(input), end(input));

You can not assign void to a std::string.
Remove input = from that line.  It's not needed.

A: The sort method itself returns a void, so what you're trying to do is assigning string to void.
Just write sort(begin(input), end(input)) instead.
Update:
Well, let's analyze the error message that your compiler gives:
error: no match for 'operator=' in 'input =
std::sort<__gnu_cxx::__normal_iterator<char*, std::basic_string<char> > >
(std::begin<std::basic_string<char> >((* & input)),
std::end<std::basic_string<char> >((* & input)))'

The last 3 lines might seem difficult and hard to understand, but the most important thing here is the first line:
no match for 'operator=' in 'input = ...

That means that the compiler can't find a rule, that can allow you to assign the input to something in the right side. So, now, when we've already know that the problem is in the assigning value, the debugging proccess is much simpler - we have to find what type of value does the sort method returns, we can do that simply by using google.


text:
Q: How can I get an ASP.NET Session variable into a javascript file? I am refactoring a legacy web app. This app has a is using the onload event inside the body tag (On the Master page) to run this javascript script. Note this script tag is after the form element in the doc. I know the syntax looks hideous (or Visual Studio at least tells it is by the squiggles), but I'll be darned, the thing DOES indeed work.
function DisplayPDF()
{
    var strPDF
    strPDF = "<%=SESSION("PDF")%>";
    if (strPDF.length != 0)
     {
        window.open(strPDF);
        <%Session("PDF") = ""%>
     }
}

My question is I'm trying to develop a more elegant solution. I have ASP.NET ajax and jQuery both available to me. I wrote a tiny asp.net ajax component that I want to use to handle this.
Type.registerNamespace("ck");

ck.pdfOpener = function() {
  ck.pdfOpener.initializeBase(this);
}

ck.pdfOpener.prototype = {
    initialize: function() {
        ck.pdfOpener.callBaseMethod(this, 'initialize');
    },

    dispose: function() {
        ck.pdfOpener.callBaseMethod(this, 'dispose');
    },

    openPDF: function(){
       //HOW CAN I RETRIEVE A SESSION VARIABLE HERE???
    }
}

ck.ClientControl.registerClass('ck.pdfOpener', Sys.Component);
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

Can/Should I be doing it this way? Or should I create a WebService that returns said variable. Thanks for any advice.
Cheers,
~ck in San Diego

A: Use the Page.ClientScript.RegisterClientScriptBlock(typeof(YOURPAGECLASS), "KEY", "ACTUALJSCODE"); in your code behind (i.e. the Page_Load event handler)

A: Alternatlively, you could send the PDF file directly from the asp.net page instead of within the client script.
string pdfFile = Session("PDF");
if (!string.IsNullOrEmpty(pdfFile))
{
  Session.Remove("PDF");

  Response.ContentType = "application/pdf";
  FileInfo fi = new FileInfo(pdfFile);
  Response.AddHeader("Content-Disposition", "attachment; filename=\"" + Path.GetFileName(pdfFile) + "\"");
  Response.AddHeader("Content-Length", fi.Length.ToString());
  Response.WriteFile(pdfFile);
  Response.Flush();
  return;
}

A: A simple way to do this would be as you said simply make an Ajax call to a page method, MVC action, HttpHandler or web service that returns the required value from the session.  The bigger question here is why you are storing the path to a PDF file in your session state?


text:
Q: Save radio button value into a variable using AMPscript I'm quite new AMPscript, the problem I'm facing is I want to store the radio button value into a variable then I want to display that variable please someone help me.

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>JavaScript Radio Button</title>

    <form
      id="dashform"
      action="%%=RequestParameter('PAGEURL')=%%"
      method="post"
    >

        <input type="radio" name="option" value="reason_1" id="reason_1" />
        I never signed up, or didn't realize I had signed up, for your email list.

        <input type="radio" name="option" value="reason_2" id="reason_2" />
        Your content isn't relevant to me.

        <button id="btn">Select your option</button>

    </form>


text:
Q: displaying data from two tables in one grid I have a grid for my admin module and it works fine, but I now would like to add more data onto that grid, but the additional data is held in a second table in my database.
To display this additional data I have tried
protected function _prepareCollection()
{
    $collection = Mage::getModel('modulename/modelname')->getCollection();
    $collection->join(array('table2' => 'table1'), 'table1_id = table2_id', 'unsubscribed');//additional line
    $this->setCollection($collection);
    return parent::_prepareCollection();
}

protected function _prepareColumns()
{
    $this->addColumn('table1_id', array(
        'header'    =>  $this->__('ID'),
        'align'     => 'left',
        'width'     => '50px',
        'index'     => 'table1_id',
    ));

    $this->addColumn('salutation', array(
        'header'    => $this->__('Title'),
        'align'     => 'left',
        'index'     => 'salutation',
        'width'     => '80px',
    ));

    $this->addColumn('f_name', array(
        'header'    => $this->__('First Name'),
        'align'     => 'left',
        'index'     => 'f_name',
        'width'     => '100px',
    ));

    $this->addColumn('l_name', array(
        'header'    => $this->__('Last Name'),
        'align'     => 'left',
        'index'     => 'l_name',
        'width'     => '100px',
    ));

    $this->addColumn('subscribed', array(
        'header'    =>  $this->__('Subscribed'),
        'align'     => 'left',
        'width'     => '80px',
        'index'     => 'Subscribed',
        'type'      => 'options',
        'options'   => array(
            0 => 'Subscribed',
            1 => 'Not Subscribed',
        ),
    ));//additional column

table1 has table1_id, salutation, f_name, l_name
table2 has table2_id, subscribed
First I added the new column and that displayed fine, then I added the join statement, but that returned an

Integrity constraint violation: 1052 Column 'table1_id' in on clause is ambiguous

So its obviously something to do with $collection->join() but what have I done wrong? I wasn't sure if it was due to the order I place the tables but reordering them failed, i'm obviously missing something
===EDIT===
$collection = Mage::getModel('module/model')->getCollection();
$collection->getSelect()->join( array('options'=>$this->getTable('module/table2')),'main_table.table1_id = options.table2_id','options.*');

A: When joining a table to a collection you'll have to use a prefix for the fields so every field is unique in the query.
$collection->getSelect()->join( array('options'=>'table2'),'`main_table`.`table1_id` = `options`.`table2_id`','`options`.*');

tbl2 is the Alias of table2 in this case which will give you a query like:
SELECT main_table.*, tbl2.unsubscribed FROM table1 AS main_table INNER JOIN table2 AS tbl2 ON main_table.table1_id = tbl2.table2_id
Print the query to check if prefixes are added on all the fields and to check for any other issues.
var_dump((string)$collection->getSelect());

You can check this Magento wiki page for a brief explanation on joining


text:
Q: How to find all the points in time series data were new lows were made? So I have a set of data, which is AMD stock prices and the code looks like the following:
import pandas as pd
import pandas_datareader as web
import datetime as dt

#get stock prices
start = dt.datetime(2017, 1, 1)
end = dt.datetime(2020, 1, 1)
d = web.DataReader('AMD', 'yahoo', start, end)

So know my question is, what code would be able to find out every time the stock ( so in other words d['Adj Close']), made a new 52 week low. So then you would be able to print the price of the stock everytime this happened. Thank You

A: # import packages, seed numpy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.seed=42

Generate mock data
Timestamps and price data as list:
timestamps = ['timestamp'+str(x) for x in range(20)]
price = [np.random.normal(100,10) for _ in range(20)]

Put them to a Pandas dataframe:
df = pd.DataFrame({'timestamps':timestamps,'price':price})

Look for lows
Let's define window. Every time the code considers a datapoint, it will consider window-many datapoints before it (not including itself).
window=3

Iterate through price, checking if the current price is the lower than any of the window-many prices before. Save the indices of those datapoints for which this is True:
indices=[]
for index, row in enumerate(df.iterrows()):
    if index >= window:
        if all(df.loc[index,'price'] < each for each in df[index-window:index]['price'].values):
            indices.append(index)

Or, if you prefer list comprehensions:
indices = [index for index, row in enumerate(df.iterrows()) if index>=window and all(df.loc[index,'price'] < each for each in df[index-window:index]['price'].values)]

Check results
Let's plot the data & our findings to make sure it is right. We will plot the lows as vertical lines on our plot.
df.plot()
for index in indices:
    plt.axvline(index,c='r')

Resulting in:

Which is what we have expected.


text:
Q: How can I correctly install Bochs on OSX Sierra v10.13.4? The path I took was using sh .conf.macos. After that, I tried sudo make and I get an error
../bochs.h:75:12: fatal error: 'types.h' file not found
#include <types.h>
using ./configure didn't help much because when I would make, I get a whole bunch of errors generated from carbon.cc. If I understand correctly, carbon.cc is deprecated but how do I deal with this?
I've tried this with both Bochs 2.6.8 and the latest SVN dated April 2, 2018.

A: I had similar problems while compiling bochs on MacOs.  I saw lots of header not found problems. I tried with brew and it works.
Please use:
 brew install bochs


text:
Q: Сбор данных для машинного обучения Есть набор параметров который собирается. Условно 1..n, однако некоторые параметры при сборе собрать не получилось. Для наглядности
1; 23; 100; 23;12; 432; 2;4
-; 123; 23; 17;67; 567;45;435
93; -; 324; 131;3; 213; 2; 233

Как поступить в таких ситуациях? Отбрасывать всю строку? Заполнять средним значением? Заполнять 0 значением?


text:
Q: How to properly create an Alea GPU project? Errors on "Getting Started" code I have done the following to create an Alea GPU project in Visual Studio 2012 Professional:

*

*File > New > Project > F# Application

*Updated NuGet Package Manager to latest version

*Tools > NuGet Package Manager > Console

*PM> Install-Package Alea.CUDA

*PM> Install-Package Alea.CUDA.IL

*Installed license using these instructions: http://quantalea.com/static/app/tutorial%5Cgetting_started%5Cinstall_license.html

*Copied the code from here https://github.com/quantalea/AleaGPUTutorial/blob/master/src/fsharp/getting_started/ParallelSquare.fs into my main project file.

*Build Solution.

I get the following errors:

*The lines numbers and file from the GitHub link above correspond with each other.

I'm new to using Alea GPU, Visual Studio, and F#.  I've tried doing what I could with the resources I have available.  Although the the Alea GPU website explains what to do (install Alea through NuGet, install license, provides code, etc.) it might be targeted to users who have experience working with Visual Studio.  It's also worth mentioning I have CUDA drivers installed on this machine.
I have also followed the instructions on this page, but it seems like it's still under construction: http://quantalea.com/static/app/tutorial%5Cgetting_started%5Ccreate_new_project.html.  I'm not using Fody since I won't be using C#.

A: Thanks for reporting the web site problem. Yes, our document are under constructing. I tried your steps and I figured out how to do it correctly, which I will show you later. The issues you met are mainly because:

*

*You are using VS2012, which by default referencing FSharp 3.0, which is a little out-of-date, we suggest to use FSharp 3.1

*You forget to reference other assemblies which is used in the code, such as NUnit and FSharp.Charting

*Alea.CUDA.Fody doesn't means to work with C#, it means to do AOT compile on GPU code. It uses Fody plugin to compile GPU code during MSBuild process, so your appliction doesn't need to compile GPU code in runtime.

Now, here are the steps:

*

*Open VS 2012, upgrade nuget plugin, then new F# console application project

*Expand "References" in solution explorer, and remove the FSharp.Core reference (since it is FSharp 3.0, we will replace it with new 3.1)

*Go to "Package Manager Console", install some nuget packages which is used in the code:

*

*Install-Package FSharp.Core

*Install-Package FSharp.Charting

*Install-Package NUnit

*Now we will install Alea.CUDA.Fody (which will install Alea.CUDA by dependency). But since Fody plugin has to run some powershell script to create an FodyWeavers.xml file to configure Fody usage, and this script doesn't work well with F# project (it works with C# project). The workaround is simple, just click "save all" in VS2012 before you run Install-Package Alea.CUDA.Fody. You will see some red error in the package manager console, that is fine, it is just the Fody plugin's script doesn't work well with F# project. You can safely ignore it. After install Alea.CUDA.Fody, a file FodyWeavers.xml file will be added to your project, there you can configure how you will do the AOT compilation. I suggest you add a setting to show verbose information: <Alea.CUDA Verbose="true"/>

*Now you need add some common references, since the package FSharp.Charting uses them. To do that, right click your "References" in solution explorer, and choose "Add Reference...", under "Assemblies" -> "Framework", select these assemblies:

*

*System.Drawing

*System.Windows.Forms

*System.Windows.Forms.DataVisualization

*Now your project is set. Please Change the building configuration to "Release".

*Now let's add the source file. First right click Program.fs in solution explorer, and select "Add above" -> "New Item...", select F# source file, name it ParallelSquare.fs

*Copy https://github.com/quantalea/AleaGPUTutorial/blob/master/src/fsharp/getting_started/ParallelSquare.fs into that new created file

*You need modify one place: https://github.com/quantalea/AleaGPUTutorial/blob/master/src/fsharp/getting_started/ParallelSquare.fs#L139 , change this to WorkerExtension.Launch(worker, <@ squareKernel @>) lp dOutputs.Ptr dInputs.Ptr inputs.Length , the reason is, the Launch method is an extension method, which the FSharp compiler in VS 2012 doesn't support it well, so we call that extension method directly (So I suggest you to use VS 2013).

*Now in your Program.fs file, call the test in main function: Tutorial.Fs.quickStart.ParallelSquare.squareChart(). and then you can press "F5" to run it.

After this, I suggest you read http://quantalea.com/static/app/manual/compilation-index.html where explains the intallation, the AOT vs JIT compilation, etc.


text:
Q: Functions in R - General properties I'm very new to R, I come from a VBA background.
If I understand it correctly, you cannot make procedures ( subs ) in R as you can in VBA or VB? How do I make a functino which just runs as a procedure? I'm trying on the code below, but is there any way it can just run as is, or do I have to have parameters within the function?
pgraf <- function () {

  library(ggplot2)

  dframe <- data.frame( x = c(3,1,5), y= c(2,4,6), label = c("a", "b", "c"))

  p <- ggplot (dframe, aes(x, y, label = label)) + xlab(NULL) + ylab(NULL)
  p <- p + geom_point() + opts(title="geom_point")

  return (pgraf)
}


text:
Q: MySQL "greater than" condition sometimes returns row with equal value I'm running into a baffling issue with a basic MySQL query.
This is my table:
id | rating
1  | 1317.17
2  | 1280.59
3  | 995.12
4  | 973.88

Now, I'm attempting to find all rows where the rating column is larger than a certain value. If I try the following query:
SELECT * FROM (`users`) WHERE `rating` > '995.12'

It correctly returns 2.
But, if I try
SELECT * FROM (`users`) WHERE `rating` > '973.88'

it returns 4! So it's as if it thinks the 973.88 in the table is greater than 973.88, but it doesn't make the same mistake with 995.12. This happens regardless of whether I run the query from a PHP script or in phpMyAdmin.
Any ideas?

A: Decisions and consequences
This is the consequences that you've got because you decided to use floating-point data type. Floats are not precise. And that means: yes, you can result in a>a = true
For instance, your fourth row:

mysql> SELECT *  FROM t WHERE id=4;
+------+--------+
| id   | rating |
+------+--------+
|    4 | 973.88 |
+------+--------+
1 row in set (0.00 sec)

I've left data type as you've posted, it's FLOAT. Here we are:

mysql> SELECT rating>973.88 FROM t WHERE id=4;
+---------------+
| rating>973.88 |
+---------------+
|             1 |
+---------------+
1 row in set (0.00 sec)

Oops!

Behind the screen
Why? To understand why it is so, you should realize how floating-point data type is represented. Long story is here. But - I'll take a brief overview.
Here how it is represented:  where:

*

*s is the sign

*b is the base. It's meaning is same as radix

*e is the exponent.

That means we can represent one number in different ways - and that depends of which base we'll chose. Most common is b=2. But not all real numbers can be represented exactly with this base, even if in decimal base they look "good". Famous example is 0.1 - which can not be represented in b=2 precisely - so it is stored approximately. Again, long story you can see here - but I'll just note, that it's impossible to represent it precisely with base 2.
The result is: even if number is precise in decimal radix, it still may be impossible to represent it precisely - and, therefore, it will be stored approximately. That's how it works and, in fact, this is intended - because of structure of floats itself.

What to do
Fixed precision
Well, first, you should ask yourself: do you really need float? Attention: I said: float. Because - there are also fixed point numbers. They will represent number with fixed precision. To say it easy: with fixed-point data type you may be sure that you'll store exactly what you see on the screen. So if it's 973.88 - then it's 973.88 and not 973.8800000439234. Moving to the deal:

mysql> ALTER TABLE t CHANGE rating rating DECIMAL(8,2);
Query OK, 4 rows affected, 4 warnings (0.47 sec)
Records: 4  Duplicates: 0  Warnings: 4

and ..

mysql> SELECT rating>973.88 FROM t WHERE id=4;
+---------------+
| rating>973.88 |
+---------------+
|             0 |
+---------------+
1 row in set (0.00 sec)

TADA! Magic happens. Your number is now stored with fixed precision, thus, such comparison failed.
Using float
Then, may be there are use-cases when you're stuck with floats (however, in case of DBMS it's hard for me to remember even one such use-case - if only not the case with large amount of calculations, which may cause performance impact, see description below). Then there's still a way to make it work. You should decide what precision is applicable for you. That is: from which point will you treat numbers as equals.
You're storing only two significant digits, so I assume that precision of 1E-5 would be more than enough. Then, your query will look like:

mysql> set @eps=1E-5;
Query OK, 0 rows affected (0.00 sec)

and use it with:
SELECT * FROM t WHERE rating>973.88+@eps

which will result in

+------+---------+
| id   | rating  |
+------+---------+
|    1 | 1317.17 |
|    2 | 1280.59 |
|    3 |  995.12 |
+------+---------+

Which is better?
To realize this, you'll need to look under cover once again. I've given a brief overview of what float data type is and why it isn't precise. However, fixed data type also has it's weakness. May be it's not the thing of which we should worry in context of DBMS, but I'll mention it: fixed data type, in general, will cause performance impact. And it will depend of how much calculations will you do in your DBMS.
In MySQL, fixed-point data types (such as DECIMAL) are implemented as BCD strings (so to make long story short - again, here's wiki link). That means in comparison to float it will cause performance issues. But if you're not going to do calculations in DBMS too often, then that impact won't be even noticeable - I've mentioned it because both types, float- and fixed-point have their own issues.

Conclusion
DBMS, like all the other computer stuff, isn't perfect. It's just using some internal things to do the work. That means: in some cases you'll have to realize how that internal things work to understand why did you got some odd result.
In particular, floats are not precise. Yes, there are tons of answers like this in the Internet, but I'll repeat. They are not precise. You should not rely on precision when it's about floats. And - in almost all DBMS there are fixed-point data types. And - in cases like yours you should use them. They will do just same work, but with them you'll be sure about selected precision.
However, you may want to use floats - if you're going to make too much calculations in your DBMS. But, on the other hand, that is about - why are you going to do that? Why do not use application to produce those calculations (and, therefore, avoid both performance impact of using fixed-point data-types and presicion problems with floats - because using fixed-point with average amount of calculations is ok)

A: @Hituptony is correct. Try this:
SELECT * FROM (`users`) WHERE `rating` > 973.88

SQL FIDDLE

A: You do not need the single quotes when you're comparing numbers.
Take the single quotes off and try again.
However, this has been noted as something you can solve with ROUND(SUM(column), 2) * 1
if the single quotes don't work, compare it to the value of this ^^
See link: https://dev.mysql.com/doc/refman/5.0/en/problems-with-float.html


text:
Q: a function which is 1. easy to compute and 2. equal to 1 inside a interval, and quickly transitions to zero towards the boundaries I need a function which has a plot more or less like this:
Basically, I need something which "smooths out" the indicator function of an interval, and which transitions to 0 at a calibratable rate.
The bump function times $e$, as it is, doesn't work, because the transition from 1 to 0 at the boundaries is too gradual. EDIT: I found out that changing the numerator of the argument of the exponential, i.e., going from
$$\exp\left(-\frac{1}{0.25-x^2}\right)$$
to
$$\exp\left(-\frac{0.001}{0.25-x^2}\right)$$
works perfectly:

so I could as well as close the question now :) However, I'm still curious how this is done usually in (applied?) mathematics. I don't need strictly compact support, i.e., my function needs only to asimptotically vanish, but it doesn't need to be exactly equal to zero anywhere on the real line. Thus the following function works:
$$\frac{1}{(1+\exp(-100(x+0.5))(1+\exp(-100*(x-0.5))}$$
Is it usual to use this kind of function to "smooth out" the indicator function, or is it more common to use the bump function? I seem to remember that during university we were shown a lot of functions with a similar graph, so it must be something quite common, but I can't recall their expressions.

A: You could do a convolution with a small mean-preserving filter. The convolution of two continous functions can be defined:
$$(f*g)(t) \overset{def}{=} \int_{-\infty}^{\infty}f(\tau)g(t-\tau)d\tau$$
And for discrete functions:
$$(f*g)[n] \overset{def}{=} \sum_{m=-\infty}^{\infty}f[m]g[n-m]$$
A famous and easy to understand category of such filters to convolve with is the family of self-convoluted constants related to splines, pascals triangle, combinatorics, interpolation and many other things. Sometimes the convolution is called a convolution-product. In this sense if we let $o$ denote the exponent in this multiplicative sense we can write $f^{(*o)}(t) = (f\underset{o-1 \text{ times}}{\underbrace{*\cdots*f}})(t)$
$$\text{First few self convoluted mean-preserving filters}\cases{f^{(*1)} (t) = f(t)\\f^{(*2)}(t) = (f*f)(t)\\f^{(*3)}(t) = (f*f*f)(t)\\f^{(*4)}(t)= (f*f*f*f)(t)}$$
Where $f$ is the (blue) function - constant on an interval and 0 everywhere else.

These can then be convolved with your big square to produce a "smoothing" effect. In practice you only need to calculate the convolution wherever the smaller filter overlaps two distinct values of the piecewise constant function. Since these are self convoluted by construction and your test function is ac constant, you can actually see the transition right in this image.


text:
Q: Deploy Rule Service WSO2 Business Rule Server I was trying to deploy a rule service with WSO2 Business Rule Server
I exactly followed this link
http://docs.wso2.org/wiki/display/BRS200/Creating+and+Deploying+the+Rule+Service#CreatingandDeployingtheRuleService-RuleServiceWizard
I also made the jar file from 3 different class files:
OrderAccept.class OrderReject.class and PlaceOrder.class
I am trying to deploy the server with wizard in the end I got this error
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask. runPeriodic(ScheduledThreadPoolExecutor.java:181)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.
run(ScheduledThreadPoolExecutor.java:205)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExec
utor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:907)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.ClassNotFoundException: Class Not found : samples.userguide
.PlaceOrder
at org.apache.axis2.deployment.DeploymentClassLoader.findClass(Deploymen
tClassLoader.java:92)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at org.apache.axis2.deployment.DeploymentClassLoader.loadClass(Deploymen
tClassLoader.java:280)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at org.wso2.carbon.rule.common.config.HelperUtil.processFactDefaultValue
s(HelperUtil.java:43)

Anyone could help me where I might make mistakes?

A: It seems your jar files are not properly picked. One reason I can think of it, your axis2 archive has wrong folder structure. I am talking about the rule service upload mechanism. You may see there is a folder structure recommended in the documentation. After creating the .aar file, extract it and see whether you have the same folder structure. If it differs from the recommended one, your jar files will not get picked.

A: I've tried the same example and it's also giving me the same error(both methods, Rule service Upload and Rule Service Wizard). The folder structure that @Amila was suggesting seems to be ok according to the documentation. What I recently found is this link http://wso2.com/library/articles/2013/05/eclipse-plugin-wso2-business-rules-server from which I quote "Previously WSO2 BRS artifacts (aar/car) were created using the web UI rule wizard or creating the artifact by combining several artifacts. With the new WSO2 Developer Studio plug-in for rule services, one can easily create a complete deployable BRS artifact using the Eclipse IDE. Developers can easily create WSO2 BRS artifacts using this tool, and deploy it in the WSO2 Business Rules Server." What I'm guessing is that this new method/tool would substitute the "old" methods(upload and wizard). Give it a try.


text:
Q: How to vertically center action buttons in a shiny app? I have two buttons that I have horizontally centered in my column, but haven't been able to figure out how to vertically center as well. I tried using "vertical-align- middle." Here is my UI code below:
ui <- shinyUI(fluidPage(
  tags$style(
    HTML('
         #buttons {
         background-color:yellow; position:fixed; margin-bottom:50px; vertical-align: middle; opacity:1; height:50px; z-index:5;
         }

         #fluidrow1 {
        height:50px;
         }

         ')
    ),
    fluidRow(id="fluidrow1",
      column(12, align="center", id="buttons",
             actionButton("test1", "Test1"),
             actionButton("rmd2", "RMD2")
      )
    )
  ,uiOutput("uioutput")

))

When I tried to do the first button individually, using the following code:
 #test1 {
        height:50px; vertical-align: middle;
         }

I end up getting a really weird looking UI with both buttons centered, but one is large and is the height of the entire column div.

A: You can do this by:
 display: flex;
 align-items: center;
 justify-content: center;

instead of vertical-align: middle;
So it will be something like:
library(shiny)

ui <- shinyUI(fluidPage(
  tags$style(
    HTML('
         #buttons {
         background-color:yellow; position:fixed; margin-bottom:50px; opacity:1; height:50px; z-index:5;
         display: flex;
         align-items: center;
         justify-content: center;
         }

         #fluidrow1 {
        height:50px;
         }

         ')
  ),
  fluidRow(id="fluidrow1",
           column(12, align="center", id="buttons",
                  actionButton("test1", "Test1"),
                  actionButton("rmd2", "RMD2")
           )
  )
  ,uiOutput("uioutput")

))

server <- function(input, output, session) {

}

shinyApp(ui, server)


text:
Q: Additivity of suprema I'm currently starting with a more formal approach of calculus. I am reading Apostol's Calculus Vol. 1 and found the proof of the additivity of suprema confusing. Could someone please do it and explain it without skipping any steps.
The conditions given in the book are:
Let A and B be nonempty sets that have a supremum.
Given that
$$
C=\{a+b | a\in A, b\in B\}
$$
Prove that:
$$
\sup C=\sup A +\sup B
$$
Thanks in advance for the help!!!

A: If $a\in A$ and $b\in B$, then $a+b\leqslant\sup A+\sup B$ and therefore $\sup A+\sup B$ is an upper bound of $C$. So, $\sup C\leqslant\sup A+\sup B$.
Now, suppose that $\sup C<\sup A+\sup B$. Take $a\in A$ and $b\in B$ such that $\sup C<a+b\leqslant\sup A+\sup B$. But $a+b\in C$ and so we can't have $a+b>\sup C$.
Can you finish the proof by proving that if $\sup C<\sup A+\sup B$, then there must be an $a\in A$ and a $b\in B$ such that $\sup C<a+b$?


text:
Q: Unable to Hibernate: Swap header not found I hadn't allocated any swap partition while installing ubuntu before so I couldn't hibernate my laptop which gave error: couldn't find swap device,try swapon. I then created a swap partition using GParted of size about 10Gb and checked on swapon.

I then checked the size of swap in terminal,

I don't understand what this means and I am not sure what should I do after this. Still, I am unable to hibernate and now it says Swap header not found. What should I do to solve this problem?


text:
Q: Usando $tempo = date("d/m/Y H:i:s",time()-86400); para deletar agendamentos passado Estou usando este código para excluir os agendamentos com datas e horários já passados em relação ao tempo atual.
<?php
while($res = mysql_fetch_array($select_agenda)){

$id = $res['id'];
$nome = $res['nome'];
$tel = $res['tel'];
$cel = $res['cel'];
$email = $res['email'];
$plano = $res['plano'];
$data = $res['data'];
$horas = $res['horas'];
$tempo = date("d/m/Y  H:i:s",time()-86400);

$sql = mysql_query("DELETE FROM agendar WHERE data < '$tempo'");
?>

Sabendo que 86400 refere-se a quantidade de segundos de um dia, estou usando o código acima, e excluindo os agendamentos passados referente ao tempo atual, na virada das datas.
Seguindo este raciocínio, alterei para -1800, para que fosse excluídos os arquivos a cada 30 minutos. Ficando assim:
$tempo = date("d/m/Y  H:i:s",time()-1800);
$sql = mysql_query("DELETE FROM agendar WHERE data < '$tempo'");

Mas dessa forma esta excluindo todos os registros, e não o ultimo 30 minutos referente ao tempo real.
Os agendamentos são feitos com intervalos de 30 minutos.
Se os amigos puderem me dar uma ajudar de como devo proceder para os agendamentos sejam excluídos a cada 30 minutos, ficarei muito agradecido.
Grande abraço à todos.

A: Não sei se entendi bem a pergunta, mas é possível excluir os registros com um campo tipo "datetime" com valores inferiores a 30 minutos do tempo atual utilizando na query de exclusão a função NOW() do MySQL:
$sql = mysql_query("DELETE FROM agendar WHERE data <  NOW() - INTERVAL 30 MINUTE");

Lembrando que NOW() retorna a data/hora atual, e com o INTERVAL pode adicionar (usando +) ou subtrair (usando -) do tempo atual (ou seja, do valor retornado por NOW()).
Onde utilizei MINUTE, é possível substituir por: YEAR para ano,  MONTH para mês, DAY para dia, HOUR para hora, MINUTE para minuto, SECOND para segundo.
OBS: vale lembrar que a LIB mysql está depreciada para versões a partir do PHP 5.5 , utilize PDO ou MySQLi.
Espero ter ajudado!

A: Para subtrair 30 minutos do seu tempo inicial em PHP, ao invés de $tempo = date("d/m/Y  H:i:s",time()-1800); você pode fazer:
$tempoInicial = date("d/m/Y  H:i:s",time());
$menosTrintaMinutos = date("Y-m-d H:i:s", strtotime("-30 minutes", strtotime($tempoInicial )));

//echo 'tempo inicial: '.$tempoInicial.'<br/>';
//echo 'tempo -30m: '.$menosTrintaMinutos;

$sql = mysql_query("DELETE FROM agendar WHERE data < '$menosTrintaMinutos '");

Executando $sql você deleta todos os registros da tabela agendar onde há mais de 30 minutos passados (quando a coluna data é inferior à data atual descontando-se 30 minutos).


text:
Q: Working on same project on different computers forces me to uninstall app Sometimes I work with my laptop. But when I am at home, I work with my PC. I just put the project on Dropbox and continue working on it from a different PC. But every time I run the app from Android Studio, I have to uninstall due to different signature thing.  It is debug version not release so IDE does signing automatically. I am developing an app just for myself, even I am upgrading it, I don't want to lose my info stored previously.
So how can I prevent uninstalling?

A: Go into Build > Edit Build Type > Module : app > Signing and create a new one, then select on the Build Type tab > Signins Config.
Now you just have to share the keystore on your Dropbox.


text:
Q: How to avoid `nil` error when trying to join strings from different lines I have a file like this:
QWWWQV27

ETYUM
2019-01-29 03:20:07
KJJD_990

RP04MMB High risk YUZZP

HHLPPD
2019-01-23 12:34:13
CDF55UHM11

UYRP566_I Low risk ABCX

I want to concatenate the date and the next line containing the word "risk", and assign it to a variable.
I have the following code.
require 'date'

File.foreach("file.txt",sep="\n") do |line|
    if (DateTime.strptime(line.strip, '%Y-%m-%d %H:%M:%S') rescue nil)
     date = line.strip  #Here I'm storing the date in variable "date"
     next
    end

    risk = line[/.*risk.*/]
    next unless not (risk.nil?)
    output = date + risk
    p output
end

And I get this error:
NoMethodError: undefined method `+' for nil:NilClass
        from (irb):3333:in `block in irb_binding'
        from (irb):3325:in `foreach'
        from (irb):3325
        from /usr/bin/irb:11:in `<main>'

When I capture the line that contains "risk" and want to concatenate it with the date stored in variable date, the content of this variable is nil.
I don't know when date changes to nil. What am I doing wrong? How can I store the date to concatenate it later when the line containing the word "risk" appears?

A: str =<<_
QWWWQV27

ETYUM
2019-01-29 03:20:07
KJJD_990

RP04MMB High risk YUZZP

HHLPPD
2019-01-23 12:34:13
CDF55UHM11

UYRP566_I Low risk ABCX
_

FNAME = 'temp'
File.write(FNAME, str)
  #=> 144

require 'date'

We begin by defining two procs, both of which have one argument, line, which will be a line of the file after line.strip!.
date_r = Proc.new { |line| DateTime.strptime(line,
  '%Y-%m-%d %H:%M:%S') rescue false }
  #=> #<Proc:0x00005784561a3b28@(irb):567>
risk_r = Proc.new { |line| line.match? /\brisk\b/i }
  #=> #<Proc:0x00005784561c5610@(irb):569>

Next, use Array#cycle to produce an enumerator enum. Each time p = enum.next is executed one of the two procs date_r and risk_r will be assigned to the variable p, first date_r, then risk_r, then date_r and so on, forever. Both procs return true or false.
enum = [date_r, risk_r].cycle
  #=> #<Enumerator: [#<Proc:0x00005784561a3b28@(irb):567>,
    #<Proc:0x00005784561c5610@(irb):569>]:cycle>
p = enum.next # initialize p to date_r
  #=> #<Proc:0x00005784561a3b28@(irb):567>

File.foreach(FNAME).with_object([]) do |line, arr|
  line.strip!
  if p.call(line)
    arr << line
    p = enum.next
  end
end.each_slice(2).map(&:join)
  #=> ["2019-01-29 03:20:07RP04MMB High risk YUZZP",
  #    "2019-01-23 12:34:13UYRP566_I Low risk ABCX"]

Note that before .each_slice(2).map(&:join) is executed,
File.foreach(FNAME).with_object([]) do |line, arr|
  ...
end
  #=> ["2019-01-29 03:20:07", "RP04MMB High risk YUZZP",
  #    "2019-01-23 12:34:13", "UYRP566_I Low risk ABCX"]


text:
Q: API - Framework -Library
Possible Duplicate:
API vs Toolkit vs FrameWork vs Libarary

Can someone Explain the differences between an API, a Framework and a Library.
Some examples would be helpfull , specially for API.

A: API (Application Programming Interface) - Allows you to use code in an already functional application in a stand-alone fasion.
Framework - Code that gives you base classes and interfaces for a certain task/application type, usually in the form of a design pattern. (Though not always)
Library - Related code that can be swapped in and out at will to accomplish tasks at a class level
Ref Ryan answer


text:
Q: Maximize $x_1^2 + 4x_1 x_2 +x_2^2$ subject to $x_1^2 +x_2^2 =1$
[If someone could please show me how to complete this problem I would be really grateful, the instructor didn't provide an answer key for the old practice exams.

A: As , hints given by $\text{Toby Mak} $ ,
If you take $x_1=cosx , x_2= sinx $
Then , as, $x_{1}^{2}+x_{2}^{2}+4x_{1}x_{2} = cos^{2}x+sin^{2}x+4cosx\cdot sinx = 1 +4cosx\cdot sinx $
So, we have to find maximum value of $cosx\cdot sinx $
Take , $f(x)=cosx\cdot sinx $
Now , $f'(x)=cos^{2}x-sin^{2}x = cos(2x) $
Maximum will be taken by $f$ at $f'(x)=0 \implies cos(2x)=0 \implies x=\frac{\pi}{4} $
Now , at $x=\frac{\pi}{4} $ , $f=\frac{1}{2} $
So, Max of $x_{1}^{2}+x_{2}^{2}+4x_{1}x_{2}=1+\frac{4}{2}=3 $


text:
Q: How to fetch value of a bean variable inside the application I have use case where in I want to declare a bean which gets initialised at app start up and later I want to use the variable of the bean on a conditional expression
Below is the code snippet
// This is the bean I am declaring
@Configuration
public class ABCConfiguration {
    @Bean(name="mybean")
    public ABCConfig abcConfig() {
                // ABCFunction() is a function which returns true/false
        ABCConfig config = new ABCConfig(ABCFunction());
        return config;

    }

}

public class ABCConfig {

    private boolean isXYZ;

    public DRConfig(boolean isXYZ) {
        this.isXYZ = isXYZ;
    }

    public boolean isXYZ() {
        return isXYZ;
    }
}

Now I want use value of variable isXYZ inside my application through the already registered bean
on a conditional expression. This is how I am trying right now.
@ConditionalOnExpression("${mybean.isXYZ()} == true")

But I am getting the below error
Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'

A: base on this arthicle you can get value of @Bean with several methods one of them is :
Understanding getBean() in Spring

@Configuration
class AnnotationConfig {

    @Bean(name = {"tiger", "kitty"})
    @Scope(value = "prototype")
    Tiger getTiger(String name) {
        return new Tiger(name);
    }

    @Bean(name = "lion")
    Lion getLion() {
        return new Lion("Hardcoded lion name");
    }

    interface Animal {}
}

 @Autowired
 private ApplicationContext context;

 Tiger tiger = (Tiger) context.getBean("lion");


text:
Q: Python Logging: Evaluate Time before adding a new entry I am editing a python-script to control home appliances (sonos, hue etc.) with the log of a plex mediaserver.
So far things went well, now i am struggeling with a question i could not find an answer to. These are my first steps, please bear with me.
I have a log file, which collects session information in this format:

...
2014-09-13 14:40:02 johnedoe is watching 30c3 Keynote
2014-09-13 14:48:06 thomas is watching Band of Brothers
2014-09-13 15:28:03 johnedoe is watching The Zero Theorem
...

if a new session is detected, the script evaluates if the part "johnedoe is watching 30c3 Keynote" is already present. i would like to include a timestamp-check, which would not only examine if the session is present, but also if a already logged session is older than two hours.

In pseudocode:  if (alert not in log) or (if alert in log and older than two hours):

Can i access the corresponding timestamp directly, or to i have to regex the line? Any help is greatly appreciated. Many thanks in advance.
This is the tail of code:
logLocation = '/storage/downloads/plexMon.log'
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename=logLocation, level=logging.INFO)
log = open(logLocation).read()
server = urllib2.urlopen('http://127.0.0.1:32400/status/sessions')
data = server.read()
server.close()
tree = ET.fromstring(data)
for video in tree.iter('Video'):
  show = video.get('grandparentTitle')
  episode = video.get('title')
  if show == "None":
    title = episode
  else:
    title = '%s - %s' % (show, episode)
    user = video.find('User').get('title').split('@')[0]
  alert = '%s is watching %s' % (user, title)
  if alert not in log:
    logging.info(alert)
    if all(i not in alert for i in ignoreAlertList):
      sendAlert(alert)
      if user == "johnedoe":
          b = Bridge('192.168.1.109')
          b.set_light(1, 'bri', 50)
          my_zone = SoCo('192.168.1.105')
          my_zone.unjoin()
          my_zone.pause()

A: Without regexes, this may be easier to achieve, if you use:
log_lines = open(logLocation).readlines() # read log files as a list[] of lines

instead of:
log = open(logLocation).read()

and then use something like:
for line in log_lines:
    if(line.__contains__(alert)):
        partsOfLine = str(line).split()
        dateParts = str(partsOfLine[0]).split("-")
        timeParts = str(partsOfLine[1]).split(":")
        alerttime = datetime.datetime(int(dateParts[0]),int(dateParts[1]),int(dateParts[2]),int(timeParts[0]),int(timeParts[1]),int(timeParts[2]))
        timediff_in_min = (alerttime - datetime.now()).total_seconds()/60
        if(timediff_in_min >= 120):
            print "ignoring older than 2 hours"
        else:
            print "new alert in the last 2 hours"


text:
Q: Accessing array beyond it's size I have this code snippet and I have no idea why it's working in my code.
mft_fragment *pfrag = malloc(sizeof(mft_fragment));
printf("size2:%lu\n", sizeof(mft_fragment));
pfrag[23].fragment_count = 10;

printf prints 8 bytes. Shouldn't I be getting segmentation fault or something like that?


text:
Q: Postgresql : UNNESTING & NESTING I started exploring json in postgresql.
I have below jsonb in table.
'{
   "Owner":[
      {
         "Edgeid":4,
         "Weight":40,
         "EdgeColor":"Black"
      },
      {
         "Edgeid":1,
         "Weight":10,
         "EdgeColor":"Black"
      },
      {
         "Edgeid":2,
         "Weight":20,
         "EdgeColor":"Black"
      }
   ],
   "Supporter":[
      {
         "Edgeid":3,
         "Weight":30,
         "EdgeColor":"Red"
      }
   ]
}'

i am using below code to unnest "Owner" & "Supporter" into different columns
SELECT  column_name::JSONB -> 'Owner' AS owner_property,
        column_name::JSONB -> 'Supporter' AS supporter_property
        FROM table_name;

now suppose if i need to nesting it back to normal like above mentioned json from the two separate column. what would be my code.
Thanks in Advance.


text:
Q: How to remove outliers from a dataframe? I have a (268X4) df and found the outliers (22,1) for one column. I want to remove those outliers from the df. How do I do that?
> df=df_nonull import pandas as pd   # to manipulate dataframes import
> numpy as np   # to manipulate arrays
>
> # a number "a" from the vector "x" is an outlier if
> # a > median(x)+1.5*iqr(x) or a < median-1.5*iqr(x)
> # iqr: interquantile range = third interquantile - first interquantile def
>outliers(x):
>        return np.abs(x- x.median()) > 1.5*(x.quantile(.75)-
>x.quantile(0.25))
>
> # Give the outliers for the first column for example
>outliers=df.StockValue[outliers(df.StockValue)]

A: You can only remove the whole row, njot a single cell like (22,1). If you want to remove the complete row of the data.
df = df.drop(df.index[[22]])


text:
Q: Count beepers in stacks in Java Need to write method called clearStacks() that moves the most recently created robot forward until it reaches a wall picking up all beepers at it goes. The method should return no value
and take no parameters.
It also has a side-effect: the method prints how many beepers the robot picked up in each stack. Supposing there were 3 stacks on a row, the output might look like this:
Beepers: 4
Beepers: 1
Beepers: 7
My problem that I can not write how many beepers the robot picked up in each stack. Only overall amount. I am new in Java..
My code:
void clearStacks() {
int beepers=0;
while(isSpaceInFrontOfRobotClear()) {
    moveRobotForwards();
    while(isItemOnGroundAtRobot()) {
        pickUpItemWithRobot();
        ++beepers;
        println(beepers);
    }
}
}

A: Before checking for a stack, you'll want to reset your count. You'll then need to use a conditional statement to see if any beepers were picked up after clearing a stack (or determining that a stack was not there).
void clearStacks() {
    int beepers=0;
    while(isSpaceInFrontOfRobotClear()) {
        moveRobotForwards();

        /* Reset the count of beepers. */
        beepers = 0;

        /* Pick up any beepers at current spot. */
        while(isItemOnGroundAtRobot()) {

            /* Pick up beeper, and increment counter. */
            pickUpItemWithRobot();
            ++beepers;

        }

        /* Check to see if we picked up any beepers.
         * if we did, print the amount.
         */
        if(beepers > 0){
            println(beepers);
        }
    }
}

A: Maybe try implementing an array? You could use the first 3 elements to represent the first 3 stacks and then the value could represent how many beepers were picked up in each stack.
int[] beepers = new int[3];
int count = 0;
while(isSpaceInFrontOfRobotClear()) {
    moveRobotForwards();
    while(isItemOnGroundAtRobot()) {
        pickUpItemWithRobot();
        beepers[0]++;
        if (count > #numberOfBeepers) {
               break;
        }
    }
    for (int i: beepers) {
             System.out.print(beepers[i] + " ")
        }
  }
}

Let me know if this answers your question or if it didn't


text:
Q: Accepting negative doubles with boost::program_options I need to be able to have boost::program_options parse an array of doubles
that are passed on a command line. For positive doubles, this is no problem,
of course (use multitoken with std::vector<double> in add_options), but for
negative ones, I know that these are ambiguous arguments.
Here is a demonstration of what I would like to take in:

mycommand --extent -1.0 -2.0 -3.0 1.0 2.0 3.0 --some-other-argument somevalue

extent is to be backed by a Bounds class with at least one constructor
that takes in six individual T arguments (in this case -- double).
template <typename T>
class Bounds
{
public:
    typedef T value_type;
    typedef typename std::vector< Range<T> >::size_type size_type;

    typedef typename std::vector< Range<T> > Ranges;

    Bounds( T minx, T miny, T minz,
            T maxx, T maxy, T maxz)
    {
        // fill Ranges vector
    }

private:
    Ranges ranges;
};

What else must I supply to support using add_options take in the Bounds class? I'd
like to do something similar to this.  Possible?
namespace po = boost::program_options;
po::options_description options("options");

options.add_options()
    ("extent,e", po::value< Bounds< double > >(), "Extent to clip points to")

po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
  options(options).positional(p).run(), vm);

po::notify(vm);

if (vm.count("extent"))
{
    Bounds<double> bounds = vm["extent"].as< Bounds<double> >();
    // do other stuff
}

A: The trick is to force boost to classify all numbers as positional values (not to be confused with positional_options_description. The way you do that is define a style_parser and give it to the command_line_parser as an extra_style_parser:
    #include <boost/program_options/option.hpp>
    #include <boost/lexical_cast/try_lexical_convert.hpp>
    #include <boost/program_options/value_semantic.hpp>

    using po = boost::program_options;

    std::vector<po::option> ignore_numbers(std::vector<std::string>& args)
    {
        std::vector<po::option> result;
        int pos = 0;
        while(!args.empty()) {
            const auto& arg = args[0];
            double num;
            if(boost::conversion::try_lexical_convert(arg, num)) {
                result.push_back(po::option());
                po::option& opt = result.back();

                opt.position_key = pos++;
                opt.value.push_back(arg);
                opt.original_tokens.push_back(arg);

                args.erase(args.begin());
            } else {
                break;
            }
        }

        return result;
    }

Once you have it, this is how you use it:
    po::store(po::command_line_parser(argc, argv)
        .extra_style_parser(&po::ignore_numbers)
        .options(commands)
        .run(), vm);

You can now use negative numbers and short command line arguments at the same time.
However, there's still a problem, there's no way to restrict the number of tokens each argument takes, which can be problematic if you use positional arguments. For example, something like this won't work:
    foo --coords 1 2 3 4 bar.baz

In order to fix this, we'll need to add a way to force the number of tokens an argument requires:
    template<class T, class charT = char>
    class bounded_typed_value : public po::typed_value<T, charT>
    {
    public:
        bounded_typed_value(T* store_to)
            : typed_value<T, charT>(store_to), m_min(-1), m_max(-1) {}

        unsigned min_tokens() const {
            if(m_min < 0) {
                return po::typed_value<T, charT>::min_tokens();
            } else {
                return (unsigned)m_min;
            }
        }

        unsigned max_tokens() const {
            if(m_max < 0) {
                return po::typed_value<T, charT>::max_tokens();
            } else {
                return (unsigned)m_max;
            }
        }

        bounded_typed_value* min_tokens(unsigned min_tokens)
        {
            if(min_tokens > 1) {
                po::typed_value<T, charT>::multitoken();
            }

            m_min = min_tokens;

            return this;
        }

        bounded_typed_value* max_tokens(unsigned max_tokens)
        {
            if(max_tokens > 1) {
                po::typed_value<T, charT>::multitoken();
            }

            m_max = max_tokens;

            return this;
        }

        bounded_typed_value* fixed_tokens(unsigned num_tokens)
        {
            if(num_tokens > 1) {
                po::typed_value<T, charT>::multitoken();
            }

            m_min = num_tokens;
            m_max = num_tokens;

            return this;
        }

    private:
        int m_min;
        int m_max;
    };

    template<class T, class charT = char>
    bounded_typed_value<T, charT>*
    bounded_value()
    {
        return new bounded_typed_value<T, charT>(0);
    }

You can now put it all together like this:
    po::positional_options_description p;
    p.add("file-name", -1);

    boost::program_options::options_description desc;
    desc.add_options()
        ("coords,c", boost::program_options::bounded_value<std::vector<double>>()->fixed_tokens(4), "Bounding box");

    po::store(po::command_line_parser(argc, argv)
        .extra_style_parser(&po::ignore_numbers)
        .positional(p)
        .options(commands)
        .run(), vm);

A: The approach to handling negative numbers specified here might also work for you.

I was parsing it by the simple parser

store(command_line_parser(argc, argv).options(commands).run(), vm);

, but solution was to use the extended
  one:

parse_command_line

A: The easy way would be to wrap your parameters in quotes:
mycommand --extent '-1.0 -2.0 -3.0 1.0 2.0 3.0' --some-other-argument somevalue


text:
Q: Forget to reset parameter for production version I use TAdoconnection to access the database.
During development i set the connectionstring to my local database and set connected to true in order to get the information for the other dbcomponents.
When I finalize the program for a customer I forget sometimes to reset the parameter, which leads to an exception on the customer computer because the connectionstring is invalid.
I tried to put in the oncreate event of the datamodule (first line) a connected:=false but it seems to late.
How can I make sure that it the program has the rigth settings for the customer?
I tried to set some parameter in in a conditional compiling phrase like:
{$IFDEF PRODUCT}
param1:=..
....
{$ENDIF}

But I have no clue how to do this for visual components.

A: You can set true ConnectionString at runtime on event TADOConnection.OnBeforeConnect:
procedure TDM1.ADO1BeforeConnect(Sender: TObject);
begin
  ADO1.ConnectionString := 'Provider=SQLOLEDB;......';
end;

Or you can delay connecting
var CanConnect: Boolean;
procedure TDM1.ADO1BeforeConnect(Sender: TObject);
begin
  if not CanConnect then Abort;
end;

A: You cannot use conditionals if dfm files. Which means that if you set properties at design time, then they will be applied at run time, unconditionally.
If you must avoid shipping software with certain properties set, then you must simply stop yourself from doing that. A programmatic solution at run time is not an option.
Personally I would use my version control process to help. Whenever I commit changes I review all the changes. I'd have it is part of my routine to check dfm changes.
On top of that I'd test the software before releasing it. This testing needs to be done in a clean room setting. You'll want a virtual machine snapshot that is representative of the target deployment environment. Testing on your development machine is clearly not a viable option.

A: As others have said, a source control system could help detect changes to your .DFM files, however, there are also some other tools/ideas at your disposal.
Here are a couple of ideas that will not affect your current deployment procedures too much:
1) Connected property: GExperts GExperts includes an IDE add-in that can detect open connections at compile-time, and automatically set the connected property to false for you.  At a minimum, you could use the tool to detect and change manually, or let the tool do it for you.  The feature can be found on the GExperts menu: Configuration, Set Component Properties, then add TAdoConnection, Property: Connected, Value: false.
2) ConnectionString: Move your connection string to an .ini file or registry, and have two values, one for development and one for production.  Within your code, set each based on a flag, or use:
 if debughook <> 0 then
   // fetch design-time connection string
 else
   // fetch production connection string

I would also suggest you look into automating your build process using software such as FinalBuilder.


text:
Q: Cant access Json Array values created by json_decode My json_decode() is returning an array but i just cant seem to access it. Here's as much of information i think would be useful. I'm pulling a json value from a server using curl commands.
The response (output) from the server :
//php code from getVal.php
$response = curl_exec($ch);
echo($response);
var_dump($response);

{ "automat": false, "brightness": null, "increase: set time": 2, "decrease: set time": 2 } string(101) "{ "automat": false, "brightness": null, "increase: set time": 2, "decrease: set time": 2 } "

Converting the json formatted string to json array:
//php code from getVal.php
$res = json_decode($response, true);
echo($res);
echo("

");
var_dump($res);
echo("

");
echo($res["automat"]);

output:

Array

array(4) { ["automat"]=> bool(false) ["brightness"]=> NULL ["increase: set time"]=> int(2) ["decrease: set time"]=> int(2) }

Clearly $res prints as Array for some reason, and when trying to print $res["automat"] it doesn't t print anything at all. I've checked the console and there is no errors.
Solutions already tried with no result :
//1:
$response =  stripslashes($response);
//2:
$response = html_entity_decode($response);
//3:
$nbsp = html_entity_decode( " " );
$response = str_replace( $nbsp, "", $response);
//for each above
$res = json_decode($response, true);

Any further information can be provided if asked.

A: You are trying to echo a bool with a false value. It will not return/print anything.
You can test this, be executing the following code:
echo '('. NULL .')' . "\r";
echo '('. false .')'. "\r";
echo '('. true .')' . "\r";

This will give your output:
()
()
(1)

In order to see something from your example, use another key for this:
echo $res["increase: set time"];

P.S. Don't use images for showing source code.


text:
Q: What are some of the pros and cons for using SAM vs serverless framework? I was wondering which approach to use/explore more, I am currently exploring options to choose the best/suitable framework for building microservices on AWS Lambda, and canary deployments is a huge feature (SAM supports it, but serverless dont right now). Following are my questions:

*

*In general, what would be pros and cons of choosing SAM over serverless or vice-versa?

*Can you write SAM in serverless.yaml? Like SAM has some useful features and if we could utilize them in serverless that would be great

Thanks

A: AWS SAM
The focus on the AWS Serverless Application Model(At least for the moment), is to simplify defining AWS Resources related with Serverless Technology Stack (Lambda, API Gateway & etc.) in CloudFormation.
There are several limitations that comes with SAM. Its currently not providing full support for Custom Authorizers in a flexible manner. Also the DevOps tooling and plugins support is minimal compared to Serverless Framework.
Since SAM is native to AWS, support for AWS features will be available in SAM earlier than the Serverless Framework.
Serverless Framework
A DevOps Framework which allows to simplify defining and deploying AWS, Azure, Google Cloud and IBM Open Wisk in an unified manner. It uses CloudFormation underneath for AWS Serverless Stack Provisioning and comes with Plugins Eco System as well as simple commands to carryout DevOps tasks.
Serverless Framework has several limitations

*

*Deploys new API Gateways for each stage.

*Serverless Framework combines all the Lambda functions (If many defined in a single Serverless Project) and deploy all the code for all the functions, unless blacklisted specifically.


text:
Q: ACCESS 2007: Determine maximum value per row across multiple columns I have a table with multiple date columns per employee:
   Emp 1, Date1, Date2, Date3
   Emp 2, Date1, Date2, Date3

etc.
I would like to write a single query that returns to me the maximum date of the three dates available on a per-employee basis.  I understand I need to write a UNION ALL query but I can't seem to get the syntax so that I get a max value per employee record.  I keep getting the same value for all employees.  I'm sure this is a stupid error, but it's driving me nuts.  Any help would be most appreciated.

Thank you for the prompt responses!  Is there a way to do this without using an iif statement?  I'd like to generalize it if at all possible, since there are several other date fields and it gets really unwieldy figuring out the IIF logic.
Also, I forgot to mention that any of those dates could be empty, and the IIF logic seems to return the NULL as the maximum value.

A: SELECT ID, Max(TheDate) AS MaxDate
FROM
(
   SELECT ID, Date1 AS TheDate
   FROM myTable
   UNION
   SELECT ID, Date2 AS TheDate
   FROM myTable
   UNION
   SELECT ID, Date3 AS TheDate
   FROM myTable
)
GROUP BY ID

I know that this is not a clean solution.
But this is what you are looking for when you wrote of UNION.
EDIT: You could use UNION ALL instead of UNION. With above query, it will not make a difference in the output, I suppose.

A: Would something like this do:
(this was MSSQL2008 not sure if it will work in Acess)
Create Test Data
create table t1
    ( EmployeeId int,
      Date1  datetime,
      Date2  datetime,
      date3  datetime)

insert into t1 values (1, '2009-10-11', '2009-04-01', '2009-12-25')
insert into t1 values (2, '2009-10-24', '2009-04-03', '2009-12-19')

My Query
select case
    when date1 > date2 and DATE1 > date3 then date1
    when date2 > date1 and date2 > date3 then date2
    when date3 > date1 and date3 > date2 then date3
    end as highest
    from t1

A: Will something like this work?
select
  EmployeeColumn,
  iff(iif(Date1 > Date2, Date1, Date2) > Date3, iif(Date1 > Date2, Date1, Date2), Date3)
from yourTable

A: If you don't want to restrict the solution to SQL, you could use my iMax() function:
  Public Function iMax(ParamArray p()) As Variant
  ' Idea from Trevor Best in Usenet MessageID rib5dv45ko62adf2v0d1cot4kiu5t8mbdp@4ax.com
    Dim i As Long
    Dim lngUBound As Long
    Dim v As Variant

    v = p(LBound(p))
    lngUBound = UBound(p)
    For i = LBound(p) + 1 To lngUBound
      If v < p(i) Then
         v = p(i)
      End If
    Next
    iMax = v
  End Function

I call it "Immediate Max()" on analogy from IIf(), Immediate If(), because it's intended for row-level processing within a query.

A: Wow! I am seeing it is too complex to do a simple: Max(Field-Constant1,Constant2).
My Objective: Calulate a value depending on only one filed, but do not let calculated value be less than a constant.
Expample Rows on a two field table (KeyField, ValueField):
1 10
2 5
3 8
4 Null

I want a select that returns (when Constant1=6 and Constant2=1), i put the whole maths to clarify it (only the top most right part after the last = is what i want):
1 Max(10-6,1)=Max(4,1)=4
2 Max(5-6,1)=Max(-1,1)=1
3 Max(8-6,1)=Max(2,1)=1
4 Max(Null-6,1)=Max(Null,1)=Null

So i just want (when Constant1=6 and Constant2=1) in case it is not enough clear:
1 4
2 1
3 1
4 Null

Beware of that Null.
I really want something really more complex, but solving that i would be able to solve the complex one i want.
It can be resumed as:
-Return Null if value is Null or not a valid value for the math operator used (not allways is just a - or a +, etc)
-Return the calculated value if it is possible to do the math, but limited to a range (not less than a value and not bigger than another value).
If i do it on pseudo-code it would be as this:
try // try to do the maths
   MyCalculatedValue=SomeMaths(FieldValue);
   MyCalculatedValue=Min(Max(MyCalculatedValue,MinValue),MaxValue);
except // In case the SomeMaths can not be done (FieldValue is Null, negative square, division by zero, etc)
      MyCalculatedValue=Null;
end;
return MyCalculatedValue;

Just in case someone say database is not normalized: I want to do some maths to a field, then limit the result in a range; so smallest sample database will only have one table that will only have two fields (unique key field, data field), that is imposible to not be fully normalized; i am not talking about maximun of some fields on a row, neither maximun for a full table on a field (aggregate functions), just only i want to put a lower and an upper limits to a calculated value, but considering Null when such value is Null or the maths to be done to such value can not be done (cases like Constant1/(FieldValue-Constant2), etc.).
Real sample just in case someone do not get when this can be used:
Table Fields:
ID (Key)
SpacePosition (DecimalData)

Desired result fields for the query:
ID as ID
Min(Max(SpacePosition-SomeSpaceLongitud,StartPosition),EndPosition) AS RangeStart
Min(Max(SpacePosition+SomeSpaceLongitud,StartPosition),EndPosition) AS RangeEnd

Hope sample is clear and hope someone can help, with something easier than using VBA functions!
P.D.: Think that such Maths are more complex than just + and -, and table has a lot, lot more registers than just a few, think on near some billions of registers.
P.P.D.: It is not an option to hard code such results, since it would be no normalized database and worst, such range limits are values typed by user when running the query.


text:
Q: Snowflake - want to revert back to previous version of table before I replaced it I need to revert a table back to the state it was in before a CREATE OR REPLACE statement was run (i.e. the table is still populated).
I can see the QueryID in the history but can't for the life of me remember how I revert the change

A: The solution has already been provided by Francesco & Nick but here is a little more detail in the form of an example... Bascially you need to rename the current table and undrop the old one. It's like a fist-in-last-out stack where the current table sits at the top and you need to pop it off (rename it) to get to the previous one:
I've got some comments in the SQL for you to follow though:
-- Create the initial table
create table dont_drop_me(col1 varchar, col2 varchar)
;

-- Insert 4 rows of some sample data
insert overwrite into dont_drop_me values
('col1_row1', 'col2_row1'),
('col1_row2', 'col2_row2'),
('col1_row3', 'col2_row3'),
('col1_row4', 'col2_row4')
;

-- Replace the table (by accident?). New table has an extra column to prove changes.
create or replace table dont_drop_me(col1 varchar, col2 varchar, col3 varchar);

-- Now the new table contains no data but has 1 extra column
select * from dont_drop_me;
-- +----+----+----+
-- |COL1|COL2|COL3|
-- +----+----+----+

-- View what tables are on the history. The top row is the current table, the second
-- row is the first table that we replaced
show tables history like 'dont_drop_me';
-- +------------------------------+------------+-------------+-----------+-----+-------+----------+----+-----+--------+--------------+------------------------------+--------------------+---------------+-------------------+----------------------------+-------------------------+-----------+
-- |created_on                    |name        |database_name|schema_name|kind |comment|cluster_by|rows|bytes|owner   |retention_time|dropped_on                    |automatic_clustering|change_tracking|search_optimization|search_optimization_progress|search_optimization_bytes|is_external|
-- +------------------------------+------------+-------------+-----------+-----+-------+----------+----+-----+--------+--------------+------------------------------+--------------------+---------------+-------------------+----------------------------+-------------------------+-----------+
-- |2021-02-26 04:56:23.948 -08:00|DONT_DROP_ME|SIMON_DB     |PUBLIC     |TABLE|       |          |0   |0    |SYSADMIN|1             |NULL                          |OFF                 |OFF            |OFF                |NULL                        |NULL                     |N          |
-- |2021-02-26 04:56:19.610 -08:00|DONT_DROP_ME|SIMON_DB     |PUBLIC     |TABLE|       |          |4   |1024 |SYSADMIN|1             |2021-02-26 04:56:24.073 -08:00|OFF                 |OFF            |OFF                |NULL                        |NULL                     |N          |
-- +------------------------------+------------+-------------+-----------+-----+-------+----------+----+-----+--------+--------------+------------------------------+--------------------+---------------+-------------------+----------------------------+-------------------------+-----------+

-- We need to rename existing object to move it off the top of the stack so that we can recover the first one
alter table dont_drop_me rename to renamed_dont_drop_me;

-- Now view what tables are in the history again. You can see that the first table created has moved to the top of the stack
show tables history like 'dont_drop_me';
-- +------------------------------+------------+-------------+-----------+-----+-------+----------+----+-----+--------+--------------+------------------------------+--------------------+---------------+-------------------+----------------------------+-------------------------+-----------+
-- |created_on                    |name        |database_name|schema_name|kind |comment|cluster_by|rows|bytes|owner   |retention_time|dropped_on                    |automatic_clustering|change_tracking|search_optimization|search_optimization_progress|search_optimization_bytes|is_external|
-- +------------------------------+------------+-------------+-----------+-----+-------+----------+----+-----+--------+--------------+------------------------------+--------------------+---------------+-------------------+----------------------------+-------------------------+-----------+
-- |2021-02-26 04:56:19.610 -08:00|DONT_DROP_ME|SIMON_DB     |PUBLIC     |TABLE|       |          |4   |1024 |SYSADMIN|1             |2021-02-26 04:56:24.073 -08:00|OFF                 |OFF            |OFF                |NULL                        |NULL                     |N          |
-- +------------------------------+------------+-------------+-----------+-----+-------+----------+----+-----+--------+--------------+------------------------------+--------------------+---------------+-------------------+----------------------------+-------------------------+-----------+

-- Now undrop the table and prove that it is the old one (the one with 4 rows and 2 columns)
undrop table dont_drop_me;
select * from dont_drop_me;
-- +---------+---------+
-- |COL1     |COL2     |
-- +---------+---------+
-- |col1_row1|col2_row1|
-- |col1_row2|col2_row2|
-- |col1_row3|col2_row3|
-- |col1_row4|col2_row4|
-- +---------+---------+

A: This assumes you have the required time travel enabled/available...

*

*Clone the table at the required point in time

*Rename the table to anything you want

*Rename the clone to the original table name

Cloning at a point in time is described here: Cloning Time Travel

A: The UNDROP TABLE would do the trick but because you've run a CREATE OR REPLACE, you will first have to move the newly created table into a different schema:
For example:
use database dev;

create table public.t1 (id int);
insert into public.t1 (id) values (1), (2);

create or replace table public.t1 (id int);

create schema temp_schema;

alter table public.t1 rename to temp_schema.t1;

undrop table public.t1;


text:
Q: Performance of MarshalByRefObject Attribute in the same AppDomain I need to add the MarshalByRefObject attribute to some classes (that define the interface of a plug-in) to allow sandboxing of these plug-ins.
These classes are also used in a "non-plugin" context in a completely different application, but the attributes are in code. Do I will have any performance penalties in this other application without extra AppDomains?

A: You should have no major performance impact, if it is being called from the same AppDomain none of the methods of MarshalByRefObject will be called.
If there was a major impact than WinForms would be in a lot of trouble considering Control derives from MarshalByRefObject


text:
Q: golang convert excel sheet to a struct I tried to use https://github.com/tealeg/xlsx and https://github.com/360EntSecGroup-Skylar/excelize
I success to read from excel file
package main

import (
    "fmt"

    "github.com/360EntSecGroup-Skylar/excelize"
)

func main() {
    f, err := excelize.OpenFile("Book1.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
    // Get value from cell by given worksheet name and axis.
    cell, err := f.GetCellValue("Sheet1", "B2")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(cell)
    // Get all the rows in the Sheet1.
    rows, err := f.GetRows("Sheet1")
    for _, row := range rows {
        for _, colCell := range row {
            fmt.Print(colCell, "\t")
        }
        fmt.Println()
    }
}

put I want to convert data from excel to Array of defined struct
example
type InvoiceSheet struct {
    amount string
    item   string

}

var invoices []InvoiceSheet

err := excel.READMETHOD('path of file', &invoices)

then I can iterate invoices

A: I'm not interiorized with that module, but looking at the source code I see there's a "Columns()" function you can use to get the values you need.
// Columns return the current row's column values.
func (rows *Rows) Columns() ([]string, error)

https://github.com/360EntSecGroup-Skylar/excelize/blob/master/rows.go

A: I don't think any directly serialization is supported (not familiar with the package) so then why you wouldn't traverse your spreadsheet and initialize struct by struct and append it to a slice.
If your schema is known in advance you could define a map with your categories and use them as a reference point e.g.

columns:= map[string]string{"Id" : "A1", "Item" : "B1", "Amount" : "C1"}

Start a loop within you will parse next rows to extract your struct values.
func (m *MergeCell) GetCellValue() string

Do it until  its something to read, maybe until there is Id a not empty string.
I've just came up with a possible way to implement it nicer.
Instead, map[string]string use some map[string]Cell.
That Cell would look like that:
type struct Cell {
    column : string
    row : int
}
func (c Cell) str() {
    return fmt.Sprintf("%s%d", c.column, c.row)
}

It appears they have some column iterator implemented that can help you as well.
Here is example that basically solves your task (I omitted error handling to make it shorter).
    const sheet2 = "SheetName"

    f, _ := OpenFile(filepath.Join("test", "Book1.xlsx"))

    rows, _ := f.Rows(sheet2)

    var collectedRows [][]string
    for rows.Next() {
        columns, _:= rows.Columns()
        // here init your struct and append it to slice as described above
    }

More examples with rows you'll find in tests files e.g. here.
Now it's your turn. Good luck!


text:
Q: Prove unequal with numbers in $\mathbb{R}^{+}$ I have problems to prove the following inequality:
Let $a_{1}$, $a_{2}$, $b_{1}$, $b_{2}$ $\in$ $\mathbb{R}^{+}$ then:
$$\left( \frac{b_{1}+b_{2}}{a_{1}+a_{2}}\right)^{a_{1}+a_{2}}>\left( \frac{b_{1}}{a_{1}}\right)^{a_{1}}\left( \frac{b_{2}}{a_{2}}\right)^{a_{2}}$$
where: $a_{1}$, $a_{2}$, $b_{1}$, $b_{2}$ are all different.
I was unable to make the show, and I begin to doubt that is true why come to ask if it is valid or not, should be true if I can help with testing, I was the grateful.

A: Let x = b(1)/a(1) > 0 and y = b(2)/a(2) > 0. Then we need to prove:
((x*a(1) + y*a(2))/(a(1) + a(2)))^(a(1) + a(2)) > x^(a(1))*y^(a(2)  <====>
(a(1) + a(2))*ln(x*a(1)/(a(1) + a(2)) + y*a(2)/(a(1) + a(2))) > (a(1)/(a(1) + a(2)))*lnx +

*

*(a(2)/(a(1) + a(2)))*lny.

Let m = a(1)/(a(1) + a(2)) > 0, and n = a(2)/(a(1) + a(2)) > 0 then m + n = 1. So we prove:
ln(mx + ny) > mlnx + nlny with m, n > 0 and m + n = 1. Observe that f(t) = lnt is concave
if t > 0 because f''(t) = -1/t^2 < 0. So Jensen's inequality applies to get the answer.


text:
Q: How do I correct [object%20Object] in URL path when using EmberJS transitionToRoute from Controller? I'm attempting to setup an action in a template to transition users to another route based on a dynamically generated navbar, using a combination of json / and js that is executed client side. I've managed to configure my application so that I can generate regular paths that work, but I would like to use transitions to avoid additional page loads.
A gist with what is (hopefully) the necessary information is:
https://gist.github.com/rjfranco/5289201
JS:
App.Router.map ->
  @route 'index', {path: "/#{short_name}"}
  @route 'customList', {path: "/#{short_name}/custom-list/:list_name"}
  @route 'multiLevelList', {path: "/#{short_name}/multi-level-list/:list_name/:list_level"}

App.EventController = Em.ObjectController.extend
  goTo: (navbar_icon) ->
    @transitionToRoute navbar_icon.route, navbar_icon.context

# Sample passed navbar_icon
navbar_icon =
  img_src: '/somesource_or_another.jpg'
  display_name: 'My Link Name!'
  route: 'customList'
  context: {list_name: 'Exhibitors'}

template:
{{#each controller.navbarIcons}}

{{display_name}}

{{/each}}

The expected page actually loads fine, but the url the application transitions to is not correct, and refreshing breaks the application.
I'm expecting a URL along the lines of: /ruhaha/custom-list/Exhibitors
and I end up with one like: /ruhaha/custom-list/[object%20Object]
Slight update:
I've found that I could abuse a couple of methods on the app to produce the results I want:
App.handleURL('/ruhaha/custom-list/Exhibitors')
App.Router.router.replaceURL('/ruhaha/custom-list/Exhibitors')
This will actually trigger the route, and replace the url effectively transitioning my application to the state I want without a page request. Although this works I'm pretty certain this is the wrong way to take care of this issue.

A: I ended up resolving this issue (with some help from nerdyworm on freenode) by specifying a serialize method in my route that just returned the param I was expecting:
App.CustomListRoute = Em.Route.extend
  serialize: (params) ->
    params


text:
Q: How to read a list from a YAMLConfigutation I have a YAML file that looks like this:
foo:
  bar:
    - entry1: 1
      entry2: a
    - entry1: 2
      entry2: b

(Where the actual list is much longer.) I'm reading this file using Apache Configuration2's YAMLConfiguration. I can see the data in the internal data structures used in Apache Configuration2, but I can't figure out how to get this list out. I actually have a class that matches the structure of the list elements, which is what I'd really like to read into:
class MyListEntry {
    public int entry1;
    public String entry2;
}

How can I get the data YAMLConfiguration into a List<MyListEntry>?

A: Here's the solution I found (note this works for any HierarchicalConfiguration, not just YAMLConfiguration)
// this will return a list of List<HierarchicalConfiguration<ImmutableNode>>, one entry for each element of the list
var subConfigList = hierarchicalConfig.configurationsAt("foo.bar");

List<MyListEntry> myListEntries = new ArrayList<>(subConfigList.size());
// iterate over the subconfigs and pull out the specific values of interest
for(var subConfig : subconfigs) {
    MyListEntry myListEntry = new MyListEntry();
    myListEntry.entry1 = subConfig.getInt("entry1");
    myListEntry.entry2 = subConfig.getString("entry2");
    myListEntries.add(myListEntry);
}


text:
Q: Bash process substitution: how to portably refer to standard input? The question here is the bold sentence below. Suppose I'm trying to do this:
diff -u <(some command) {mystery-syntax}

I am diffing the output of some command and some data that comes from standard input—for instance, a copy-and-paste in the terminal. Like this:
$ diff -u <(echo foo) {mystery-syntax}
bar
[Ctrl-D]
--- /dev/fd/63  2021-11-04 11:28:19.360366909 -0700
+++ /dev/fd/62  2021-11-04 11:28:19.360366909 -0700
@@ -1 +1 @@
-foo
+bar

What actual syntax is the {mystery-syntax} meta-token covering?
The diff utility doesn't use the - convention for specifying standard input, so we cannot use that.
One answer is: /dev/fd/0.
$ diff -u <(echo foo) /dev/fd/0
bar
[Ctrl-D]
--- /dev/fd/63  2021-11-04 11:31:02.837040697 -0700
+++ /dev/fd/0   2021-11-04 11:30:56.807964644 -0700
@@ -1 +1 @@
-foo
+bar

OK, so we have it working in one way, on systems that have Linux-style /dev/fd. But is there a way without referencing the /dev filesystem, which is a system-specific implementation detail? I believe Bash process substitution is supported on systems which have mechanisms other than /dev/fd. The manual states that:

Process substitution is supported on systems that support named pipes
(FIFOs) or the /dev/fd method of naming open files.

For instance, the obvious:
diff <(echo foo) <(cat)

doesn't work; for whatever reason, even though the <(cat) process substitution needs only the output side of cat, cat is nevertheless being invoked in such a way that it has no standard input:
$ diff -u <(echo foo) <(cat)
cat: -: Input/output error
--- /dev/fd/63  2021-11-04 11:33:59.303347814 -0700
+++ /dev/fd/62  2021-11-04 11:33:59.303347814 -0700
@@ -1 +0,0 @@
-foo

There are some "clever" behaviors here, too. If we explicitly redirect
/dev/fd/0 into cat's input, that is still borked somehow:
$ diff -u <(echo foo) <(cat < /dev/fd/0)
cat: -: Input/output error

But! If we give cat it a here-document as its standard input, there
is no interference:
$ diff -u <(echo foo) <(cat <<<"bar")
--- /dev/fd/63    2021-11-04 11:40:03.612616179 -0700
+++ /dev/fd/62    2021-11-04 11:40:03.612616179 -0700
@@ -1 +1 @@
-foo
+bar

A: If one of the filenames given to diff on the command line is - (a dash), the utility will read from standard input in its place.
$ echo hello | diff -u <( echo ok ) -
--- /dev/fd/12  Fri Nov 12 21:25:18 2021
+++ -   Fri Nov 12 21:25:18 2021
@@ -1 +1 @@
-ok
+hello

From the GNU diff manual:

If  a FILE is -, read standard input.

From the OpenBSD manual:

If either file1 or file2 is -, the standard input is used in its place.

From the POSIX standard:

file1, file2
A pathname of a file to be compared. If either the file1 or file2 operand is -, the standard input shall be used in its place.

A: diff -u <(echo foo) <(cat) doesn't work in an interactive bash because commands in process substitution are not put in the foreground so can't read from the terminal device. Like in cat & where cat is also run in background (not in the foreground process group of the terminal device), the process running cat is suspended with a SIGTTIN signal as soon as it tries to read from its controlling terminal.
echo hello | diff -u <(echo ok) <(cat) works because the whole pipeline made of two subshells is in foreground, and anyway cat is reading from the pipe, not the terminal. The process substitutions end up being in foreground because they were started by the subshell (the second component of that pipeline) that is in foreground.
bash-5.0$ diff -u <(echo ok) <(ps -o pid,ppid,pgid,args)
--- /dev/fd/63  2021-11-12 22:39:41.985207894 +0000
+++ /dev/fd/62  2021-11-12 22:39:41.985207894 +0000
@@ -1 +1,6 @@
-ok
+    PID    PPID    PGID COMMAND
+   9779    9772    9779 /bin/zsh
+1957388    9779 1957388 bash --norc
+1958861 1957388 1957388 bash --norc
+1958862 1957388 1958862 diff -u /dev/fd/63 /dev/fd/62
+1958863 1958861 1957388 ps -o pid,ppid,pgid,args

--- /dev/fd/63  2021-11-12 22:39:01.017237420 +0000
+++ /dev/fd/62  2021-11-12 22:39:01.017237420 +0000
@@ -1 +1,7 @@
-ok
+    PID    PPID    PGID COMMAND
+   9779    9772    9779 /bin/zsh
+1957388    9779 1957388 bash --norc
+1958325 1957388 1958324 diff -u /dev/fd/63 /dev/fd/62
+1958326 1958325 1958324 [bash] <defunct>
+1958327 1958325 1958324 bash --norc
+1958328 1958327 1958324 ps -o pid,ppid,pgid,args

See how ps is running in a different process group in the first case above, and in the same process group as the rest in the second case.
If you run:
bash-5.0$ (diff -u <(echo ok) <(ps -o pid,ppid,pgid,args))
--- /dev/fd/63  2021-11-12 22:42:04.761112701 +0000
+++ /dev/fd/62  2021-11-12 22:42:04.761112701 +0000
@@ -1 +1,6 @@
-ok
+    PID    PPID    PGID COMMAND
+1960605    9772 1960605 /bin/zsh
+1960612 1960605 1960612 bash --norc
+1960757 1960612 1960757 diff -u /dev/fd/63 /dev/fd/62
+1960759 1960757 1960757 bash --norc
+1960760 1960759 1960757 ps -o pid,ppid,pgid,args

It's back to being OK as then we start a whole subshell in foreground.
So the easy work around here is to run the pipeline in a subshell.
In any case, again, that only applies to interactive shells (where terminal job control is being performed) and when stdin is the controlling terminal of the session.
In scripts (and you generally only care about portability in scripts), there's no problem with diff -u <(echo ok) <(cat) even when stdin is a terminal as the shell is non-interactive and doesn't do job control.
That cat however does nothing useful, it's the same UUOC as in:
cat | diff -u <(echo ok) -

Or
cat | diff -u <(echo ok) /dev/stdin

On systems that don't support /dev/fd/x / /dev/stdin¹, for commands which unlike diff, don't support - to specify stdin, <(cat) in bash or zsh (but not in ksh versions prior to ksh93u where that feature comes from) uses a temporary named pipe instead, so diff -u <(echo ok) <(cat) will still work on those systems.
Since we mention portability though, note that in zsh, you need:
echo hello | { diff <(echo ok) <(cat); }

For the stdin of cat to also be the pipe from echo.
Also note that:
echo hello | cmd /dev/stdin # or /dev/fd/0, /proc/self/fd/0²

Doesn't work with ksh93 on Linux, because there, ksh93's | uses socketpairs instead of pipes³ and on Linux (and Cygwin), contrary to other systems, opening /dev/stdin is not like dup(0), it opens the same file as open on stdin, and you can't open() a socket.
More reading in connected Q&As here:

*

*What is the portable (POSIX) way to achieve process substitution?

*When was process substitution first introduced?

*Bash: process substitution and stdin

¹ very few these days and there are probably far more systems without bash than without /dev/fd/x
² except for those commands such as gawk that treat or can treat /dev/stdin as meaning stdin by themselves without actually opening the file in the same was as for -.
³ as Linux' pipe implementation doesn't let you peek at the contents which ksh93 needs to perform some (dubious) optimisations.


text:
Q: Crystal Reports Crosstab Summarized Fields labels not aligned I have been having trouble with the summarized field labels of my Crystal Reports crosstab aligning with their corresponding cells while formatting the crosstab.  There are multiple summarized fields per row.
I am attempting to mimic excel style using crosstab.  This may not be the best way to go about it but with the data and my crystal experience it has been my best option.  My steps have been to:

*

*Uncheck "Show Cell Margins" in the Customize Style tab of Cross-Tab Expert.

*Put a bottom border on the display cells and label text objects.

When I do this the Cells space out vertically slightly and look fine, however the Summarized Field row labels to the left of them do not space out but still grow with the cells; so the text objects that they consist of actually overlap, while the cells do not.  So now the Labels do not align with the Cells themselves.
Example:
http://imgur.com/yuUWqkl - Default Crosstab formatting
http://imgur.com/5zSAnSr - After applying the formatting steps from above.
Sorry for the long explanation.  I have tried everything I could think of to re-align them but have come up blank.  If you have any suggestions please let me know
Thanks!

A: You can change the formatting of a summarized field by clicking embedded object formats. Like right click on one of the Summarized field and then click Format Object, from Here you can format a particular summarized field.


text:
Q: Understanding the definition of multiplicity for a nonsingular point I'm reading the definition from Shafarevich:
If $P=(0,0)$ and the leading terms in the equation of the curve have degree $r$ then $r$ is called the multiplicity of $P$. Thus a nonsingular point has multiplicity 1.
I don't understand how this definition applies, for example, to a parabola defined by $y=x^2$. Suppose I want to verify that $(0,0)$ is a nonsingular point by computing its multiplicity: the leading term here is $x^2$, so multiplicity should be 2, which cannot be, because $(0,0)$ is indeed nonsingular. Also, how would the definition change if $P \neq (0,0)$?

A: I had the exact same question as you, and I came to this question in search of help, so I will post an answer for anyone else who stumbles upon it.
When Shafarevich says the word "leading term", he means the term with minimal total degree. In the example above, $f(x,y) = y-x^2$ has a term with degree one, so the multiplicity of $(0,0)$ is $1$.
Suppose $(0,0)$ is a singular point of $g(x,y) = a + bx + cy + h(x,y)$, where $h$ has terms of degree $\ge 2$. By taking partial derivatives, one can see that $a=b=c=0$, so the claim that every singular point has multiplicity $\ge 2$ holds.