text:
Q: 14.04 :: Troubles after waking from suspend I am having issues with suspending my Acer Aspire 5739G running Ubuntu 14.04.
I have tried suspending using different methods - pm-suspend, from GUI, from Keyboard shortcut - but my system still freezes when waking up.
First of all, at Login screen the GUI won't respond to any keyboard or mouse inputs - the password text field doesn't respond, even the icons at the panel. After a while, the cursor starts blinking in the password field and I can type my password.
When I press 'login' and it logs in (It says I'm logged in) but then I get a blank desktop except for the 14.04 LTS label at the bottom. Frozen again. After a long period of time, it goes back to the login screen and plays the Ubuntu startup sound (sounds like beating drums).
It basically goes into the same loop every time I try to wake up
I have tried:
unity-tweak-tool --reset-unity

changing the drivers (currently Xorg) to Nvidia tested ones and some other commands and tips found here and there on the web but nothing!
Who can help me to sort this out?
An Ubuntu newbie.


text:
Q: OpenCV: Using cvGoodFeaturesToTrack with C++ mat variable I am trying to use the cvGoodFeatureToTrack function in Visual Studio 2010 with the image type as Mat. Most of the examples I have seen use the IplImage pointer.
Right now I have this:
int w, h; // video frame size

Mat grayFrame;
Mat eigImage;
Mat tempImage;
const int MAX_CORNERS = 10;
CvPoint2D32f corners[MAX_CORNERS] = {0};
int corner_count = MAX_CORNERS;
double quality_level = 0.1;
double min_distance = 10;
int eig_block_size = 3;
int use_harris = false;

w = CurrFrame.size().width;
h = CurrFrame.size().height;
cvtColor(CurrFrame, grayFrame, CV_BGR2GRAY);
cvGoodFeaturesToTrack(&grayFrame,
                      &eigImage,
                      &tempImage,
                      corners,
                      &corner_count,
                      quality_level,
                      min_distance,
                      NULL,
                      eig_block_size,
                      use_harris);

It compiles but gives me a memory access violation. Help!

A: As a starting point, if using C++ anyway (like your use of cv::Mat and cv::cvtColor suggests), then why not use C++ interface for the rest, too?
This would mean the use of cv::goodFeaturesToTrack or a cv::GoodFeaturesToTrackDetector, which are made to work on cv::Mat and friends instead of making unneccessary casts from cv::Mat to IplImage*.
cv::Mat grayFrame;
std::vector<cv::Point2f> corners;
double quality_level = 0.1;
double min_distance = 10;
int eig_block_size = 3;
int use_harris = false;

const int MAX_CORNERS = 10;
cv::cvtColor(CurrFrame, grayFrame, CV_BGR2GRAY);
cv::goodFeaturesToTrack(grayFrame,
                        corners,
                        MAX_CORNERS,
                        quality_level,
                        min_distance,
                        cv::noArray(),
                        eig_block_size,
                        use_harris);

redpajama_set_name: RedPajamaStackExchange


text:
Q: QThread Потоки ( как правильно закрыть поток ) Привет всем! накидал маленький рабочий пример за 5 минут, но возник вопрос, как правильно закрыть поток? При старте создаётся новый поток, а старый сохраняется... Возможно, что то не учёл или сделал не так. Вот исходники:
main.cpp
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();

return a.exec();
}

mainwindow.cpp
 #include "mainwindow.h"
 #include "ui_mainwindow.h"
 #include <QDebug>
 #include <QtCore>

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(this->ui->pushButton_start, SIGNAL(clicked()), this, SLOT(startGUI()));
connect(this->ui->pushButton_stop, SIGNAL(clicked()), this, SLOT(stopGUI()));
}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::startGUI()
{

// Создание потока
QThread* thread = new QThread;
Worker* worker = new Worker();

// Передаем права владения "рабочим" классом, классу QThread.
worker->moveToThread(thread);

//connect(worker, SIGNAL(sendBool(bool)), this, SLOT(stopGUI(bool)));

// Связываем сигнал об ошибки со слотом обработки ошибок(не показан).
//connect(worker, SIGNAL(error(QString)), this, SLOT(errorHandler(QString)));

// Соединяем сигнал started потока, со слотом process "рабочего" класса, т.е. начинается выполнение нужной работы.
connect(thread, SIGNAL(started()), worker, SLOT(process()));

// Отображаем в главном потоке Gui, значения из вторичного потока
connect(worker, SIGNAL(sendNumber(int)), this, SLOT(LineEditUi(int)));

// Оповещаем поток, что нужно остановиться
connect(this, SIGNAL(sendNumberBoolStop(bool)), worker, SLOT(reciveBoolStop(bool)), Qt::DirectConnection);

// По завершению выходим из потока, и удаляем рабочий класс
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));

// Удаляем поток, после выполнения операции
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

thread->start();
}

void MainWindow::LineEditUi(int number)
{
ui->lineEdit->setText(QString::number(number));
}

void MainWindow::stopGUI()
{
Stop = true;
qDebug() << Stop;
sendNumberBoolStop(Stop);
qDebug() << "sendMumberBoolStop = " << Stop;
}

mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "worker.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

bool Stop;

public slots:
void startGUI();

void stopGUI();
void LineEditUi(int number);

signals:
void sendNumberBoolStop(bool);

private:
Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

worker.cpp
#include "worker.h"
#include <QDebug>

Worker::Worker(QObject *parent) : QObject(parent)
{
Stop = false;
temp = 0;
}

Worker::~Worker()
{
qDebug() << "destruction Thread";
}

void Worker::process()
{
Stop = false;
if(!Stop == true)
{
    for (temp; temp <= 1000; temp++)
    {
        if(!Stop == true)
        {
        emit(sendNumber(temp));
        //ui->lineEdit->setText(QString::number(temp));
        //QCoreApplication::processEvents();
        qDebug() << temp;
        }
        else
        {
            return;
        }
    }
  }
}

void Worker::reciveBoolStop(bool Numb)
{
Stop = Numb;
qDebug() << "reciveBoolStop = " << Stop;
}

worker.h
#ifndef WORKER_H
#define WORKER_H

#include <QObject>

class Worker : public QObject
{
Q_OBJECT
public:
//Worker();
//virtual ~Worker();
explicit Worker(QObject *parent = 0);
~Worker();

bool Stop;
int temp;

signals:
void finished();
//void error(QString err);

void sendNumber(int);

public slots:
void process();

void reciveBoolStop(bool Numb);
};

#endif // WORKER_H

mainwindow.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>395</width>
<height>165</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralWidget">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
 <layout class="QHBoxLayout" name="horizontalLayout">
  <item>
   <widget class="QLineEdit" name="lineEdit"/>
  </item>
  <item>
   <widget class="QPushButton" name="pushButton_start">
    <property name="text">
     <string>Start</string>
    </property>
   </widget>
  </item>
  <item>
   <widget class="QPushButton" name="pushButton_stop">
    <property name="text">
     <string>Stop</string>
    </property>
   </widget>
  </item>
 </layout>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
 <x>0</x>
 <y>0</y>
 <width>395</width>
 <height>21</height>
</rect>
</property>
</widget>
<widget class="QToolBar" name="mainToolBar">
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
</widget>
<widget class="QStatusBar" name="statusBar"/>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>

A: В приведенном коде не испускается сигнал Worker::finished, следовательно поток не понимает, что ему нужно остановиться. Испустить сигнал нужно на выходе из функции Worker::process.
Добавлю, что для задачи единоразово запустить какой-то процесс в отдельном потоке лучше подойдет QtConcurrent::run
void MainWindow::startGUI()
{
    Worker* worker = new Worker();

    // Отображаем в главном потоке Gui, значения из вторичного потока
    connect(worker, SIGNAL(sendNumber(int)), this, SLOT(LineEditUi(int)));

    // Оповещаем поток, что нужно остановиться
    connect(this, SIGNAL(sendNumberBoolStop(bool)), worker, SLOT(reciveBoolStop(bool)), Qt::DirectConnection);

    //Запланируем удаление воркера после окончания расчета
    connect(worker,SIGNAL(finished()), worker,SLOT(deleteLater()));
    QtConcurrent::run(worker,&Worker::process);
}


text:
Q: Something Is Interfering With My Jquery I'm not entirely sure what is going on, but everything was working pretty great and we have a thing called FallingLeavesChristmas.min.js and it's not activating on this page specifically. I thought at first it was the js itself but its not. It works on other pages, just not this one specifically.
      <audio id="sound" width="300" height="32" controls="controls" loop autoplay ><source src="http://files.enjin.com/692771/tss.mp3" type="audio/mp3"></audio>

<link href="http://files.enjin.com/972880/Web_Dev/css/bootstrap.min.css" rel="stylesheet"></link>
<link href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.css" rel="stylesheet" type="text/css">

<link href='http://fonts.googleapis.com/css?family=Raleway:400,200' rel='stylesheet' type='text/css'>

  <link href="http://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css" rel="stylesheet">

Twitter

Facebook

Twitch

YouTube

Email Us

The cat is running to load the site for you, please wait a few seconds while she gathers enough yarn to complete the site.

    <marquee loop="infinite" scrollamount="5" direction="left" scrolldelay="20" onmouseover="this.stop()" onmouseout="this.start()">

    </marquee>

  Announcements

<marquee behavior="scroll" bgcolor="black" direction="left" onmouseover="this.stop();" onmouseout="this.start();">

The new Home Page has been released to the public! Thanks to everyone for their amazing support!</marquee>

×

BLACK DESERT

         <a href="/blackdesert"<button class="btn1">APPLY</button><button class="btn1">FORUMS</button><button class="btn1">MORE INFO</button>

   ×

BLADE AND SOUL

         <a href="/bns"<button class="btn1">APPLY</button><button class="btn1">FORUMS</button><button class="btn1">MORE INFO</button>

   ×

BLADE AND SOUL

         <a href="/Dragomon"<button class="btn1">APPLY</button><button class="btn1">FORUMS</button><button class="btn1">MORE INFO</button>

The website this is on is: http://www.eternagaming.com/home2clone

A: You need to move or add jquery.js before any file that requires jquery. Looks like e-particles.js is throwing the error. Trying moving it before that.

A: I couldn't figure out what was wrong so I simply removed the entire thing and created a snow effect using CSS instead.


text:
Q: Auto-accept calls in Android I have some code. It works, but only when the activity is open. When an application is minimized, it does not work. How do I make it work constantly?
try {
    Runtime.getRuntime().exec("input keyevent " + Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
} catch (IOException e) {
    //handle error here
}


text:
Q: Excel working with 5 sheets and updating another sheet I am creating a work sheet for my workers.. Each sheet is a name for that worker so like: James(sheet 1), Elver (Sheet 2), Chris (Sheet 3), John (Sheet 4) and then i have another sheet for another worker say (Mike) that makes things for these builders and are paid for it.
What i would like to do is in A1-A30 i enter something like (8x10) on James sheet (10x20) on Elver sheet etc... on Mikes sheet i want it to automatically go down the rows adding to Mikes sheet from A1 on James sheet or Elvers sheet every time i change a cell from A1-A30 on either of their sheets it automatically add's it to  Mikes sheet
How can i do this i have been trying to figure it out for a week now..Macros? Linking? please help!
I have tried linking, equals etc.. but it's not what im looking for i just want to take any work sheets i make and anytime i enter data in a column it automatically loads it into a specific sheet going down that sheet

A: A Workbook SheetChange

*

*Select Developer > Visual Basic (F11). Copy the code to the ThisWorkbook module of the correct workbook. Exit the Visual Basic Editor.

*When, in one of the worksheets from the array, a value in the range A1:A30 is manually changed, this (new) value(s) is written to the first available cell in column A of worksheet Mike.

Option Explicit

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

    Dim Workers As Variant: Workers = Array("James", "Elver", "Chris", "John")
    Const WorkersAddress As String = "A1:A30"
    Const Chief As String = "Mike"
    Const ChiefColumn As String = "A"

    If IsError(Application.Match(Sh.Name, Workers, 0)) Then Exit Sub

    Dim wrg As Range: Set wrg = Intersect(Sh.Range(WorkersAddress), Target)
    If wrg Is Nothing Then Exit Sub

    Dim cws As Worksheet: Set cws = ThisWorkbook.Worksheets(Chief)
    Dim cCell As Range
    Set cCell = cws.Cells(cws.Rows.Count, ChiefColumn).End(xlUp).Offset(1)

    Application.EnableEvents = False

    Dim wCell As Range

    For Each wCell In wrg.Cells
        cCell.Value = wCell.Value
        Set cCell = cCell.Offset(1)
    Next wCell

    Application.EnableEvents = True

End Sub

A: I don't even think you need VBA as long as your version of Excel supports dynamic arrays.  TEXTJOIN allows concatenating all of the texts in a range or set of ranges, and you can use that to generate an xml document and parse it into an array with FILTERXML.  I have only used two sheets here (James and Elver), but you can add more at will.  You would put this in Mike!A1:
=FILTERXML("<xml><x>" & TEXTJOIN("</x><x>", TRUE, James!$A$1:$A$30, Elver!$A$1:$A$30) & "</x></xml>", "//x")

Here it is formatted so that it is a little easier to see what's going on:
=FILTERXML(
  "<xml><x>" &
  TEXTJOIN("</x><x>", TRUE, James!$A$1:$A$30, Elver!$A$1:$A$30) &
  "</x></xml>",
  "//x"
)

First, combine all of the texts using TEXTJOIN, using </x><x> as the separator.  You're using this separator so that you can produce a valid xml string to use later.
TEXTJOIN("</x><x>", TRUE, James!$A$1:$A$30, Elver!$A$1:$A$30)

Wrap that with "<xml><x>" and "</x></xml>" to finalize the xml string.
="<xml><x>" & TEXTJOIN("</x><x>", TRUE, James!$A$1:$A$30, Elver!$A$1:$A$30) & "</x></xml>"

and pass the entire generated string to FILTERXML with the selector //x.  This will return the text of all x nodes in your xml string as an array.  x here was selected arbitrarily.  You could use anything.
Here it is working on my machine.  C1 just contains the text so you can see it:
Let me know if that works for you.


text:
Q: Excel pivot on analysis server slow, same cross table in powerbi desktop is fast My customer wants to continue using Excel pivot.
We have a tabular model in azure analysis server.
When making a pivot on 2 columns (1 from the fact, 1 from the dimension table), it is very slow and a memory allocation error occurs.
Making the same selection in pbi desktop in a table, is no problem.
What is the difference? Both are live connections on tabular, no import.
The excel connections connects to a perspective of the model.
When applying a measure to the pivot it works, but the pivot (in straight table format) should also be possible to show without a measure.
Purpose is to quickly drag & drop all required attributes into the pivot, just like in PBI desktop.
Thanks,
Johan.


text:
Q: ServiceStack RedisMqServer not always handling messages published from separate application Context
I have a RedisMqServer configured to handle a single message on my ServiceStack web service. The messages on that MQ originate from another application and show up in the .inq with all the correct properties. Everything is on 4.0.38.
My configuration in MyAppHost.cs:
public override void Configure(Container container)
{
    var redisFactory = new PooledRedisClientManager(0, "etc:etc");
    redisFactory.ConnectTimeout = 5;
    redisFactory.IdleTimeOutSecs = 30;
    redisFactory.PoolTimeout = 3;
    container.Register<IRedisClientsManager>(redisFactory);

    //Plugins, Filters, other Registrations omitted

    var mqHost = new RedisMqServer(redisFactory, retryCount: 2);
    mqHost.DisablePublishingResponses = true;
    mqHost.RegisterHandler<CreateVisitor>(ServiceController.ExecuteMessage);
    mqHost.Start();
}

And then in Global.asax.cs:
void Application_Start(object sender, EventArgs e)
{
    new MyAppHost().Init();
}

Problem
The messages are not consistently handled when I deploy this elsewhere. They wait in the .inq until whenever. Nothing is lost, just delayed for an indeterminate duration.
As of this moment, the only things that come to mind are:

*

*I'm using IIS Express locally, and the server is using IIS.

*Application_Start needs to happen before it can handle messages.

I've tried initializing the service by making other API calls over HTTP, before and after queuing messages, with more failure than success. Sometimes the service starts to handle them, but I am unable to identify and thus influence when this happens.
Note
I do have several other console applications and windows services that listen on other MQs and handle messages placed by other applications, and those have always worked flawlessly. This is the first time I've tried this from within an existing web service, however.

A: Hard to know what the issue from this description (are messages getting lost or just delayed?) but this sounds like it's due to ASP.NET AppDomain recycling in which case you can disable AppDomain recycling or setup up a continuous ping route to hit your ASP.NET Web Application to keep the AppDomain alive.
If the ASP.NET Service is available on the Internet you can use services like https://uptimerobot.com or https://www.pingdom.com to configure it to ping your Service at different intervals (e.g. 5-10 minutes) otherwise if this is an internal Service you can use a Scheduled Task.


text:
Q: Riparian corridor delineation in QGIS I am trying to delineate the riparian corridors using GRASS in R. But I am having some issues.
So is there a plugin in QGIS using which I can extract riparian corridors using the already available upstream corridors?


text:
Q: How to fill missing values in DataFrame using another DataFrame in Pandas my df looks like this:
sprint   sprint_created
------   -----------
S100     2020-01-01
S101     2020-01-10
NULL     2020-01-20
NULL     2020-01-31
S101     2020-01-10
...

in the above df, you can see that some of the sprint values are NULL
I have another df2 that has sprint date ranges:
sprint   sprint_start   sprint_end
------   -----------    ----------
S100     2020-01-01     2020-01-09
S101     2020-01-10     2020-01-19
S102     2020-01-20     2020-01-29
S103     2020-01-30     2020-02-09
S104     2020-02-10     2020-02-19
...

How can I map these data and fill in the NULL values in the df by comparing the data in the df2?
Please note that the shape of df and df2 are different.

A: I assummed duplicated sprint in df(first dataframe can be dropped). Please advice otherwise if not so. I use merge asof with one day tolerance based on my comparison of the two dfs you provided. Advice otherwise if so
df.assign(sprint=pd.merge_asof( df.drop_duplicates(keep='first'), df1, left_on="sprint_created", right_on="sprint_start", tolerance=pd.Timedelta("1D"))['sprint_y']).dropna()
  sprint sprint_created
0   S100     2020-01-01
1   S101     2020-01-10
2   S102     2020-01-20
3   S103     2020-01-31

If your frame has legit multiple sprints as explained above in comments. Please try;
g=df.assign(sprint=pd.merge_asof( df.drop_duplicates(keep='first'), df1, left_on="sprint_created", right_on="sprint_start", tolerance=pd.Timedelta("1D"))['sprint_y'])
g.loc[g.sprint.isna(), 'sprint']=g.groupby('sprint_created').sprint.ffill()
print(g)

sprint sprint_created
0   S100     2020-01-01
1   S101     2020-01-10
2   S102     2020-01-20
3   S103     2020-01-31
4   S101     2020-01-10

A: One way would be to melt and resample your df2 and create a dictionary to map back to df1:
#make sure columns are in datetime format
df1['sprint_created'] = pd.to_datetime(df1['sprint_created'])
df2['sprint_start'] = pd.to_datetime(df2['sprint_start'])
df2['sprint_end'] = pd.to_datetime(df2['sprint_end'])

#melt dataframe of the two date columns and resample by group
new = (df2.melt(id_vars='sprint').drop('variable', axis=1).set_index('value')
          .groupby('sprint', group_keys=False).resample('D').ffill().reset_index())

#create dictionary of date and the sprint and map back to df1
dct = dict(zip(new['value'], new['sprint']))
df1['sprint'] = df1['sprint_created'].map(dct)
#or df1['sprint'] = df1['sprint'].fillna(df1['sprint_created'].map(dct))
df1
Out[1]:
  sprint sprint_created
0   S100     2020-01-01
1   S101     2020-01-10
2   S102     2020-01-20
3   S103     2020-01-31
4   S101     2020-01-10


text:
Q: Trouble running lighttpd with webpy This is what my lighttpd.conf file looks like:
server.modules = (
    "mod_access",
    "mod_alias",
    "mod_compress",
    "mod_accesslog",
)

server.document-root        = "/home/ashley/leagueratings"
server.upload-dirs          = ( "/var/cache/lighttpd/uploads" )
server.errorlog             = "/var/log/lighttpd/error.log"
server.pid-file             = "/var/run/lighttpd.pid"
server.username             = "www-data"
server.groupname            = "www-data"

## Use ipv6 if available
#include_shell "/usr/share/lighttpd/use-ipv6.pl"

compress.cache-dir          = "/var/cache/lighttpd/compress/"
compress.filetype           = ( "application/x-javascript", "text/css", "text/html", "text/plain" )

include_shell "/usr/share/lighttpd/create-mime.assign.pl"
include_shell "/usr/share/lighttpd/include-conf-enabled.pl"

server.modules   += ( "mod_fastcgi" )
server.modules   += ( "mod_rewrite" )

 fastcgi.server = ( "/leagueratings.py" =>
 ("/" => ( "socket" => "/tmp/fastcgi.socket",
    "bin-path" => "/home/ashley/leagueratings.py",
    "max-procs" => 1,
   "bin-environment" => (
     "REAL_SCRIPT_NAME" => ""
   ),
   "check-local" => "disable"
 ))
 )

 url.rewrite-once = (
   "^/favicon.ico$" => "/static/favicon.ico",
   "^/static/(.*)$" => "/static/$1",
   "^/(.*)$" => "/leagueratings.py/$1",
 )

I've done both
chown www-data:www-data leagueratings.py

and
chmod +x leagueratings.py

But I cannot connect to my website. The default site work previously before I changed lighttpd.conf
This is the error log
2016-09-13 19:37:35: (log.c.164) server started
2016-09-13 19:49:49: (server.c.1558) server stopped by UID = 0 PID = 1
2016-09-13 19:49:50: (log.c.164) server started
2016-09-13 19:49:50: (mod_fastcgi.c.1112) the fastcgi-backend /home/ashley/leagueratings.py failed to start:
2016-09-13 19:49:50: (mod_fastcgi.c.1116) child exited with status 2 /home/ashley/leagueratings.py
2016-09-13 19:49:50: (mod_fastcgi.c.1119) If you're trying to run your app as a FastCGI backend, make sure you're using the FastCGI-enabled version.
If this is PHP on Gentoo, add 'fastcgi' to the USE flags.
2016-09-13 19:49:50: (mod_fastcgi.c.1406) [ERROR]: spawning fcgi failed.
2016-09-13 19:49:50: (server.c.1022) Configuration of plugins failed. Going down.

Please help me I've been trying to get my webpy server up and running for production for a long time now. I've also tried apache2 and nginx but nothing seems to work. Thank you.

A:
2016-09-13 19:49:50: (mod_fastcgi.c.1112) the fastcgi-backend /home/ashley/leagueratings.py failed to start:

This does not appear to be a web server issue.
Have you tried manually starting up leagueratings.py?  It is possible that a needed python module is missing (and needs to be installed), or that there is a syntax error in the python script.


text:
Q: Undefined response in callback node js? I am trying to call a function that retrives all the document from a collection and returns the data. Now, everything works fine but for some reason , I am getting an undefined response from my function callback. What could I be doing wrong?
var findImages = function(db, callback) {
    var s ="";
    db.collection('imageinfo', function(err, collection) {
        collection.find().toArray(function(err, items) {

            for(var i=0;i<items.length;i++){
                console.log("imagename",items[i].imagename);
                s =s + items[i].imagename+",";

            }

            if(i==items.length){
                callback(s);

            }
        });

    });

};

app.get("/fetchrecords",function(req,res){
    console.log("entered");
    findImages(db,function(req,res){
     console.log("res",res);
    });

    res.end("Sent records");

});

A:
I am getting an undefined response from my function callback.

Callback of findImages only returns one parameter when invoked callback(s);
But in your callback definition you logging second argument. Instead, log only first argument
findImages(db,function(res){
 console.log("res",res);
});

A: i will never be the same as items.length. Because reason 1 i is not in your for loop, so it is out of scope.
Reason 2, even if i is in your loop, your loop will give i a maximum value of items.length -1 because you use <.
Your solution:
var findImages = function(db, callback) {
    var s ="";
    db.collection('imageinfo', function(err, collection) {
        collection.find().toArray(function(err, items) {
           var i = 0;
            while( i<items.length){
                console.log("imagename",items[i].imagename);
                s =s + items[i].imagename+",";
                i++;
            }
              callback(s);

        });

    });

};


text:
Q: How to check does EC2 Instance Savings Plan applied to my EC2 instance or not I purchased EC2 Instance Savings Plan with full upfront.
Is is possible to check - does it applied to my EC2 instance or not? I want to be sure that I bought saving plan with correct settings.

A: You should be able to check it using Utilization report and coverage report.


text:
Q: Bootstrap table border radius won't work I am trying to get curved corners on a table, however nothing is happening when I add border-radius. I've tried adding !important but it didn't help.
.table {
border: 3px solid #d8d8d8;
border-radius: 10px;
}

Thanks if someone can fix it

A: You can add an div around with class panel.

https://codepen.io/Ylama/pen/BJjBeq

A: This is the solution
HTML :

  i am a good guy you think ? am i.....

CSS :
.table{
  border: 3px solid #d8d8d8;
  border-radius: 10px;
}

codepen


text:
Q: complex JSON schema .. help  "responseCode": String
"responseMessage": String
"responseBody": { "conversations": [
{
"conversationId": String,
"state": String,
"conversationType": String,
"mediaType": Enum,
"startDate":Integer,
"duration": Integer,
"tags":[{ "tagName":String,
"tagType":String,
"tagCreateDate":Integer,
"tagOffset":Integer
}],
]}
This schema continues, but my question regarding the first section applies to the rest...
How can I deserialize a JSON response based on this schema into .NET objects? what would the .NET object look like?
Is there another way to read it ? (like a .NET Dataset type of way?)
Thanks. Roey.

A: If you want (or have to) to use JavaScriptSerializer the code could look like following:
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace JsonSer {
    public class MyTag {
        public string tagName { get; set; }
        public string tagType { get; set; }
        public long tagCreateDate { get; set; }
        public int tagOffset { get; set; }
    }
    public enum MyMedia {
        Diskette,
        UsbStick,
        Disk,
        Internet
    }
    public class MyConversation {
        public string conversationId { get; set; }
        public string state { get; set; }
        public string conversationType { get; set; }
        public MyMedia mediaType { get; set; }
        public long startDate { get; set; }
        public int duration { get; set; }
        public List<MyTag> tags { get; set; }
    }
    public class MyConversations {
        public List<MyConversation> conversations { get; set; }
    }
    public class MyData {
        public string responseCode { get; set; }
        public string responseMessage { get; set; }
        public MyConversations responseBody { get; set; }
    }
    class Program {
        static void Main (string[] args) {
            MyData data = new MyData () {
                responseCode = "200",
                responseMessage = "OK",
                responseBody = new MyConversations () {
                    conversations = new List<MyConversation> () {
                         new MyConversation() {
                             conversationId = "conversation1",
                             state = "state1",
                             conversationType = "per JSON",
                             mediaType = MyMedia.Internet,
                             startDate = DateTime.Now.Ticks,
                             duration = 12345,
                             tags = new List<MyTag>() {
                                 new MyTag() {
                                     tagName = "tagName1",
                                     tagType = "tagType1",
                                     tagCreateDate = DateTime.Now.Ticks,
                                     tagOffset = 1
                                 }
                             }
                         }
                     }
                }
            };

            Console.WriteLine ("The original data has responseCode={0}", data.responseMessage);
            JavaScriptSerializer serializer = new JavaScriptSerializer ();
            string json = serializer.Serialize (data);
            Console.WriteLine ("Data serialized with respect of JavaScriptSerializer:");
            Console.WriteLine (json);
            MyData d = (MyData)serializer.Deserialize<MyData> (json);
            Console.WriteLine ("After deserialization responseCode={0}", d.responseMessage);
        }
    }
}

the corresponding JSON data will be look like
{
    "responseCode": "200",
    "responseMessage": "OK",
    "responseBody": {
        "conversations": [
            {
                "conversationId": "conversation1",
                "state": "state1",
                "conversationType": "per JSON",
                "mediaType": 3,
                "startDate": 634207605160873419,
                "duration": 12345,
                "tags": [
                    {
                        "tagName": "tagName1",
                        "tagType": "tagType1",
                        "tagCreateDate": 634207605160883420,
                        "tagOffset": 1
                    }
                ]
            }
        ]
    }
}

You can easy modify the code if you decide to use DataContractJsonSerializer.

A: First you can beautify all your JSON using http://jsbeautifier.org/ to make it more readable, and then the only way I know is to just go through every property step by step and create classes for them. You should add the [DataContract] attribute for classes and the [DataMember] attribute for properties.
Example
[DataContract]
public class Response{
    [DataMember]
    public string responseCode {get;set;}
    [DataMember]
    public string responseMessage {get;set;}
    [DataMember]
    public ResponseBody responseBody {get;set;}
}

Automatic generation of these classes
There are alternatives for XMLSerialization (using XSD) but as far as I know there are no similar solutions for json thus far.
To finally deserialize the json into .NET object you can use the following code:
Response myResponse = new Person();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myResponse.GetType());
myResponse = serializer.ReadObject(ms) as Response;
ms.Close();

Where Response would be the type of object that represents the root of your json.
For more information visit the MSDN page of the DataContractJsonSerializer class.


text:
Q: Angular Bootstrap Ui-select I am trying to use the ui-select directive in my angularjs but it is not displaying, i tried following the documentation and this is what i did:
 <ui-select ng-model="form.gender" theme="bootstrap">
    <ui-select-choices repeat="gender in genders">
        {{ gender.name }}
    </ui-select-choices>
</ui-select>

Then I have an array of genders:
$scope.genders = [
    {
        name: 'Male'
    },
    {
        name: 'Female'
    }
];

I haven't really used this directive before so I'm a bit confused as to what i am doing wrong.
There are no errors being displayed in my browser console, i have included the module in my app as well.
I want to use it for more than a simple dropdown of genders but i figure this is a start if i can do this then i won't have any more problems. :)
Edit: So i cleared my browser cache and refreshed my page and this time i did notice an error:
Error: [ui.select:transcluded] Expected 1 .ui-select-match but got '0'.

A: just add a class named as the tag.
 <ui-select ng-model="form.gender" theme="bootstrap">
    <ui-select-choices class="ui-select-choices" repeat="gender in genders">
        {{ gender.name }}
    </ui-select-choices>
</ui-select>

A:
Error: [ui.select:transcluded] Expected 1 .ui-select-match but got '0'.

This error was fixed recently at Github page.
Just update ui-select to v0.14.3.
Reference: https://github.com/angular-ui/ui-select/issues/224

A: You must visit this link and follow its examples.
You can follow its examples
I personally prefer to use uiselect2, its more powerful and simple than uiselect
link of uiselect2

A: .ui-select-toggle > .caret { pointer-events: none }
fixes the problem of
error: [ui.select:transcluded] Expected 1 .ui-select-match but got '0'.
for me

A: As @Caner Çakmak said, I added a class named as tag in both ui-select-choices and ui-select-match
Ex:
<ui-select ng-model="form.gender" theme="bootstrap">
    <ui-select-match class="ui-select-match" [etc...etc....etc]>
    <ui-select-choices class="ui-select-choices" repeat="gender in genders">
    {{ gender.name }}
    </ui-select-choices>
</ui-select>

And it worked! Thanks
PS: I am using ui-select v0.19.X and Angular v1.5.X (that seems to be when this error occurs)


text:
Q: Jackson deserialize List as a property of POJO I have a POJO class which will be deserialized from JSON which comes as RequestBody in Spring. This POJO class contains List<String> as an instance variable. When this variable is deserialized, value is null. How to correctly deserialize it? Below are the code samples
My POJO looks like below
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class BookDto {
@JsonProperty("bookName")
private String bookName;
@JsonProperty("authors")
private List<String> authors;
@JsonProperty("description")
private String description;
}

My JSON object looks like below
{
 "bookName":"Vagrant Up and Running",
 "authors":["aone", "atwo"],
 "description":"Getting started guide for Vagrant development"
}

Below is the sample method call
public void method(@RequestBody BookDto bookDto) {}

I had followed given suggestion and the deserializer code is given below
public class AuthorDeserializer extends JsonDeserializer<List<String>> {
@Override
public List<String> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    Author author = jsonParser.readValueAs(Author.class);
    return author.authors;
}

private static class Author {
    public List<String> authors;
}
}

A: Make fields Public or add getter's to make them deserialize-able
Refer this for more deails

A: If you use Lombok, consider adding this annotation @Data like below:
@Data //You can remove the @Getter and @Setter annotation since @Data includes them
@NoArgsConstructor
public class BookDto {
   private String bookName;
   private List<String> authors;
   private String description;
}

Note: This is not related to the issue but please remove @JsonProperty()for clarity, this annotation is useless in your case since your JSON object's properties have the same name as your DTO's properties and by default the ObjectMapper use the names to map properties.
EDIT: @RequestBody deserializes the JSON for you so you don't need to do it manually.


text:
Q: Remote Debugging in Visual Studio (VS2008), Windows Forms Application I'm trying to Remote Debugging a Windows Forms Application (C#), but i'm always getting this error:

Unable to connect to the Microsoft Visual Studio Remote Debugging Monitor
  named 'XXX. The Visual Studio Remote
  Debugger on the target computer cannot
  connect back to this computer.
  Authentication failed. Please see Help
  for assistance.

I tried to config according to the MSDN guides but i was not able to make it work.
My setup:

*

*Development Computer - XP (x86) that
is connected to a domain.

*Test Computer - Vista (x86) that is NOT
    connected to a domain.

*I have network connection between
    the machines.

*I created a local user in the Test
    computer (user1) with the name of my domain
    user that I run the Visual Studio (mydomain\user1). setup the same password.

*On The Test Computer i'm running "msvsmon.exe" as application (not as services), i'm running it using "runas" command with the user that i have created. (user1):
runas /u:user1 msvsmon.exe
Can Someone help me please?
Thanks.

A: The problem that I had is that I had 2 users:
mydomain\user1
mytestmachine\user1

that is not correct (according to Gregg Miskely) i needed to define a local user in my development computer, for example:
mydevcomputer\debug
mytestmachine\debug

with the same password and run the VS2008 and the Debugging Monitor with this user:

A: This is how it worked for me:
Remote computer: Microsoft Virtual PC, "IHS\RDM" attached to my corporate domain, logged in as jdoe, administrator account.
Local computer: Attached to local domain, logged in as jdoe, administrator account.
1) remote computer: install rdbgsetup.exe (from Visual Studio 2005\Disk 2\Remote Debugger\x86)
2) Remote computer: RUNAS /user MYDOMAIN\jdoe /netonly msvsmon
3) Remote computer: msvsmon->Tools->permissions add user "MYDOMAIN\jdoe" (I have to do this every time I re-start)
4) local computer: run msvsmon.
5) local computer, msvsmon->Tools->permissions, add object types: "computers", "IHS\RDM"
6) local computer, vs2005->debug->attach to process. Transport: Default, Qualifier: jdoe@RDM
7) Refresh, and voila; a process list!

A: Gregg Miskely has a blog post on why the service account needs to have admin privileges (when set up that way).  One of the points is that the user account, in your case the user on the Test machine, must have privileges for connecting back to the other computer.  It sounds like you are hitting a case where the account mydomain\user1 has insufficient privileges to connect to your development computer.
If that doesn't help perusing Gregg's blog posts, sending him mail could help.

A: Does TESTCOMPUTER\user1 have the same password as mydomain\user1?
You can also try running msvsmon.exe on the target computer instead of the Remote Debugging Service.  You can use "Run As..." to run it under various credentials.  Once you get things working with msvsmon,exe you should be able to install (or re-enable) the Remote Debugger Service having it run under those credentials.
EDIT:
You should be able to use the Permissions property page in msvsmon.exe to set up the appropriate debugging permissions for your domain user on the target machine:
http://msdn.microsoft.com/en-us/library/ms164722.aspx

A: So you're a developer and one of your users got an exception, and you want to debug it remotely without closing the exception window, but they're logged on as a different user account.  As it turns out, you can debug their application, but it gets tricky.
0) You still need matching local accounts on both the remote app machine and the local Visual Studio machine, which means adding an account to the user's computer.
1) You need to use runas with the /netonly option.  Open a command prompt to the folder where msvsmon is and type
runas /user:[user] /netonly msvsmon

This causes msvsmon to use the user's credentials only when accessing the network (e.g. when msvsmon connects back to the local VS machine).  msvsmon will get upset if you call it with runas without using /netonly.
2) You need to add permissions for the local Visual Studio machine to connect the remote application machine, via the Remote Debug Monitor's Tools->Permissions menu.

A: So I can't reply without an account, and I can only reply to my own comments, but my registered account is separate from the anonymous account I posted from, so this has to be a "new answer".  Sorry.
baget - when I made this work earlier today, I created a local account on both the Remote Debug Monitor PC and Visual Studio PC.  RDM was not on the domain, VS was.  Both local accounts are administrator with credentials identical to my domain account.  From a different account (also administrator) I called runas from an elevated prompt with the netonly switch.  You may or may not need to provide your domain with the username, but since the passwords should all match I don't think it matters much.
Don't forget to adjust your permissions in the RDM to allow the user account running VS to connect with Debug privileges.  It's pretty picky about who it lets you add to the list, so if you don't create the local account first you'll get pretty frustrated.  And if you're running RDM under a different user account name, you have to use the full server name when trying to attach to the remote computer; if you run both RDM and VS from the same user account then you can get away with just the computer name.


text:
Q: Dividing one audio signal by another one Short version
I need to divide an audio signal by another one (amplitude-wise). How could I accomplish this in the Web Audio API, without using ScriptProcessorNode? (with ScriptProcessorNode the task is trivial, but it is completely unusable for production due to the inherent performance issues)
Long version
Consider two audio sources, two OscillatorNodes for example, oscA and oscB:
var oscA = audioCtx.createOscillator();
var oscB = audioCtx.createOscillator();

Now, consider that these oscillators are LFOs, both with low (i.e. <20Hz) frequencies, and that their signals are used to control a single destination AudioParam, for example, the gain of a GainNode. Through various routing setups, we can define mathematical operations between these two signals.
Addition
If oscA and oscB are both directly connected to the destination AudioParam, their outputs are added together:
var dest = audioCtx.createGain();

oscA.connect(dest.gain);
oscB.connect(dest.gain);

Subtraction
If the output of oscB is first routed through another GainNode with a gain of -1, which is then connected to the destination AudioParam, then the output of oscB is effectively subtracted from that of oscA, because we are effectively doing an oscA + -oscB op. Using this trick we can subtract one signal from another one:
var dest = audioCtx.createGain();
var inverter = audioCtx.createGain();

oscA.connect(dest.gain);

oscB.connect(inverter);
inverter.gain = -1;
inverter.connect(dest.gain);

Multiplication
Similarly, if the output of oscA is connected to another GainNode, and the output of oscB is connected to the gain AudioParam of that GainNode, then oscB is multiplying the signal of oscA:
var dest = audioCtx.createGain();
var multiplier = audioCtx.createGain();

oscA.connect(multiplier);
oscB.connect(multiplier.gain);

multiplier.connect(dest.gain);

Division (?)
Now, I want the output of oscB to divide the output of oscA. How do I do this, without using ScriptProcessorNode?

Edit
My earlier, absolutely ridiculous attempts at solving this problem were:

*

*Using a PannerNode to control the positionZ param, which did yield a result that decreased as signal B (oscB) increased, but it was completely off (e.g. it yielded 12/1 = 8.5 and 12/2 = 4.2) -- now this value can be compensated for by using a GainNode with its gain set to 12 / 8.48528099060058593750 (approximation), but it only supports values >=1

*Using an AnalyserNode to rapidly sample the audio signal and then use that value (LOL)

Edit 2
The reason why the ScriptProcessorNode is essentially useless for applications more complex than a tech demo is that:

*

*it executes audio processing on the main thread (!), and heavy UI work will introduce audio glitches

*a single, dead simple ScriptProcessorNode will take 5% CPU power on a modern device, as it performs processing with JavaScript and requires data to be passed between the audio thread (or rendering thread) and the main thread (or UI thread)

A: It should be noted, that ScriptProcessorNode is deprecated.
If you need A/B, therefore you need 1/B, inverted signal. You can use WaveShaperNode to make the inversion. This node needs an array of corresponding values. Inversion means that -1 becomes -1, -0.5 becomes -2 etc.
In addition, make sure that you are aware of division by zero. You have to handle it. In the following code I just take the next value after zero and double it.
function makeInverseCurve( ) {
  var n_samples = 44100,
      curve = new Float32Array(n_samples),
      x;
  for (var i = 0 ; i < n_samples; i++ ) {
    x = i * 2 / n_samples - 1;
    // if x = 0, let reverse value be twice the previous
    curve[i] = (i * 2 == n_samples) ? n_samples : 1 / x;
  }
  return curve;
};

Working fiddle is here. If you remove .connect(distortion) out of the audio chain, you see a simple sine wave. Visualization code got from sonoport.


text:
Q: AngularJS $filter for nested fields does not work as expected I want to filter my shop objects according to their name. But "name" field is nested like:
name: {
    "en": "name english",
    "tr": "name turkish"
}

and params.filter() is :
    name.en:"eng"
If I filter like that:
$filter('filter')($scope.shops, params.filter())

result is an empty array.
Where am I wrong?

A: Angular's filter operates on arrays, not objects.  To do what you need, so long as you are doing in javascript, can be done like this
$scope.shops[params.filter()];

A: I believe your syntax is not correct, try doing something like this.
$filter('filter')($scope.shops, {name: en})[0];
This should return the first value in your object.


text:
Q: Find median of value I have a data set which is a data set of gene nodes. It has a pair of nodes and their is some value as weight given. I have to find a median of the corresponding gene pair. I count the number of times the node pair occurs in entire data set and then calculate the median of the value. Here Col[0] and Col[1] are the node pairs and Col[2] is the weight.  The code below prints the nodes and the median value for odd occurrences correct but for even occurrences it shows the larger value of the two middle values. Any suggestions appreciated.
Input Type:Small list from large file.
5372 937 65.0
4821 937 65.0
4376 937 65.0
2684 937 65.0
4391 3715 1880.0
3436 1174 2383.0
3436 3031 2383.0
3436 1349 2383.0
5372 937 70.0
4821 937 70.0
4376 937 70.0
2684 937 70.0
3826 896 10.0
3826 896 17.0
5372 937 62.0
4821 937 62.0
4376 937 62.0
2684 937 62.0
3826 896 50.0
4944 3715 482.0
4944 4391 482.0
2539 1431 323.0
5372 937 59.0
4821 937 59.0
4376 937 59.0
2684 937 59.0
896 606 11.0
3826 896 10.0
5045 4901 11.0
4921 4901 11.0
4901 3545 11.0
4901 3140 11.0
4901 4243 11.0

code:
from collections import defaultdict
import numpy as np

pt  = defaultdict(float)
pm  = defaultdict(float)
pc  = defaultdict(int)
with open('input.txt', 'r') as f:
    with open('output.txt', 'w') as o:
    for numline, line in enumerate((line.split() for line in f), start=1):
        pair = line[0], line[1]
        pc[pair] += 1
        pt[pair] = float(line[2])
        pm[pair] = np.median(pt[pair])
        print pair, pc[pair], pm[pair]

As per the definition median for even set of numbers is the average value of the two middle numbers and for odd set of number the middle value is the median. How can I get a better median value in case of even set of numbers?

A: Your pt dictionary is not right. You are storing the last weight of each pair, and to compute the median you need the whole list of weights. You could do:
from collections import defaultdict
import numpy as np

pt  = defaultdict(list)
pc  = defaultdict(int)
with open('input.txt', 'r') as f:
    with open('output.txt', 'w') as o:
    for numline, line in enumerate((line.split() for line in f), start=1):
        pair = line[0], line[1]
        pc[pair] += 1
        pt[pair].append(float(line[2]))

# now with the medians
pm  = dict()
for pair, weights in pt.items():
    pm[pair] = np.median(weights)
    print pair, pc[pair], pm[pair]


text:
Q: How to implement momentum in mini-batch gradient descent with python? I was reading about momentum and I was trying to implement the equation of momentum in my mini-batch code.

The problem is that it is not working the regression line is going too far from the ideal line and I`m not sure if the implementation is correct.

def stochastic_gradient_descent_step(m,b,data_sample):

    n_points = data_sample.shape[0] #size of data
    m_grad = 0
    b_grad = 0
    stepper = 0.0001 #this is the learning rate
    z_m = 1.0
    z_b = 1.0
    betha = 0.81

    for i in range(n_points):

        #Get current pair (x,y)
        x = data_sample[i,0]
        y = data_sample[i,1]
        if(math.isnan(x)|math.isnan(y)): #it will prevent for crashing when some data is missing
            #print("is nan")
            continue

        #you will calculate the partical derivative for each value in data
        #Partial derivative respect 'm'
        dm = -((2/n_points) * x * (y - (m*x + b)))

        #Partial derivative respect 'b'
        db = - ((2/n_points) * (y - (m*x + b)))

        #Update gradient
        m_grad = m_grad + dm
        b_grad = b_grad + db

    #calculate the momentum
    z_m = betha*z_m + m_grad
    z_b = betha*z_b + b_grad
    #Set the new 'better' updated 'm' and 'b'
    m_updated = m - stepper*z_m
    b_updated = b - stepper*z_b

return m_updated,b_updated

Edited
I have edited my code now and as Sasha suggested me I put the gradient calculation in one function and the momentum in other and I put z_m and z_b as global so they don't lose their value in each iteration.
z_m =0.0 #initilise to 0
z_b =0.0 #initilise to 0
def getGradient(m,b,data_sample):
    global z_m
    global z_b
    n_points = data_sample.shape[0] #size of data
    m_grad = 0
    b_grad = 0
    stepper = 0.0001 #this is the learning rate

    betha = 0.81

    for i in range(n_points):

        #Get current pair (x,y)
        x = data_sample[i,0]
        y = data_sample[i,1]
        if(math.isnan(x)|math.isnan(y)): #it will prevent for crashing when some data is missing
            #print("is nan")
            continue

        #you will calculate the partical derivative for each value in data
        #Partial derivative respect 'm'
        dm = -((2/n_points) * x * (y - (m*x + b)))

        #Partial derivative respect 'b'
        db = - ((2/n_points) * (y - (m*x + b)))

        #Update gradient
        m_grad = m_grad + dm
        b_grad = b_grad + db

    return m_grad,b_grad

def calculateMomentum(m_grad,b_grad,betha=0.81,stepper=0.0001):
    global z_m,z_b
    #calculate the momentum
    z_m = betha*z_m + m_grad
    z_b = betha*z_b + b_grad
    #Set the new 'better' updated 'm' and 'b'
    m_updated = m - stepper*z_m
    b_updated = b - stepper*z_b
    return m_updated,b_updated

Now the regression line is calculated correctly (maybe). With SGD the final error is 59706304 and with momentum the final error is 56729062, but it could be for the random mini-batch choosen at the moment of calculating the gradient.

A: First of all initialisation is invalid, z_m and z_b should be initialised to 0 (as this is your first guess of the gradient). Second of all in the  current, functional form you never "store" z_m or z_b for next iteration, so they do get reset (to the invalid value of 1)


text:
Q: Redirect with message after success ajax call How to make it when function success redirect user to index page to show message on the page that deletion was successful? So far I was able only to redirect user
$.ajax({
   type: 'get',
   url: 'lessonDel.php',
   data: 'ajax=1&delete=' + upload_id,

   success: function()
   {
        window.location.href = 'index.php';
        //alert('You successfully deleted this Lesson!  Status = ' + xhr.status);
   }
});

A: change window.location.href = 'index.php#lessondelete';
in your index page :
$(function(){
var hash = window.location.hash
if(hash == "#lessondelete") {
  alert('You successfully deleted this Lesson!');
//$('body').prepend('
You successfully deleted this Lesson
')
}
});

A: In addition to accepted answer:
The only problem with the accepted answer is the added #text will not be removed from the URL and if we refresh the page the success message will appear again. So to avoid the message on page refresh change the URL by using the sample code below
history.pushState({},"URL Rewrite Example","https://stackoverflow.com/example")

But you can do it only in browsers that support it. Just try the above line after changing the URL as per your; in your browsers JavaScript-Console


text:
Q: Python Module error even though init file kept
I am not sure what to do here.
The below image shows the heirarchy.

I tried init file in the code.
Kept main.py (not using it) in the parent folder

A: The problem is that "import Data_Upload" looks for that file in the current directory.  In your example, the current directory is E:\Traffic_Dip_4G, and that's not where the module is located.  You need to add the parent of your top-level directory to the Python path (sys.path) so it can be found.
Something like this, BEFORE you do any other imports:
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(__file__)+'/../..'))


text:
Q: multiple type with typescript I have that object that I want to use as a type:
interface MyInput {
    id: string,
    label: string,
    setter: Function,
    type: string,
    value: string | string[] | boolean,
    options?: string[]
}

I have some errors like:

Property 'map' does not exist on type 'string | boolean | string[]'.
Type 'string | boolean | string[]' is not assignable to type 'boolean | undefined'.

The thing is that I will always know whether my value is string[], boolean or string with my type property.
Is there any solution to remove those errors without make 3 different interfaces?
Beside putting my value property to any or to create 3 diffent types, I do not known.

A: You may define the interface with generic type, as in below code
interface MyInput<T = string | string[] | boolean> {
    id?: string,
    label?: string,
    setter?: Function,
    type?: string,
    value: T,
    options?: string[]
}

The actual type can be determined while defining variable, as in below code
let ip: MyInput<string[]> = {
    value: []
}

ip.value.map((v) => {...})

A: You will need to do something to cast it or annotate it with a @ts-ignore.  e.g.
(input.value as string[]).map(...


text:
Q: As if + would is correct as in idiomatic use? Is the second sentence grammatically correct?
"- I want to drive a Ferrari"
"- As if you would be able to drive it"
I know the sentence "As if you were able to drive it" is correct, but can I use the other one instead of "As if!", for example?
Thanks

A: Technically, there may be grounds for objection, though I doubt most native speakers would notice even in writing unless their attention were drawn to it.
"As if" is an abridged clause of comparison, so "as if you would be able to drive it" is the elliptical equivalent of "[you want to drive it] as [you would drive it] if you would be able to drive it." You see how wrong the double conditional looks in that full version.


text:
Q: When converting a project to use ARC what does "switch case is in protected scope" mean? When converting a project to use ARC what does "switch case is in protected scope" mean?
I am converting a project to use ARC, using Xcode 4 Edit -> Refactor -> Convert to Objective-C ARC...
One of the errors I get is "switch case is in protected scope" on "some" of the switches in a switch case.
Edit,
Here is the code:
the ERROR is marked on the "default" case:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"";
    UITableViewCell *cell ;
    switch (tableView.tag) {
        case 1:
            CellIdentifier = @"CellAuthor";
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        cell.textLabel.text = [[prefQueries objectAtIndex:[indexPath row]] valueForKey:@"queryString"];
        break;
    case 2:
        CellIdentifier = @"CellJournal";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        cell.textLabel.text = [[prefJournals objectAtIndex:[indexPath row]] valueForKey:@"name"];

        NSData * icon = [[prefJournals objectAtIndex:[indexPath row]] valueForKey:@"icon"];
        if (!icon) {
            icon = UIImagePNGRepresentation([UIImage imageNamed:@"blank72"]);
        }
        cell.imageView.image = [UIImage imageWithData:icon];

        break;

    default:
        CellIdentifier = @"Cell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
        break;
    }

    return cell;
}

A: There are 2 easy ways to solve this issue:

*

*You are probably declaring variables. Move the declaration of the variables
outside the switch statement

*Put the whole case block in between curly brackets {}

The compiler can not calculate the code line when the variables are to be released.
Causing this error.

A: Surround each case itself with braces {}. That should fix the issue (it did for me in one of my projects).

A: For me, the problem started on the middle of a switch and curly brackets did not worked out, unless you have to include {} IN ALL previous case statements. For me the error came when I had the statement
NSDate *start = [NSDate date];

in the previous case. After I deleted this, then all subsequent case statement came clean from the protected scope error message

A: Before:
    case 2:
        NSDate *from = [NSDate dateWithTimeIntervalSince1970:1388552400];
        [self refreshContents:from toDate:[NSDate date]];
        break;

I moved NSDate definition before switch, and it fixed the compile problem:
NSDate *from;  /* <----------- */
switch (index) {
    ....
    case 2:
        from = [NSDate dateWithTimeIntervalSince1970:1388552400];
        [self refreshContents:from toDate:[NSDate date]];
        break;

}

A: Declare the variables outside the switch, then instantiate them inside the case.
That worked perfectly for me using Xcode 6.2

A: Hard to be sure without looking at the code, but it probably means there's some variable declaration going on inside the switch and the compiler can't tell if there's a clear path to the required dealloc point.

A: default:
        CellIdentifier = @"Cell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            ***initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];***
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
        break;
    }

Note: Check! The syntax of the bold & italicized line. Rectify it and you are good to go.

A: Surround with braces {} the code between the case statement and the break in each case.
It worked on my code.


text:
Q: Parsing cbor stream I'm trying to parse CBOR stream using tinyCBOR. Goal is to write a generic parsing code for "map type"(because i don't know how many keys are there and which are they, in cbor stream)but not for a json, I just want to get values using "key",but for getting values from key i have to know the key.
Im simply able to parse the value by passing "key" in function
cbor_value_map_find_value(&main_value,"Age",&map_value);

but few things still not clear to me.
What sequence to follow, for getting key and values from CBOR stream?
For eg. following is my data in map format -
{"Roll_number": 7, "Age": 24, "Name": "USER"}

here is this binary format from cbor.me link -
   A3                        # map(3)
   6B                        # text(11)
   526F6C6C5F6E756D626572    # "Roll_number"
   07                        # unsigned(7)
   63                        # text(3)
   416765                    # "Age"
   18 18                     # unsigned(24)
   64                        # text(4)
   4E616D65                  # "Name"
   64                        # text(4)
   55534552                  # "USER"

1.How to get key from stream. like - Roll_number or AGE from stream?(sequentially getting key and values also fine).
2.After getting Roll_number value, how can i jump to next element ("Age") for getting "key" and "value".
3.How to identify that i'm reached at the "end of stream" and now there is no data ??
Any snippet code, that how to parse and which sequence of function need to follow.
Any help is appreciate.
Thanks!!!

A: The example code is pretty helpful for understanding the API.  To iterate over the keys and values of a map, you call cbor_value_enter_container, then cbor_value_advance until cbor_value_at_end returns true (as long as there are no nested maps or arrays you want to look inside).  For example:
cbor_parser_init(input, sizeof(input), 0, &parser, &it);
if (!cbor_value_is_map(&it)) {
  return 1;
}
err = cbor_value_enter_container(&it, &map);
if (err) return 1;
while (!cbor_value_at_end(&map)) {
  // get the key.  Remember, keys don't have to be strings.
  if (!cbor_value_is_text_string(&map)) {
    return 1;
  }
  char *buf;
  size_t n;
  // Note: this also advances to the value
  err = cbor_value_dup_text_string(&map, &buf, &n, &map);
  if (err) return 1;
  printf("Key: '%*s'\n", (int)n-1, buf);

  if (strncmp(buf, "Age", n-1) == 0) {
    if (cbor_value_is_integer(&map)) {
      // Found the expected key and value type
      err = cbor_value_get_int(&map, &val);
      if (err) return 1;
      printf("age: %d\n", val);
    }
    // note: can't break here, have to keep going until the end if you want
    // `it` to still be valid.
  }
  free(buf);
  err = cbor_value_advance(&map);
  if (err) return 1;
}
err = cbor_value_leave_container(&it, &map);
if (err) return 1;


text:
Q: Magento eliminating child products to get applicable price I have a script that dynamically retrieves price of configurable products that I have written, and now I am going back and making sure that it takes into account any configurable attributes that there may be. The following is called via ajax and I have debugged it down to the most central part of the loop (therefore all magento methods are working). It should be removing children that do not match the attributes. The end goal is to have one child left, and echo the price. Each child DOES contain a unique price (this I know). Can you see why this is not working right now?
<?php
require_once('/var/www/Staging/public_html/app/Mage.php');
umask(0);
Mage::app();

$product_id = $_POST['productID'];
$optionSelectionArray = $_POST['optionSelectionArray']; //the ids of configurable options selected

//var_dump($optionSelectionArray);

$product =  Mage::getModel('catalog/product')->load($product_id); // no need to use the _ here, it's not protected/private; additonally Mage::registry won't work because you're technically not on a product detail page
$attributes = $product->getTypeInstance(true)->getConfigurableAttributes($product);
$childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null,$product);

//Gather all attribute ids for given product
$availAttrs=[];
foreach($attributes as $attribute){
        $availAttrs[] = $attribute->getAttributeId();
}

foreach($availAttrs as $attr){//cycle available attributes
        foreach ($optionSelectionArray as $key => $value) {//cycle option for key
            if ($attr == $key){//if available attribute and key of optionSelectionArray match
                for($i=0; $i<sizeof($childProducts); $i++){//for each child in children
                    //get label of attribute code
                    foreach($attributes as $attribute){
                        if ($attr == $attribute->getAttributeId()){
                            $attrName = strtolower($attribute->getLabel());//get code name from attribute id
                        }//end if attribute matches attribute id
                    }//end attributes cycle

                    //CAITLIN LEFT OFF echoing the next line here to see if it is doing what it should

                    if($childProducts[$i]->getData($attrName) != $value){
                        array_splice($childProducts, $i, 1);
                    }//end if attribute values match
                    else{
                        echo("This is a match! : ");
                        echo('The vendor is ' . $childProducts[$i]->getData('vendor'). ";");
                        echo (" The price is " . $childProducts[$i]->getPrice());
                    }
                }//end childproducts loop
            }//end if
        }//end foreach optionSelectionArray
    }//end foreach availattrs

//Echo final price $childProducts[0]
?>

A: I put the following around the loops and that made sure I eliminated all products that didn't match.
while(sizeof($childProducts)>1){
//Loops
}


text:
Q: Running Python Program via sshfs-mounted Share I have a share (on Machine-A) mounted via sshfs on Machine-B.  From Machine-C, I have this share mounted also via sshfs (double sshfs) like so:
On Machine-C: /mnt/Machine-B/target_share
On Machine-B: /mnt/Machine-A/target_share
On Machine-A: /media/target_share
Now I have a Python program that runs fine in all places tested (including Machine-C on its local file system) except from Machine-C on the drive that lives on Machine-A, but is mounted on Machine-B.
The reason I am running the Python program from Machine-C is that it has the resources necessary to run it.  I have run it on Machine-A and Machine-B and it has maxed the memory out on each, thereby failing each time.  I have tried to mount the target_share on Machine-B with this type of command as well:
sudo mount -t cifs -o username=<username>,password=<password> //Machine-A/target_share /mnt/target_share
But this doesn't seem to work each way I have tried it, i.e., with different credentials, with and without credentials, etc.
To make matters worse, one caveat is that I can only SSH into Machine-B from Machine-C.  I cannot directly access Machine-A from Machine-C, which, if I could, would probably make all this work just fine.
The Python program runs on Machine-C but the logic in the middle that I need to work doesn't run and gives no errors.  It basically starts, and then ends a few seconds later.
I am relatively new to Python.  Also, not sure if this post would be better on another board.  If so, let me know or move as necessary.
I can post the Python code as well if I need to.
My apologies for the complicated post.  I didn't know how else to explain it.
Thanks in advance.

A: I found that there may be a bug in sshfs, such that if a user on a Linux system has the same user ID as another, i.e., 1002, but different usernames, this causes problems.
The way I worked around this was to actually avoid sshfs for this case all together and mount the drives directly to a local system.  I wanted to avoid this because I couldn't do this from a remote location, but it gets the job done.


text:
Q: remove $ from dataLayer total - google tag manager I have this datalayer on my completion checkout page. everything is working it fires fine. All is well for Adwords. however another ad words tracking script isn't passing the value back to the website. I believe it's because the $ sign. how can i trim the dollar sign off of the summary.total_formatted?
<script>
dataLayer.push({'subtotal':'<%= summary.total_formatted %>'});
</script>

I was thinking something like this here,
dataLayer.push({'subtotal':'<%= summary.total_formatted %>'[0].innerHTML.trim().replace('$','')});

but this is wrong gives me an arrow with the trim actually. what is the best way to handle this so the price is pasted back to the 3rd party website. I just want to exclude the $ sign to test this.

A: You can replace it directly
    var subTotal = '<%= summary.total_formatted %>';
    var dataLayer = [];
    dataLayer.push({'subtotal' : subTotal .replace('$','')});
console.log(JSON.stringify(dataLayer));

Here is a jsfiddle
Hope this helps.


text:
Q: Setting content length of an HTTP POST request I am trying to make a Http POST request using apache HTTP client. I am trying to copy contents of an HTTP POST request (received at my application) to another HTTP POST request (initiated from my application to another URL). Code is shown below:
httpPost = new HttpPost(inputURL);
// copy headers
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
      String headerName = e.nextElement().toString();
      httpPost.setHeader(headerName, request.getHeader(headerName));
}

BufferedInputStream clientToProxyBuf = new BufferedInputStream(request.getInputStream());
BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
basicHttpEntity.setContent(clientToProxyBuf);
basicHttpEntity.setContentLength(clientToProxyBuf.available());

httpPost.setEntity(basicHttpEntity);

HttpResponse responseFromWeb = httpclient.execute(httpPost);

Basically, I am trying to implement a proxy application which will get a url as parameter, froward the request to the URL and then serve pages etc in custom look and feel.
Here request is HttpServletRequest. I am facing problem in setting content length. Through debugging I found out that clientToProxyBuf.available() is not giving me correct length of input stream and I am getting Http error 400 IE and Error 354 (net::ERR_CONTENT_LENGTH_MISMATCH): The server unexpectedly closed the connection in chrome.
Am I doing it wrong? Is there any other way to achieve it?

A: The available() function doesn't provide the actual length of the content of the stream, rather

Returns the number of bytes that can be read from this input stream without blocking. (From javadoc)

I would suggest you to first read the whole content from the stream, and then set that to the content, rather than passing the stream object. That way, you will also have the actual length of the content.

A: It was rather simple and very obvious. I just needed to get content length from header as:
basicHttpEntity.setContentLength(Integer.parseInt(request.getHeader("Content-Length")));


text:
Q: C# RGB[,] to picturebox I have a data that is (2448*2048) 5Mpixel image data, but the picturebox only has (816*683) about 500,000 pixels, so I lowered the pixels and I only need a black and white image, so I used the G value to create the image, but The image I output is shown in the following figure. Which part of my mistake?
 public int[,] lowered(int[,] greenar)
    {
        int[,] Sy = new int[816, 683];
        int x = 0;
        int y = 0;
        for (int i = 1; i < 2448; i += 3)
        {
            for (int j = 1; j < 2048; j += 3)
            {
                Sy[x, y] = greenar[i, j];
                y++;
            }
            y = 0;
            x++;
        }
        return Sy;
    }

static Bitmap Create(int[,] R, int[,] G, int[,] B)
    {
        int iWidth = G.GetLength(1);
        int iHeight = G.GetLength(0);
        Bitmap Result = new Bitmap(iWidth, iHeight,
        System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        Rectangle rect = new Rectangle(0, 0, iWidth, iHeight);
        System.Drawing.Imaging.BitmapData bmpData = Result.LockBits(rect,
        System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        IntPtr iPtr = bmpData.Scan0;
        int iStride = bmpData.Stride;
        int iBytes = iWidth * iHeight * 3;
        byte[] PixelValues = new byte[iBytes];
        int iPoint = 0;
        for (int i = 0; i < iHeight; i++)
        {
            for (int j = 0; j < iWidth; j++)
            {
                int iG = G[i, j];
                int iB = G[i, j];
                int iR = G[i, j];
                PixelValues[iPoint] = Convert.ToByte(iB);
                PixelValues[iPoint + 1] = Convert.ToByte(iG);
                PixelValues[iPoint + 2] = Convert.ToByte(iR);
                iPoint += 3;
            }
        }
        System.Runtime.InteropServices.Marshal.Copy(PixelValues, 0, iPtr, iBytes);
        Result.UnlockBits(bmpData);
        return Result;

    }

https://upload.cc/i1/2018/04/26/WHOXTJ.png

A: You don't need to downsample your image, you can do it in this way. Set picturebox property BackgroundImageLayout as either zoom or stretch and assign it as:
picturebox.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
picturebox.BackgroundImage = bitmap;

System.Windows.Forms.ImageLayout.Zoom will automatically adjust your bitmap to the size of picturebox.

A: You seem to be constantly mixing up your x and y offsets, which can easily be avoided simply by actually calling your loop variables x and y whenever you loop through image data. Also, image data is generally saved line by line, so your outer loop should be the Y loop going over the height, and the inner loop should process the X coordinates on one line, and should thus loop over the width.
Also, I'm not sure where your original data comes from, but in most of the cases I've seen where the image data is in multidimensional arrays like this, the Y is actually the first index in the array. Your actual image building function also assumes this, since it uses G.GetLength(0) to get the height of the image. But your channel resize function doesn't; it makes a multidimensional array as new int[816, 683], which would be a 683*816 image, not 816*683 as you said. So that certainly seems wrong.
Since you confirmed it to be [x,y], I adapted this solution to use it like that.
That aside, you hardcoded a lot of values in your functions, which is very bad practice. If you know you will reduce the image to 1/3rd by taking only one in three pixels, just give that 3 as parameter.
The reduction code:
public static Int32[,] ResizeChannel(Int32[,] origChannel, Int32 lossfactor)
{
    Int32 newWidth = origChannel.GetLength(0) / lossfactor;
    Int32 newHeight = origChannel.GetLength(1) / lossfactor;
    // to avoid rounding errors
    Int32 origHeight = newHeight * lossfactor;
    Int32 origWidth = newWidth *lossfactor;
    Int32[,] newChannel = new Int32[newWidth, newHeight];
    Int32 newX = 0;
    Int32 newY = 0;
    for (Int32 y = 1; y < origHeight; y += lossfactor)
    {
        newX = 0;
        for (Int32 x = 1; x < origWidth; x += lossfactor)
        {
            newChannel[newX, newY] = origChannel[x, y];
            newX++;
        }
        newY++;
    }
    return newChannel;
}

The actual build code, as was remarked by GSerg in the comments, is wrong because you don't take the stride into account. The stride is the actual byte length of each line of pixels, and this is not just width * BytesPerPixel, since it gets rounded up to the next multiple of 4 bytes.
So you need to initialize your array as height * stride, not as height * width * 3, and you need to skip your write offset to the next multiple of the stride whenever you go to a lower Y line, rather than assuming it will just get there automatically because your X processing adds 3 for each pixel. Because it will not get there automatically, unless, by pure coincidence, your image width happens to be a multiple of 4 pixels.
Also, if you only use one channel for this, there is no reason to give it all three channels. Just give a single one.
public static Bitmap CreateGreyImage(Int32[,] greyChannel)
{
    Int32 width = greyChannel.GetLength(0);
    Int32 height = greyChannel.GetLength(1);
    Bitmap result = new Bitmap(width, height, PixelFormat.Format24bppRgb);
    Rectangle rect = new Rectangle(0, 0, width, height);
    BitmapData bmpData = result.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    Int32 stride = bmpData.Stride;
    // stride is the actual line width in bytes.
    Int32 bytes = stride * height;
    Byte[] pixelValues = new Byte[bytes];
    Int32 offset = 0;
    for (Int32 y = 0; y < height; y++)
    {
        Int32 workOffset = offset;
        for (Int32 x = 0; x < width; x++)
        {
            pixelValues[workOffset + 0] = (Byte)greyChannel[x, y];
            pixelValues[workOffset + 1] = (Byte)greyChannel[x, y];
            pixelValues[workOffset + 2] = (Byte)greyChannel[x, y];
            workOffset += 3;
        }
        // Add stride to get the start offset of the next line
        offset += stride;
    }
    Marshal.Copy(pixelValues, 0, bmpData.Scan0, bytes);
    result.UnlockBits(bmpData);
    return result;
}

Now, this works as expected if your R, G and B channels are indeed identical, But if they are not, you have to realize there is a difference between reducing the image to grayscale and just building a grey image from the green channel. On a colour image, you will get totally different results if you take the blue or red channel instead.
This was the code I executed for this:
Int32[,] greyar = ResizeChannel(greenar, 3);
Bitmap newbm = CreateGreyImage(greyar);


text:
Q: Insert data to a custom content type by using webform in drupal 7 I have a custom content type and respect to that I have designed a Webform for normal user. But I want to inset the data of the Webform to my custom content type and display it using view. Display a custom content type in View is know to me but I want to insert data of Webform to the custom content. Is that possible. Is there any other way where I can use a custom form to insert data in a content type. I am using drupal 7.

A: One way to do this is to use views to render the results of the form,
and then adding the view results to the custom node using views node field module.
You will need to create a new view, in the 'Show' box choose 'webform submissions'
Create the view and add it as a custom field in your custom content type.

A: I do this task using webform Rules - create a rule "on submit" event, in which create a new node using the data from the submission, and then redirect to wherever you want.
Hope this helps,
Shushu


text:
Q: Apply css to datalist tag in angular I have an input search box with autocompletion  where I am displaying array of names. I am using datalist tag. When sme names are typed in search text box it will give names present in the array. I am unable to change css of the array shown in dropdown.
my component.html
<input type="text" placeholder="select name"  (keyup)="arrayList($event.target.value)"
id="nameId" list="nameOptions"  formControlName="name">
<datalist id="nameOptions">
<option *ngFor="let name of names | async" [value]="name">
{{name}}
 </option>
</datalist>

I am trying to apply css as follows
my component.css file
datalist{
 position:absolute;
 max-height:50px;
 overflow-x:hidden;
 overflow-y:scroll
 }

Right now it is showing like below

A: Try to use
::ng-deep datalist{
     position:absolute;
     max-height:50px;
     overflow-x:hidden;
     overflow-y:scroll
 }


text:
Q: Can multiplying a pair of almost-one values ever yield a result of 1.0? I have two floating point values, a and b.  I can guarantee they are values in the domain (0, 1).  Is there any circumstance where a * b could equal one?  I intend to calculate 1/(1 - a * b), and wish to avoid a divide by zero.
My instinct is that it cannot, because the result should be equal or smaller to a or b.  But instincts are a poor replacement for understanding the correct behavior.
I do not get to specify the rounding mode, so if there's a rounding mode where I could get into trouble, I want to know about it.
Edit: I did not specify whether the compiler was IEEE compliant or not because I cannot guarantee that the compiler/CPU running my software will indeed by IEEE compliant.

A:
I have two floating point values, a and b…

Since this says we have "values," not "variables," it admits a possibility that 1 - a*b may evaluate to 1. When writing about software, people sometimes use names as placeholders for more complicated expressions. For example, one might have an expression a that is sin(x)/x and an expression b that is 1-y*y and then ask about computing 1 - a*b when the code is actually 1 - (sin(x)/x)*(1-y*y). This would be a problem because C++ allows extra precision to be used when evaluating floating-point expressions.
The most common instances of this is that the compiler uses long double arithmetic while computing expressions containing double operands or it uses a fused multiply-add instructions while computing an expression of the format x + y*z.
Suppose expressions a and b have been computed with excess precision and are positive values less than 1 in that excess precision. E.g., for illustration, suppose double were implemented with four decimal digits but a and b were computed with long double with six decimal digits. a and b could both be .999999. Then a*b is .999998000001 before rounding, .999998 after rounding to six digits. Now suppose that at this point in the computation, the compiler converts from long double to double, perhaps because it decides to store this intermediate value on the stack temporarily while it computes some other things from nearby expressions. Converting it to four-digit double produces 1.000, because that is the four-decimal-digit number nearest .999998. When the compiler later loads this from the stack and continues evaluation, we have 1 - 1.000, and the result is zero.
On the other hand, if a and b are variables, I expect your expression is safe. When a value is assigned to a variable or is converted with a cast operation, the C++ standard requires it to be converted to the nominal type; the result must be a value in the nominal type, without any "extra precision." Then, given 0 < a < 1 and 0 < b < 1, the mathematical value (that, without floating-point rounding) a•b is less than a and is less than b. Then rounding of a•b to the nominal type cannot produce a value greater than a or b with any IEEE-754 rounding method, so it cannot produce 1. (The only requirement here is that the rounding method never skip over values—it might be constrained to round in a particular direction, upward or downward or toward zero or whatever, but it never goes past a representable value in that direction to get to a value farther away from the unrounded result. Since we know a•b is bounded above by both a and b, rounding cannot produce any result greater than the lesser of a and b.)
Formally, the C++ standard does not impose any requirements on the accuracy of floating-point results. So a C++ implementation could use a bonkers rounding mode that produced 3.14 for .9*.9. Aside from implementations flushing subnormals to zero, I am not aware of any C++ implementations that do not obey the requirement above. Flushing subnormals to zero will not affect calculations in 1 - a*b when a and b are near 1. (In a perverse floating-point format, with an exponent range narrower than the significand and no subnormal values, .9999 could be representable while .0001 is not because the exponent required for it is out of range. Then 1-.9999*.9999, which would produce .0002 in normal four-digit arithmetic, would produce 0 due to underflow. No such formats are in normal hardware.)
So, if a and b are variables, 0 < a < 1 and 0 < b < 1, and your C++ implementation is reasonable (may use extra precision, may flush subnormals, does not use perverse floating-point formats or rounding), then 1 - a*b does not evaluate to zero.

A: There is a mathematical proof that it will never be >= 1.  I don't have it handy.... you may want to ask on the math stack overflow site if you are interested in studying the proof. But your instincts are correct.  It will never be >= 1.
Now, we must be careful because floating point arithmetic is only an approximation of math and has limitations.  I'm not an expert on these limitations, but the floating-point standard is very carefully designed and provides certain guarantees. I'm pretty sure one of them includes (or implies) that x * y where x < 1 and y < 1 is guaranteed to be < 1.

A: You can check that even if using the highest float or double that is lower than 1, and multiplying by itself, the result will be lower than 1. Any multiplication of numbers lower than that must give a smaller result.
Here is the code I ran, with the results in comments:
float a = nextafterf(1, 0); // 0.999999940
double b = nextafter(1, 0); // 0.99999999999999989
float c = a * a; // 0.999999881
double d = b * b; // 0.99999999999999978


text:
Q: Getting selected colname as character in R/Shiny I'm trying to subset data based on selected column from selectInput. I have tried:
as.character(input$LabelBubble)

But this doesn't seem to extract the column text. Rest of the code where I select the columns below:
output$LabelBubble = renderUI(if(input$PlotType=="Dynamic Bubble Scatter"){
 mtext <- sapply(loadfile1(), is.factor)
 mcols<-as.list(colnames(loadfile1()[,mtext]))
 selectInput(
  "LabellBubble",
  label = "Select factor variable",
  "",selectize=TRUE,multiple=FALSE,choices=mcols
 )
})

Please advise.

A: I think your problem is when there is only one column in mtext. loadfile1()[,mtext] returns a vector instead of an data.frame. If you are using dplyr you could do something like this instead with better results
mcols<-as.list(colnames(select(iris,one_of(names(mtext)[mtext]))))

hope this helps!!


text:
Q: How does the Mutate_at function work when combined with Recode? I recoded specific columns in my dataframe using this code:
ptsd_copy %>%
mutate_at(vars(AAQ_1, AAQ_4, AAQ_5, AAQ_6), funs(recode(.,
                                                   'never true' = 7,
                                                    'often untrue' = 6,
                                                    'sometimes untrue' = 5,
                                                    'undecided' = 4,
                                                    'sometimes true' = 3,
                                                    'often true' = 2,
                                                    'always true' = 1))) %>%
mutate_at(vars(AAQ_2, AAQ_3, AAQ_7, AAQ_8, AAQ_9), funs(recode (.,
                                                           'never true' = 1,
                                                            'often untrue' = 2,
                                                            'sometimes untrue' = 3,
                                                            'undecided' = 4,
                                                            'sometimes true' = 5,
                                                            'often true' = 6,
                                                            'always true' = 7)))

which works perfectly, but I don't really understand the second argument in the mutate_at function. Why do I need to wrap the recode() function inside funs(), and why do I use a period argument inside recode? My understanding is that mutate_at takes a vars() argument and a function to apply to all the columns specified inside vars. So isn't the funs() redundant?

A: As of version 0.8.0 of dplyr the use of funs() is soft depricated.
library(dplyr)
iris %>%
  mutate_at(vars(Species), funs(recode(.,
                                       "setosa" = 1,
                                       "versicolor" = 2,
                                       "virginica" = 3))) %>%
  head()
#> Warning: funs() is soft deprecated as of dplyr 0.8.0
#> Please use a list of either functions or lambdas:
#>
#>   # Simple named list:
#>   list(mean = mean, median = median)
#>
#>   # Auto named with `tibble::lst()`:
#>   tibble::lst(mean, median)
#>
#>   # Using lambdas
#>   list(~ mean(., trim = .2), ~ median(., na.rm = TRUE))
#> This warning is displayed once per session.
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2       1
#> 2          4.9         3.0          1.4         0.2       1
#> 3          4.7         3.2          1.3         0.2       1
#> 4          4.6         3.1          1.5         0.2       1
#> 5          5.0         3.6          1.4         0.2       1
#> 6          5.4         3.9          1.7         0.4       1

This means that by using version 0.8.0 or newer you don't have to use funs(). You simply use it as before just without funs()
iris %>%
  mutate_at(vars(Species), ~ recode(.,
                                    "setosa" = 1,
                                    "versicolor" = 2,
                                    "virginica" = 3)) %>%
  head()
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2       1
#> 2          4.9         3.0          1.4         0.2       1
#> 3          4.7         3.2          1.3         0.2       1
#> 4          4.6         3.1          1.5         0.2       1
#> 5          5.0         3.6          1.4         0.2       1
#> 6          5.4         3.9          1.7         0.4       1

likewise, you can create a function and pass that in too.
recode_fun <- function(x) {
  recode(x,
         "setosa" = 1,
         "versicolor" = 2,
         "virginica" = 3)
}

iris %>%
  mutate_at(vars(Species), recode_fun) %>%
  head()
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2       1
#> 2          4.9         3.0          1.4         0.2       1
#> 3          4.7         3.2          1.3         0.2       1
#> 4          4.6         3.1          1.5         0.2       1
#> 5          5.0         3.6          1.4         0.2       1
#> 6          5.4         3.9          1.7         0.4       1

Created on 2019-12-08 by the reprex package (v0.3.0)


text:
Q: JavaFX8 : add label on linechart and update them according to a zoom I'm a new JavaFX user, I have some issues into my internship project. I have to make a GUI which draw one spectra and add labels (x value) at the top of each peaks. The user can zoom on chart, so labels must be updated.
I use a first method to add labels based on this post :write text on a chart but i have some trouble, only half of labels are visible (see image) and the update of the labels position are not good after a zoom. I checked each labels value and position, they are good, if i apply an action on my chart, the second half of labels appear, so i don't know the reason of this misunderstanding. My update (labels position) function is a listener of the upperbound yaxis for the zoom, but to have the good positions i need to use my update button manually, i don't find the solution, if someone have ideas ?
I currently use anchorpane, is it better to use stackpane?
I put a part of my code :

public class PaneController implements Initializable{
 @FXML
 private LineChart<Number, Number> lineChart;
 private ObservableList<Annotation> annotationNodes = FXCollections.observableArrayList();

 @Override
 public void initialize(URL location, ResourceBundle resources) {
  // TODO Auto-generated method stub
  lineChart.setLegendVisible(false);
  lineChart.setCreateSymbols(false);
  lineChart.setData(createData());
  //create labels
  createLabels(lineChart.getData());
  //frame listener
  ((AnchorPane)lineChart.getParent()).heightProperty().addListener((num)-> update());
     //axis listener
  ((NumberAxis)lineChart.getYAxis()).upperBoundProperty().addListener((num)-> update());
     //update listener on middle button
     lineChart.getParent().addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
         @Override
         public void handle(MouseEvent event) {
            if( event.getButton() == MouseButton.MIDDLE){
             update();
             }
         }
     });
     MyJFXChartUtil.setupZooming( lineChart );
 }

 /** create data for the line chart */
 public ObservableList<Series<Number,Number>> createData(){
   ObservableList<Series<Number,Number>> data = FXCollections.observableArrayList();
   for(int i=1;i<=10;i++){
    XYChart.Series<Number, Number> peakSelect = new XYChart.Series<>();
    peakSelect.getData().add(new XYChart.Data<Number, Number>(i*2,0));
    peakSelect.getData().add(new XYChart.Data<Number, Number>(i*2,i));
    data.add(peakSelect);
   }
   return data;
 }

   /** place a x-value label on each peak */
   private void createLabels(ObservableList<Series<Number,Number>> data){
      Pane pane = (Pane) lineChart.getParent();
      //clear old annotations
      pane.getChildren().clear();
      pane.getChildren().add(lineChart);
   for(int i=0;i<lineChart.getData().size();i++){
    for(XYChart.Data<Number, Number> value:lineChart.getData().get(i).getData()){
     if(value.getYValue().intValue()>0){
         //massAnnot
         Annotation massAnnot = new Annotation(new Label(""+value.getXValue()), value.getXValue().doubleValue(), value.getYValue().doubleValue());
            annotationNodes.add(massAnnot);
            //labelAnnot
         Annotation labelAnnot = new Annotation(new Label(""+(i+1)), value.getXValue().doubleValue(), 11);
            annotationNodes.add(labelAnnot);
              }
    }
   }
      //add node to parent
      for (Annotation annot : annotationNodes) {
        pane.getChildren().add(annot.getLabel());
      }
   }

   /** update position of labels */
   private void update(){
    //clear nodes and add the linechart as children
    NumberAxis xAxis = (NumberAxis) lineChart.getXAxis();
    NumberAxis yAxis = (NumberAxis) lineChart.getYAxis();
    System.out.println(xAxis.getUpperBound()+" update "+yAxis.getUpperBound());
    Pane pane = (Pane) lineChart.getParent();

    pane.getChildren().clear();
    pane.getChildren().add(lineChart);
    int i = 0;
    for (Annotation annot : annotationNodes) {
     Node node = annot.getLabel();
     if(i%2==0){//massAnnot
      double x = lineChart.getXAxis().localToParent(xAxis.getDisplayPosition(annot.getX()), 0).getX() + lineChart.getPadding().getLeft();
      double y = yAxis.localToParent(0,yAxis.getDisplayPosition(annot.getY())).getY() + lineChart.getPadding().getTop();
      node.setLayoutX(x);
      node.setLayoutY(y - node.prefHeight(Integer.MAX_VALUE));
     }
     else{//labelAnnot
      double x = lineChart.getXAxis().localToParent(xAxis.getDisplayPosition(annot.getX()), 0).getX() + lineChart.getPadding().getLeft();
      double y = yAxis.localToParent(0,yAxis.getDisplayPosition(annot.getY())).getY() + lineChart.getPadding().getTop();
      node.setLayoutX(x);
      node.setLayoutY(y - node.prefHeight(Integer.MAX_VALUE));
     }
     node.autosize();
     pane.getChildren().add(node);
    }
   }

  class Annotation{
   private Label label;
   private double x;
   private double y;

   public Annotation(Label label, double x, double y) {
    this.label = label;
    this.x = x;
    this.y = y;
   }
   public Label getLabel(){
    return this.label;
   }

   public double getX(){
    return this.x;
   }

   public double getY(){
    return this.y;
   }
  }
}
public class Main extends Application {
 @Override
 public void start(Stage primaryStage) {
  try {
   FXMLLoader loader = new FXMLLoader();
   loader.setLocation(Main.class.getResource("Pane.fxml"));
   AnchorPane rootPane = (AnchorPane) loader.load();
   Scene scene = new Scene(rootPane);
   primaryStage.setScene(scene);
   primaryStage.setTitle("Test");

   PaneController controller = loader.getController();

   primaryStage.show();

  } catch(Exception e) {
   e.printStackTrace();
  }
 }

 public static void main(String[] args) {
  launch(args);
 }
}
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.chart.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<AnchorPane xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.PaneController">
   <children>
      <LineChart fx:id="lineChart" prefHeight="400.0" prefWidth="500.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
        <xAxis>
          <NumberAxis side="BOTTOM" />
        </xAxis>
        <yAxis>
          <NumberAxis side="LEFT" />
        </yAxis>
      </LineChart>
   </children>
</AnchorPane>

A: It seems that update is called to fast and the axis haven't updated, so when you update label positions none of the layout values have been updated. You could change your code to this:
private void update() {
    runIn(50, () -> {
        /*your current code*/
    }
}

private void runIn(int ms, Runnable callback) {
    new Thread(() -> {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) { e.printStackTrace(); }
        Platform.runLater(callback);
    }).start();
}

This works because I guess how long the longest Pulse (one screen layout and render) will take. You can view how long pulses take by adding the -Djavafx.pulseLogger=true flag to your JVM args. Every pulse will show on the console. You are looking for this:
...
PULSE: 49 [15ms:29ms]
...

The 29ms is how long it took to layout and render the scene, since 50ms is a good bit longer, when update() ran it got the new values. However, say we have a slow machine, it may take 60ms for a pulse, to long for update() to get the proper values. You would then need to change the 50ms to say, 70ms. It would be better to get a hook on the pulse and see when it ends, then run update(). Unfortunately I have no idea if such a hook exists.