text:
Q: Getting Qt to work in Fedora 12 Qt is installed by default in Fedora 12. Tried the hello world program:
 #include </usr/include/QtGui/QApplication>
 #include </usr/include/QtGui/QPushButton>

 int main(int argc, char *argv[])
 {
   QApplication app(argc, argv);
   QPushButton hello("Hello world!");
   hello.show();
   return app.exec();
}

With normal compilation g++ -o helloWorld helloWorld.cpp, it shows:

/tmp/ccfEv7zR.o: In function main':
  helloWorld.cpp:(.text+0x2a): undefined
  reference to
  QApplication::QApplication(int&,
  char**, int)'
  helloWorld.cpp:(.text+0x53): undefined
  reference to
  QPushButton::QPushButton(QString
  const&, QWidget*)'
  helloWorld.cpp:(.text+0x8b): undefined
  reference toQApplication::exec()'
  helloWorld.cpp:(.text+0x99): undefined
  reference to
  QPushButton::~QPushButton()'
  helloWorld.cpp:(.text+0xac): undefined
  reference to
  QPushButton::~QPushButton()'
  helloWorld.cpp:(.text+0xc0): undefined
  reference to
  QApplication::~QApplication()'
  helloWorld.cpp:(.text+0xdc): undefined
  reference to
  QApplication::~QApplication()'
  /tmp/ccfEv7zR.o: In function
  QString::QString(char const*)':
  helloWorld.cpp:(.text._ZN7QStringC1EPKc[QString::QString(char
  const*)]+0x1d): undefined reference to
  QString::fromAscii_helper(char
  const*, int)' /tmp/ccfEv7zR.o: In
  function QString::~QString()':
  helloWorld.cpp:(.text._ZN7QStringD1Ev[QString::~QString()]+0x2d):
  undefined reference to
  QString::free(QString::Data*)'
  collect2: ld returned 1 exit status
  bash: ./helloWorld: No such file or
  directory

and with

qmake -project;qmake;make

it shows:

/usr/lib64/qt-3.3/bin/moc
  /usr/include/QtGui/qapplication.h -o
  /usr/include/QtGui/moc_qapplication.cpp
  moc: Cannot create
  /usr/include/QtGui/moc_qapplication.cpp
  make: *
  [/usr/include/QtGui/moc_qapplication.cpp]
  Error 1

Any idea how to get it to work?
UPDATE:
My cpp was already in a non-read-only directory. Now I changed the header to
#include <QApplication>
#include <QPushButton>

and it shows this error:

g++ -c -pipe -Wall -W -O2 -g -pipe
  -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -DQT_NO_DEBUG  -I/usr/lib64/qt-3.3/mkspecs/default -I. -I. -I/usr/lib64/qt-3.3/include -o helloWorld.o helloWorld.cpp
  helloWorld.cpp:1:25: error:
  QApplication: No such file or
  directory helloWorld.cpp:2:24: error:
  QPushButton: No such file or directory
  helloWorld.cpp: In function 'int
  main(int, char*)': helloWorld.cpp:7:
  error: 'QApplication' was not declared
  in this scope helloWorld.cpp:7: error:
  expected ';' before 'app'
  helloWorld.cpp:8: error: 'QPushButton'
  was not declared in this scope
  helloWorld.cpp:8: error: expected ';'
  before 'hello' helloWorld.cpp:9:
  error: 'hello' was not declared in
  this scope helloWorld.cpp:10: error:
  'app' was not declared in this scope
  helloWorld.cpp: At global scope:
  helloWorld.cpp:5: warning: unused
  parameter 'argc' helloWorld.cpp:5:
  warning: unused parameter 'argv' make:
  ** [helloWorld.o] Error 1

A: The problem is that /usr/include/QtGui/ is "protected". (You do not have write permissions to that directory)
Move your helloworld.cpp to a directory that you have write access to. For example /home/yourusername/helloworld/helloworld.cpp
Change:
#include </usr/include/QtGui/QApplication>
#include </usr/include/QtGui/QPushButton>

To:
#include <QApplication>
#include <QPushButton>

Then try:
qmake -project
qmake
make

I suggest you read a bit up on using qmake. You will then understand why you had the first error: qmake helps you to get the includes and right libraries step by creating a Makefile for you.
Edit:
Another thing to check is to ensure qmake is in your path and optionally if the QTDIR environment variable is set.

A: From your compile log it's clear that you're using Qt 3.3.
This explains why you still can't get it to work.  The CamelCase-style headers, like QPushButton, were introduced in Qt 4.0.
Most likely you've used Qt 3.3 by accident.  Make sure that you run the qmake from Qt 4.  On many Linux distributions this is installed as qmake-qt4.


text:
Q: Если встречается нечетный элемент, то перед ним и после него вставить новые элементы со значением 0 Изменил код! Теперь имеет такой вид:
void numb_1(TSNum *&Start){

TSNum *wp,*pp,*a,*b;
wp = Start;
pp = NULL;
if(Start == NULL){
    cout << "List is empty!\n";
    return;
}
while(wp != NULL){
    if(wp->numb %2 != 0){
        a = new TSNum;
        b = new TSNum;
        a->numb=0;
        b->numb=0;
        a->next = wp;
          a->prev = wp->prev;
          wp->prev = a;
          if (a->prev = wp->prev)
              a->prev->next = a;
           else
              Start = a;
          if (b->next = wp->next)
            b->next->prev = b;
          b->prev = wp;
          wp->next = b;
          wp = b;
        }
        wp = wp->next;
    }
}

Но работает только вставка после элемента, а перед элементом не вставляет 0
A: @Юра1996, комментарии кончились...
Вы убрали часть кода, которая гарантировала, что первый элемент списка четный и следовательно заголовок списка никогда не будет изменяться, поэтому вот  эти строчки
      a->next = wp;
      a->prev = wp->prev;
      wp->prev = a;
      if (a->prev = wp->prev)
          a->prev->next = a;
       else
          Start = a;

надо изменить.
Для общего случая код должен стать таким
while(wp != NULL) {
  if(wp->numb %2 != 0){
    // make zeros
    a = new TSNum;
    b = new TSNum;
    a->numb=0;
    b->numb=0;

    // add before
    a->next = wp;
    if (a->prev = wp->prev)
      a->prev->next = a;
    else
      Start = a;
    wp->prev = a;

    // add after
    if (b->next = wp->next)
      b->next->prev = b;
    b->prev = wp;
    wp->next = b;

    // b is even, so step forward
    wp = b;
  }
  wp = wp->next;
}

UPDATE
@Юра1996, думаю Вы уже достаточно разобрались в такой реализации и Вам будет интересено взглянуть на более общий случай вставки в список и реализации Вашей конкретной задачи с его использованием.
Сделаем функцию, которая вставляет новый элемент в список после заданного или в начало списка, если вместо заданного элемента передаем NULL.
Tnum *
ins2list (Tnum **list, Tnum *after, Tnum *item)
{
  if (item->prev = after) {
    if (item->next = after->next)
      item->next->prev = item;
    after->next = item;
  } else {
    item->prev = 0;
    if (item->next = *list)
      item->next->prev = item;
    *list = item;
  }
  return item;
}

Я использую передачу указателя на указатель списка, а не ссылку, т.к. считаю использование ссылок в подобном контексте попросту вредным. Да, код получается может и чуть короче, но программисту, читающему вызывающую функцию абсолютно не понятно (без изучения вызываемой) может ли указатель быть изменен внутри вызова.
Тогда, остальной код может выглядеть так:
typedef struct numbs {
  int numb;
  struct numbs *next, *prev;
} Tnum;

static Tnum * randTnum (int vmax) {
  Tnum *x = new Tnum;
  x->numb = rand() % vmax;

  return x;
}

static void pri_list (Tnum *list) {
  for (;list; list = list->next)
    printf("%d [%p,%p]\n", list->numb, list->next, list->prev);
}

static void add_zodd (Tnum **plist) {
  for (Tnum *cur = *plist; cur; cur = cur->next)
    if (cur->numb & 1) {
      Tnum *z = new Tnum;
      z->numb = 0;
      ins2list(plist, cur->prev, z);
      z = new Tnum;
      z->numb = 0;
      cur = ins2list(plist, cur, z);
    }
}

int
main (int ac, char *av[])
{
  int n = atoi(av[1] ? av[1] : "5");
  Tnum *list = 0, *last;

  // to begin of list (as stack push)
  for (int i = 0; i < n; i++)
    last = ins2list(&list, 0, randTnum(10));

  // 3 items to end of list
  for (int i = 0; i < 3; i++)
    last = ins2list(&list, last, randTnum(20));

  pri_list(list);
  puts("== add zeros around odd iems ==");
  add_zodd(&list);
  pri_list(list);
}

Обратите внимание, что функция ins2list() возвращает адрес вставляемого элемента. Часто это удобный прием при программировании списков.

redpajama_set_name: RedPajamaStackExchange


text:
Q: data from my form refused to be saved to database php I have this form where i input data and then send to database but it isn't sending and also there is no error showing even after checking the Network dev tool instead it shows success which i echoed out at the end of the php file
HTML
<form id="hd_FU">

        Code
        <input type="text" id="code" name="code" placeholder="...">

        Title
        <input type="text" id="codeT" name="codeT" placeholder="...">

        Upload File
        <input type="file" style="width: 100% !important;
        margin-left: 0;
        margin-top: 5px;" id="hd_file" accept=".pdf, .PDF, .docx, .doc" name="hd_file">

    <button type="submit" id="hdSub" name="hdSub" class="btnSub">Submit</button>
</form>

JS
$('form#hd_FU').submit(function(e) {
    var form_data = new FormData(this);
    $.ajax({
        type: "POST",
        url: "./db_bked/uploadHD.php",
        data: form_data,
        cache:false,
        contentType: false,
        processData: false,
        beforeSend: function() {
            $("#hdSub").html('uploading....');
        },
        success: function(data) {
            if(data == 'success') {
                alert("ok")
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
        alert(jqXHR.responseText);
        }
    })
    e.preventDefault();
})

PHP
<?php
session_start();

require "../dbconn.inc/conn.php";

$userId = mysqli_real_escape_string($conn, $_SESSION['userId'] ?? "");

$code = $_POST['code'];
$codeT = $_POST['codeT'];

$dlr = "../PDF/handout/";
$uploadedFile = '';

$userproductImg = $_FILES["hd_file"];
$productFileName = $userproductImg['name'];
$productFileTmpName = $userproductImg['tmp_name'];
$productFileSize = $userproductImg['size'];
$productFileError = $userproductImg['error'];

$productFileExt = explode('.', $productFileName);
$productFileActualExt = strtolower(end($productFileExt));
$productFileAllowed = array('pdf', 'PDF');

if (in_array($productFileActualExt, $productFileAllowed)) {
    if ($productFileError === 0) {
        if ($productFileSize < 100000000) {
            $productFiles = uniqid(''. true).".".$productFileActualExt;
            $productFileDestination = $dlr.$productFiles;
            $uploadedFile = $productFiles;
            move_uploaded_file($productFileTmpName, $productFileDestination);
        }
    }
}

$sql = $conn->prepare("INSERT INTO hd_bk (code, userId, topic,  bk_filename) VALUES (?, ?, ?, ?)");
$sql->bind_param("ssss", $code, $userId, $codeT, $uploadedFile);
$sql->execute();

echo "success";

DATABASE
CREATE TABLE `hd_bk` (
    `bkId` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `code` text NOT NULL,
    `userId` int(11) NOT NULL,
    `topic` longtext NOT NULL,
    `bk_filename` text NOT NULL,
    `bk_date` datetime NOT NULL DEFAULT current_timestamp()
  )

Please does anyone know what i need to do cause am not seeing the data in my database - xampp - phpmyadmin


text:
Q: Android Window Manager Layout Inflater is not inflating a full screen layout I have been attempting to learn Android Java shenanigans, so still very new to it. I managed to get a Service working that inflates a layout to create a TYPE_SYSTEM_OVERLAY. The layout is a transparent red, but only takes up the middle part of my screen. My hope was to have it cover and fill the entire screen.
This is what happens:

Main Layout XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#0092a3">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Activate"
        android:id="@+id/btnActivate"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Exit"
        android:id="@+id/btnExit"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="25dp"
        android:layout_marginBottom="25dp"
        android:width="100dp" />

</RelativeLayout>

Overlay Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#40ff0000">

</LinearLayout>

Service Class onCreate method:
@Override public void onCreate() {
    super.onCreate();

    final WindowManager.LayoutParams params = new  WindowManager.LayoutParams(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
            PixelFormat.TRANSLUCENT);

    windowManager = (WindowManager) getApplicationContext()
            .getSystemService(Context.WINDOW_SERVICE);

    li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    mTopView = (ViewGroup) li.inflate(R.layout.red_overlay, null);

    windowManager.addView(mTopView, params);
}

Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        >
        <activity
            android:name=".MainActivity"
            android:theme="@android:style/Theme.Translucent"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>
        <service android:name=".Layer" />

    </application>

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
</manifest>

Everything works great! And I am quite proud of myself for getting this far. Sadly, I cannot figure out why it won't fill the screen. Any help is much appreciated.

A: It figures after I make a post I solve my problem. I just kept searching google and I found this helpful piece of heaven.
The new and improved Service:
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.MATCH_PARENT,
        WindowManager.LayoutParams.MATCH_PARENT,
        WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
        WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
        PixelFormat.TRANSLUCENT);

windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);

li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
mTopView = (LinearLayout) li.inflate(R.layout.red_overlay, null);

windowManager.addView(mTopView, params);

Switched ViewGroup to LinearLayout.
Switched FLAG_FULLSCREEN to MATCH_PARENT. And, Viola.


text:
Q: pyinstaller exe fails - fusionscript.dll problem [Thanks to Charles Duffy for the gentle nudging toward a clearer question! I am new to Stack Overflow and appreciate the help. After more research, it appears that the dependent code is actually within Blackmagic's fusionscript.dll code (If the .dll is missing, my exe is able to continue past the line of my code which tries to import) , so I don't see any way to get around it until they update.]
Original question:
I'm stuck trying to get a pyinstaller executable to work on a Windows 10 test system. My exe works fine on a system that has Python 3.6.8 installed.
Complete code is below. The print command that starts with "trying:" succeeds and shows the correct path for the import. The print command immediately after the import command print("Made it past import") is not executed, and the exe quits without showing any errors.
I've determined that there's just one file that is necessary for the exe to run on the test system, and that's the os.py file in the Lib folder of the Python install. Without that file, the exe just quits (without any error message) when it hits the line of code: script_module = imp.load_dynamic("fusionscript", path + "fusionscript" + ext)
For anyone trying to reproduce: the exe runs when a Python 3.6.8 install is present, or more specifically, when os.py is. I made the installer with a simple pyinstaller importTest.py command. I place the fusionscipt.dll in the folder with the resulting executable. If os.py is present, the exe runs normally and prints all of it's print commands. If you remove os.py from the Python Lib directory, this is no longer the case, and the exe quits when it hits the imp command.
NOTE: I know that imp is deprecated, but the API that my code engages with (fusionscript.dll for Resolve) only works with Python 3.6, so I can't use anything newer.

Here's the code:
from PyQt5.QtCore import QObject
import sys
import imp
import os
CURR_DIR = os.getcwd()
sys.path.append(CURR_DIR)
script_module = None
ext = ".dll"
path = CURR_DIR+"\\"
try:
    print("trying: " + path + "fusionscript" + ext)
    script_module = imp.load_dynamic("fusionscript", path + "fusionscript" + ext)
    print("Made it past import")
except ImportError:
    pass
print("script module = ",script_module)


text:
Q: How to automatically segment video using ffmpeg without re-encoding? I have a 2 hour video. I want to make 30 minute sections but avoid re-encoding. So 2 hours of video into four 30 minute videos. How can I do this using a single ffmpeg command?
I am using Ubuntu 16.04 64-bit.

A: You can use the segment muxer:
ffmpeg -i input.mp4 -map 0 -c copy -f segment -segment_time 1800 -reset_timestamps 1 output_%03d.mp4

*

*In this example output files will be named output_000.mp4, output_001.mp4, etc.

*Segments may not be exactly 30 minutes long because it must cut on keyframes only.


text:
Q: connect to a tcpListener with a extended class of tcpClient I've created a new class inherited TcpClient class that has a property named (for example) ClientName  . here is this class's definition :
Public Class MyTcpClient
    Inherits Net.Sockets.TcpClient

    Private _ClintName As String

    Sub New(ByVal host As String, ByVal port As Integer, ByVal ClientName As String)
        MyBase.New()
        _ClintName = ClientName
    End Sub

    Public Property ClientName()
        Get
            Return _ClintName
        End Get
        Set(ByVal value)
            _ClintName = value
        End Set
    End Property
End Class

I created an instant of this class and tried to connect this client to a server (TcpListener) with below code :
Try
    client = New MyTcpClient(ip, port , "ClientName")
Catch ex As Exception
    xUpdate("Can't connect to the server!")
End Try

But  every time I try to connect to the server an error occur with this massage :
"System.InvalidOperationException: The operation is not allowed on non-connected sockets."
Now , if I change  MyTcpClient to Net.Socket.TcpClient every thing will be ok.
Try
    client = New Net.Socket.TcpClient(ip, port)
Catch ex As Exception
    xUpdate("Can't connect to the server!")
End Try

Is there any way to connect to a TcpListener with an extended class of TcpClient like my class?

A: Notice that, in the code that you say works, you're using the TcpClient constructor that has parameters for IP address and port number.  Now look at your derived class definition.  Does it use that constructor?  No, it doesn't.  It uses the constructor with no parameters.  That constructor does not connect because it doesn't know what to connect to.  If you expect your derived class to connect then you have to have it call a method that actually connects.  The obvious solution is to change this:
Sub New(ByVal host As String, ByVal port As Integer, ByVal ClientName As String)
    MyBase.New()

to this:
Sub New(ByVal host As String, ByVal port As Integer, ByVal ClientName As String)
    MyBase.New(host, port)

A: thanks jmcilhinney ....
i tested your code , so now my first error is removed , but on the server side a new error occur . the error message is :
"Unable to cast object of type 'System.Net.Sockets.TcpClient' to type 'ServerChat.MyTcpClient'."
the code in server side is :
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
    Dim NewClient As MyTcpClient
    Listning = New TcpListener(GetMyIP, 3818)
    Listning.Start()
    UpdateList("Server Starting", False)
    Listning.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listning)
End Sub

Sub AcceptClient(ByVal ar As IAsyncResult)
    NewClient = Listning.EndAcceptTcpClient(ar)
    UpdateList("New Client Joined!", True)
    Listning.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listning)
End Sub

the error occue in AcceptClient sub on first line :
NewClient = Listning.EndAcceptTcpClient(ar)

should i do any change on tcpListener object or something like that? or my attempt basically is wrong?


text:
Q: Module ngAnimate is not available I am trying to inject ngAnimate in my angular project but I am facing error "Module 'ngAnimate' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument."
Here is what i did:
1) install dependencies by running "npm install angular-animate --save"
package.json
    {
"name": "roles",
  "version": "0.0.3",
  "description": "Role management system",
  "main": "index.js",
  "kibana": {
    "version": "kibana"
  },
  "scripts": {
    "lint": "eslint",
    "start": "plugin-helpers start",
    "test:server": "plugin-helpers test:server",
    "test:browser": "plugin-helpers test:browser",
    "build": "plugin-helpers build",
    "postinstall": "plugin-helpers postinstall"
  },
  "devDependencies": {
    "@elastic/eslint-config-kibana": "0.0.2",
    "@elastic/plugin-helpers": "^6.0.0",
    "babel-eslint": "4.1.8",
    "chai": "^3.5.0",
    "eslint": "1.10.3",
    "eslint-plugin-mocha": "1.1.0"
  },
  "dependencies": {
    "angular": "^1.4.7",
    "angular-animate": "^1.7.6",
    "angular-aria": "^1.4.14",
    "angular-material": "^1.1.12",
    "angular-messages": "^1.4.14"
  }
}

2) app.js
import moment from 'moment';
import chrome from 'ui/chrome';
import { uiModules } from 'ui/modules';
import uiRoutes from 'ui/routes';
import 'ui/autoload/styles';
import './less/main.less';
import template from './templates/index.html';

uiRoutes.enable();
uiRoutes
.when('/', {
  template,
  resolve: {
    currentTime($http) {
      return $http.get('../api/roles/example').then(function (resp) {
        return resp.data.time;
      });
    }
  }
});

uiModules
.get('app/roles', ['ngAnimate',
'ngAria',
'ngMessages',
'ngMaterial'])
.controller('rolesHelloWorld', function ($scope, $route, $interval,$mdThemingProvider) {
  $mdThemingProvider.theme('red')
      .primaryPalette('red');
console.log(ngmaterial);
    $mdThemingProvider.theme('blue')
      .primaryPalette('blue');

      $scope.theme = 'red';

      var isThemeRed = true;

app.js
3) index.html

  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">

Congratulations

You've successfully created your first Kibana Plugin!

{{ title }}

{{ description }}

The current time is {{ currentTime }}

    We have an interval that changes the color of the button from red to blue themes,
    Open the dialog to see the theme being inherited to the dialog and any component inside

  <md-button class="md-primary md-raised" ng-click="showAdvanced($event)">Open Dialog</md-button>

4) Error
Error: [$injector:modulerr] Failed to instantiate module kibana due to: [$injector:modulerr] Failed to instantiate module app/roles due to: [$injector:modulerr] Failed to instantiate module ngAnimate due to: [$injector:nomod] Module 'ngAnimate' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. http://errors.angularjs.org/1.4.7/$injector/nomod?p0=ngAnimate minErr/<@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:759 setupModuleLoader/</</<@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:16521 ensure@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:15527 setupModuleLoader/</<@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:16040 loadModules/<@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:31840 forEach@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:1421 loadModules@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:31512 loadModules/<@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:31889 forEach@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:1421 loadModules@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:31512 loadModules/<@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:31889 forEach@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:1421 loadModules@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:31512 createInjector@http://localhost:5601/bundles/commons.bundle.js?v=8467:36:2586 doBootstrap@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:12235 bootstrap@http://localhost:5601/bundles/commons.bundle.js?v=8467:35:12764 5157/chrome.bootstrap@http://localhost:5601/bundles/commons.bundle.js?v=8467:87:23901 0@http://localhost:5601/bundles/roles.bundle.js?v=8467:1:314 __webpack_require__@http://localhost:5601/bundles/commons.bundle.js?v=8467:1:211 window.webpackJsonp@http://localhost:5601/bundles/commons.bundle.js?v=8467:1:862 @http://localhost:5601/bundles/roles.bundle.js?v=8467:1:1

I don't know what am I doing wrong here?


text:
Q: whether the paper trail has a way to track the user activity based on a specific role I'm trying to use paper trail to track user activity in my application. i have set up the gem, followed the tutorial and made it work fine in my application..
but, when I test it as an ordinary user (as a guest user), paper trail also tracks this guest activity which the same model and controller...
Is there any way how to track the user activity based on role ?
i mean, i just want to track the activity of a specific role..
Need help..
paper trail

A:
i just want to track the activity of a specific [user] role

You can turn PaperTrail off in your controller. From the documentation:

Turning PaperTrail Off
Per Request
Add a paper_trail_enabled_for_controller method to your controller.
class ApplicationController < ActionController::Base
  def paper_trail_enabled_for_controller
    !(cool_user? || trustworthy?) # :) this part is up to you
  end
end

If that doesn't work, there are many other ways to turn PaperTrail on/off described the documentation.


text:
Q: How to get the current (working) directory in Scala? How can I get the current directory (working directory) of the executing program in Scala?

A: Use this:
import scala.reflect.io.File
File(".").toAbsolute

A: I use new java.io.File(".").getAbsolutePath, but all the other answers work too. You don't really gain anything by using Scala-specific API here over regular Java APIs

A: import scala.sys.process._
val cwd = "pwd".!!  //*nix OS

A: Use this
System.getProperty("user.dir")
Edit:
A list of other standard properties can be found here. https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

A: Use java.nio:
import java.nio.file.Paths
println(Paths.get(".").toAbsolutePath)

Remark on scala.reflect.io.File: I don't see any reason to look into scala.reflect packages for such mundane tasks. Getting the current working directory has usually nothing to do with Scala's reflection capabilities. Here are more reasons not to use scala.reflect.io.File: link.

A: os-lib makes it easy to get the current working directory and perform other filesystem operations.  Here's how to get the current directory:
os.pwd

It's easy to build other path objects from os.pwd, for example:
os.pwd/"src"/"test"/"resources"/"people.csv"

The syntax is intuitive and easy to remember, unlike the other options.  See here for more details on how to use the os-lib project.


text:
Q: How to put temporary aliases in a file? I can put aliases in my .bashrc (or files called from it) and they then work in my shell.
I can also then create other aliases at the command line, e.g.
alias aaa='ls'

and it works.   aaa does an ls operation
But if I put that alias definitions in a file, say aaa_alias, make it executable and then try and use it, it is not recognized.
I call it with ./aaa_alias and get no error.  But the aliases does not sem to have been defined in my shell.
Why not?  What am I doing wrong?  How can I have a small number of aliases ina separate file than I just use occasionally when I want and so I invoke it when I went them.

A: In order to insert the contents of a file into your current session, you need to source the file, not execute it.
. my_file

When you were just executing the file, the aliases were being set in a subshell and therefore had no effect on your current session.


text:
Q: Confused by python descriptors and __get__() This a simple class, i just want to test the feature about __get__()
The code is :
class Des(object):
    def __init__(self,num):
        self.num = num
    def __get__(self, obj, typ = None):
        return self.num

class A(object):
    des = Des(1)
    print 'the des in class is ',des

a = A()
print  'the des in object is ',a.des
print a.__dict__
print A.__dict__

the output is :
the des in class is  <Des object at 0x7f5fb550ded0>
the des in object is  1
{}
{'__dict__': <attribute '__dict__' of 'A' objects>, '__module__': '__builtin__', 'des': <Des object at 0x7f5fb550ded0>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}

my question is why the why the outputs of des are des is different (one is 1 type(int), one is object type(Des)). And the output of a.__dict__ and A.__dict is also different. What's the fucntion of __get__(), and how to use it.

A:
why the outputs of des are different (one is 1 type(int), one is object type(Des)).

In the first case, you are print the instance of Des in the A class statement's body. At this point it's nothing else than an ordinary Python object - no descriptor protocol involved since you are not doing an attribute access on a class or instance, since the A class doesn't even exist yet - so you get the default representation of the Des object.
In the second case, you are looking up (attribute access) the name des on an instance of A. The attribute resolution mechanism (implemented in object.__getattribute__) finds the name des in A.__dict__ and finds out the associated object implements __get__, so it calls A.__dict__["des"].__get__(a, A) and returns the result - in this case A.dict["des"].num, which isint(1)`.

And the output of a.__dict__ and A.__dict__ is also different.

Yes of course. A.__dict__ is the dict of class A, a.__dict__ is the dict of instance a. Why would you expect same to share the same dict ?

What's the function of __get__(), and how to use it.

Martijn Pieters's links will answer this question.

A: in your code the  des is a class attribute and in a descriptor it(class attr) will call the get() ,in the next  a.des calls the  call() method so , thats the reason you got the different output (in your example output).


text:
Q: Use one Data Constructor into two different Types Now I'm trying to write a toy-language-frontend using Haskell.
And there are two entities:

*

*rvalue - variables and integer-literals (for example)

*lvalue - variables only.

I think the most natural way to describe this in data structures is:
data LValue = Var String
data RValue = Var String | Lit Int

(I really think this is the best approach - not verbose and strict enough thanks exhaustive pattern matching)
But ghc shows me error: "multiple declarations of Var".
So the question is: what's the most straightforward way in Haskell to describe what I want?
Noteces:
There is a similar question 11 years ago with no good answer. But has anything changed for 11 years?
One value constructor belonging to two different types
And there is some other approaches with "packing" LValue again (and again and again in less-toy-language) in data-constructor like this:
data LValue = Var String
data RValue = LValue LValue | Lit Int

But I doubt is this good way: AST-transformation code becomes too verbose.

A: I actually think your proposal is the best:
newtype LValue = Var String -- newtype is slightly better here, I think
data RValue = LValue LValue | Lit Int

It is almost certainly the case that any time you use an lvalue as an rvalue, you want to treat all lvalues in a uniform way, so you likely won't need or want to do a second level of pattern matching at that moment; in other words, I claim there will be less verbosity than you might expect at first.
There are basically two alternatives. The first is to make a class:
newtype LValue = LVar String
data RValue = RVar String | Lit Int

class HasVariables ty where var :: String -> ty
instance HasVariables LValue where var = LVar
instance HasVariables RValue where var = RVar

This way you can use var for constructing either LValues or RValues. You will still need to distinguish between them syntactically when pattern-matching though.
The second is to make a GADT:
data Side = L | R
data Value side where
    Var :: String -> Value side
    Lit :: String -> Value R


text:
Q: Converting struct in main() into function version I'm new to C programming. I just figured out how to read csv files into C by struct, but struggling to convert the script into a function, then call this function in int main(). I'll need to read loads of csv files so a function will be very helpful.
Here is my code which runs successfully (non-function version):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXROWS 2

struct cudaScenarioStruct{
    char *type;
    int trial;
    int yPC;
    int yPE;
    int n;
};

struct cudaScenarioStruct cudaScenario[MAXROWS];

int main(){
int rowIndex = 0;
char line[128];
char* token = NULL;
FILE* fp = fopen("C:/Users/ms710557/Desktop/cudaScenario1(2).csv","r");
if (fp != NULL){
    while (fgets( line, sizeof(line), fp) != NULL && rowIndex < MAXROWS){

        cudaScenario[rowIndex].type = malloc(2);
        token = strtok(line, ",");
        strcpy(cudaScenario[rowIndex].type, token);

        token = strtok(NULL, ",");
        cudaScenario[rowIndex].trial = atoi(token);

        token = strtok(NULL, ",");
        cudaScenario[rowIndex].yPC = atoi(token);

        token = strtok(NULL, ",");
        cudaScenario[rowIndex].yPE = atoi(token);

        token = strtok(NULL, ",");
        cudaScenario[rowIndex].n = atoi(token);

        rowIndex++;
    }
    fclose(fp);
}

for (int i = 0; i < MAXROWS; ++i){
    printf("%s, %i, %i, %i, %i \n", cudaScenario[i].type, cudaScenario[i].trial, cudaScenario[i].yPC, cudaScenario[i].yPE, cudaScenario[i].n);
}

return 0;
}

The results look like this:
NI, 1, 61, 55, 80
NI, 2, 54, 59, 80

However when I convert it into a function and include the function in int main(), it's just not working... I've been googling for hours and couldn't find out why. This is my attempt:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXROWS 2

struct cudaScenarioStruct{
    char *type;
    int trial;
    int yPC;
    int yPE;
    int n;
};

struct cudaScenarioStruct *readCudaScenarioData(){
    struct cudaScenarioStruct csvData[MAXROWS];

    int rowIndex = 0;
    char line[128];
    char* token = NULL;
    FILE* fp = fopen("C:/Users/ms710557/Desktop/cudaScenario1(2).csv","r");
    if (fp != NULL){
        while (fgets( line, sizeof(line), fp) != NULL && rowIndex < MAXROWS){

            csvData[rowIndex].type = malloc(2);
            token = strtok(line, ",");
            strcpy(csvData[rowIndex].type, token);

            token = strtok(NULL, ",");
            csvData[rowIndex].trial = atoi(token);

            token = strtok(NULL, ",");
            csvData[rowIndex].yPC = atoi(token);

            token = strtok(NULL, ",");
            csvData[rowIndex].yPE = atoi(token);

            token = strtok(NULL, ",");
            csvData[rowIndex].n = atoi(token);
            rowIndex++;
        }
        fclose(fp);
    }

    return csvData;
}

int main()
{

    struct cudaScenarioStruct *cudaScenario;
    cudaScenario = readCudaScenarioData();

    for (int i = 0; i < MAXROWS; ++i){
        printf("%s, %i, %i, %i, %i \n", cudaScenario[i].type,
cudaScenario[i].trial, cudaScenario[i].yPC, cudaScenario[i].yPE,
cudaScenario[i].n);
    }

    return 0;
}

Any help will be highly appreciated!


text:
Q: What would be an example of an anaphoric conditional in Lisp? What would be an example of an anaphoric conditional in Lisp? Please explain the code as well.

A: An example is the Common Lisp LOOP:
(loop for item in list
      when (general-predicate item)
      collect it)

The variable IT has the value of the test expression. This is a feature of the ANSI Common Lisp LOOP facility.
Example:
(loop for s in '("sin" "Sin" "SIN")
      when (find-symbol s)
      collect it)

returns
 (SIN)

because only "SIN" is a name for an existing symbol, here the symbol SIN. In Common Lisp symbol names have internally uppercase names by default.

A: Paul Graham's On Lisp has a chapter on Anaphoric Macros.
Essentially, it's a shorthand way of writing statements that avoids repeating code. For example, compare:
(let ((result (big-long-calculation)))
  (if result
      (foo result)))

and
(if (big-long-calculation)
    (foo it))

where it is a special name that refers to whatever was just calculated in (big-long-calculation).


text:
Q: Python 3.4: List to Dictionary I have a string as follows :
['Total Revenue', 31821000, 30871000, 29904000, 'Cost of Revenue', 16447000, 16106000, 15685000, 'Gross Profit', 15374000, 14765000, 14219000, 'Research Development', 1770000, 1715000, 1634000, 'Selling General and Administrative', 6469000, 6384000, 6102000, 'Non Recurring', '-', '-', '-', 'Others', '-', '-', '-', 'Total Operating Expenses', '-', '-', '-', 'Operating Income or Loss', 7135000, 6666000, 6483000, 'Total Other Income/Expenses Net', 33000, 41000, 39000, 'Earnings Before Interest And Taxes', 7168000, 6707000, 6522000, 'Interest Expense', 142000, 145000, 171000, 'Income Before Tax', 7026000, 6562000, 6351000, 'Income Tax Expense', 2028000, 1841000, 1840000, 'Minority Interest', -42000, -62000, -67000, 'Net Income From Continuing Ops', 4956000, 4659000, 4444000, 'Discontinued Operations', '-', '-', '-', 'Extraordinary Items', '-', '-', '-', 'Effect Of Accounting Changes', '-', '-', '-', 'Other Items', '-', '-', '-', 'Net Income', 4956000, 4659000, 4444000, 'Preferred Stock And Other Adjustments', '-', '-', '-', 'Net Income Applicable To Common Shares', 4956000, 4659000, 4444000]

there is a pattern that is 1 : 3 within the list.  Is there anyway I can transform this list into a dictionary as exemplified below.
{Total Revenue : [31821000, 30871000, 29904000], Cost of Revenue : [16447000, 16106000, 15685000] ... ... ... }

I think it can be done through a dictionary comprehension.

A: You can use unpacking operation within a dict comprehension :
>>> my_dict={i:j for i,*j in [l[i:i+4] for i in range(0,len(l),4)]}
>>> my_dict
{'Non Recurring': ['-', '-', '-'], 'Total Other Income/Expenses Net': [33000, 41000, 39000], 'Selling General and Administrative': [6469000, 6384000, 6102000], 'Net Income From Continuing Ops': [4956000, 4659000, 4444000], 'Effect Of Accounting Changes': ['-', '-', '-'], 'Net Income Applicable To Common Shares': [4956000, 4659000, 4444000], 'Net Income': [4956000, 4659000, 4444000], 'Other Items': ['-', '-', '-'], 'Others': ['-', '-', '-'], 'Earnings Before Interest And Taxes': [7168000, 6707000, 6522000], 'Income Before Tax': [7026000, 6562000, 6351000], 'Extraordinary Items': ['-', '-', '-'], 'Total Operating Expenses': ['-', '-', '-'], 'Interest Expense': [142000, 145000, 171000], 'Preferred Stock And Other Adjustments': ['-', '-', '-'], 'Gross Profit': [15374000, 14765000, 14219000], 'Total Revenue': [31821000, 30871000, 29904000], 'Income Tax Expense': [2028000, 1841000, 1840000], 'Operating Income or Loss': [7135000, 6666000, 6483000], 'Cost of Revenue': [16447000, 16106000, 15685000], 'Minority Interest': [-42000, -62000, -67000], 'Research Development': [1770000, 1715000, 1634000], 'Discontinued Operations': ['-', '-', '-']}

And if you want to preserve the order you can use collections.OrderedDict :
>>> from collections import OrderedDict
>>> my_dict=OrderedDict((i,j) for i,*j in [l[i:i+4] for i in range(0,len(l),4)])
>>> my_dict
OrderedDict([('Total Revenue', [31821000, 30871000, 29904000]), ('Cost of Revenue', [16447000, 16106000, 15685000]), ('Gross Profit', [15374000, 14765000, 14219000]), ('Research Development', [1770000, 1715000, 1634000]), ('Selling General and Administrative', [6469000, 6384000, 6102000]), ('Non Recurring', ['-', '-', '-']), ('Others', ['-', '-', '-']), ('Total Operating Expenses', ['-', '-', '-']), ('Operating Income or Loss', [7135000, 6666000, 6483000]), ('Total Other Income/Expenses Net', [33000, 41000, 39000]), ('Earnings Before Interest And Taxes', [7168000, 6707000, 6522000]), ('Interest Expense', [142000, 145000, 171000]), ('Income Before Tax', [7026000, 6562000, 6351000]), ('Income Tax Expense', [2028000, 1841000, 1840000]), ('Minority Interest', [-42000, -62000, -67000]), ('Net Income From Continuing Ops', [4956000, 4659000, 4444000]), ('Discontinued Operations', ['-', '-', '-']), ('Extraordinary Items', ['-', '-', '-']), ('Effect Of Accounting Changes', ['-', '-', '-']), ('Other Items', ['-', '-', '-']), ('Net Income', [4956000, 4659000, 4444000]), ('Preferred Stock And Other Adjustments', ['-', '-', '-']), ('Net Income Applicable To Common Shares', [4956000, 4659000, 4444000])])

Also as a more pythonic and efficient way for grouping your list you can use following grouper function from python itertools recipes
>>> def grouper(iterable, n, fillvalue=None):
...     "Collect data into fixed-length chunks or blocks"
...     # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
...     args = [iter(iterable)] * n
...     return zip_longest(*args, fillvalue=fillvalue)
...
>>>
>>> from itertools import zip_longest
>>> my_dict=OrderedDict((i,j) for i,*j in grouper(l,4))
>>> my_dict
OrderedDict([('Total Revenue', [31821000, 30871000, 29904000]), ('Cost of Revenue', [16447000, 16106000, 15685000]), ('Gross Profit', [15374000, 14765000, 14219000]), ('Research Development', [1770000, 1715000, 1634000]), ('Selling General and Administrative', [6469000, 6384000, 6102000]), ('Non Recurring', ['-', '-', '-']), ('Others', ['-', '-', '-']), ('Total Operating Expenses', ['-', '-', '-']), ('Operating Income or Loss', [7135000, 6666000, 6483000]), ('Total Other Income/Expenses Net', [33000, 41000, 39000]), ('Earnings Before Interest And Taxes', [7168000, 6707000, 6522000]), ('Interest Expense', [142000, 145000, 171000]), ('Income Before Tax', [7026000, 6562000, 6351000]), ('Income Tax Expense', [2028000, 1841000, 1840000]), ('Minority Interest', [-42000, -62000, -67000]), ('Net Income From Continuing Ops', [4956000, 4659000, 4444000]), ('Discontinued Operations', ['-', '-', '-']), ('Extraordinary Items', ['-', '-', '-']), ('Effect Of Accounting Changes', ['-', '-', '-']), ('Other Items', ['-', '-', '-']), ('Net Income', [4956000, 4659000, 4444000]), ('Preferred Stock And Other Adjustments', ['-', '-', '-']), ('Net Income Applicable To Common Shares', [4956000, 4659000, 4444000])])

A: I would make a helper function that takes your data and generates it in chunks, along with a key:
def generate_revenues(data):
    data = iter(data)
    while True:
        key = next(data)
        values = [next(data), next(data), next(data)]
        yield key, values

Making the dictionary is then as simple as:
>>> dict(generate_revenues(data))

which gives:
{'Cost of Revenue': [16447000, 16106000, 15685000],
 'Discontinued Operations': ['-', '-', '-'],
 'Earnings Before Interest And Taxes': [7168000, 6707000, 6522000],
 ...
 'Total Operating Expenses': ['-', '-', '-'],
 'Total Other Income/Expenses Net': [33000, 41000, 39000],
 'Total Revenue': [31821000, 30871000, 29904000]}

Technical note for people from the future: The generator raises a StopIteration exception in order to stop iterating. In a future version of Python this will be disallowed, and you'll need to guard the calls to next with a try: except StopIteration: block.

A: indeed it can:
assert len(lst) % 4 == 0
{lst[4*i]: lst[4*i+1:4*(i+1)] for i in range(len(lst)/4)}


text:
Q: redis-cli not working if port is changed I am using redis 2.4 . When I change the port in "redis.conf" file to another port redis-cli stops working. It shows

Could not connect to Redis at 127.0.0.1:6379: Unknown error not
  connected>

A: The redis.conf file dictates the server's behavior. To tell the command line interface to connect to your newly-defined-non-default port, use the -p switch, e.g.:
$ redis-cli -p 12758


text:
Q: Modifying XML response in WCF; broken XML I am trying to modify response from a Web Service using a ClientMessageInspector. At some point I need to create a Message from a modified XMLStream. The content of the stream is below:
<soapenv:Envelope xmlns:soapenv="http://env" xmlns:xsd="http://xsd" xmlns:xsi="http://xsi" xmlns:v1="http://v1">
    <soapenv:Body>
        <v1:VM>
            <SH>
                aa
                bb
            </SH>
        </v1:VM>
    </soapenv:Body>
</soapenv:Envelope>

I try to create the message using:
System.Xml.XmlReader XMLReader = System.Xml.XmlReader.Create(XMLStream);
Message ModifiedReply = System.ServiceModel.Channels.Message.CreateMessage(OriginalReply.Version, null, XMLReader);

However when I print the Message content with Message.ToString() I get:
<s:Envelope xmlns:s="http://env">
    <s:Header />
        <s:Body>
            ... stream ...
        </s:Body>
</s:Envelope>

How can I prevent "...stream..." and get the actual XML parts?

A: A message when created from a XmlReader will always print out ...stream... as its body. Since the reader is a forward-only view on the underlying XML, it cannot be consumed multiple times, so if ToString were to read the data from the reader, the message wouldn't be able to be used by the rest of the WCF pipeline (such as the encoder, which would write it to the wire).
What you can do, if you really want to see the full message, is to buffer the message yourself, then recreate it later. You can use a MessageBuffer for that. And if you really want the full message contents, ToString may or may not give it to you, so you need to write the message out to force it to be printed.
public class StackOverflow_12609525
{
    public static void Test()
    {
        string xml = @"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""
            xmlns:xsd=""http://xsd""
            xmlns:xsi=""http://xsi""
            xmlns:v1=""http://v1"">
        <soapenv:Body>
            <v1:VM>
                <SH>
                    aa
                    bb
                </SH>
            </v1:VM>
        </soapenv:Body>
    </soapenv:Envelope>";
        MemoryStream XmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
        XmlReader reader = XmlReader.Create(XmlStream);
        Message originalReply = Message.CreateMessage(reader, int.MaxValue, MessageVersion.Soap11);
        Console.WriteLine(originalReply); // this shows ...stream...
        Console.WriteLine();

        XmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
        reader = XmlReader.Create(XmlStream);

        Message modifiedReply = Message.CreateMessage(reader, int.MaxValue, originalReply.Version);
        MessageBuffer buffer = modifiedReply.CreateBufferedCopy(int.MaxValue); // this consumes the message

        Message toPrint = buffer.CreateMessage();
        MemoryStream ms = new MemoryStream();
        XmlWriterSettings ws = new XmlWriterSettings
        {
            Indent = true,
            IndentChars = "  ",
            OmitXmlDeclaration = true,
            Encoding = new UTF8Encoding(false)
        };
        XmlWriter w = XmlWriter.Create(ms, ws);
        toPrint.WriteMessage(w);
        w.Flush();
        Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));

        modifiedReply = buffer.CreateMessage(); // need to recreate the message here
    }
}


text:
Q: RenderScript "slow" blur I've been fiddling around with RenderBlur on an image for my login screen, i've gotten everything to work with a runnable() and a delay to blur the image immediately, however i'm trying to make it a slow blur while the username and password fields come into view.
I've had a bit of a look around (could be looking in the wrong places) but I haven't found anything related to what i'm after. I've attempted to use a while loop and have a blurradius value increment with a delay afterwards and send to the blurBitmap class method, but it either still blurs it immediately (meaning I probably messed something up somewhere and will most likely keep trying with this method until a better solution is found).. or it crashes.
Does anyone know if, in the first place this is possible with RenderScript? And if so, what should I be searching for.
Thanks for any help you can provide.
Resources: https://futurestud.io/blog/how-to-use-the-renderscript-support-library-with-gradle-based-android-projects

A: You can do this with RenderScript, though how you are doing it now doesn't sound like a good idea.  Look into using a custom Animator which you can then run a RS blur against the image.  Using Animator will be more flexible in the long run and automatically ties in with the view system rather than requiring you to handle View or Activity state explicitly.
The approach @JasonWihardja outlined will also work, but again I would suggest doing this in an Animator or similar mechanism.

A: Blurring an image repeatedly might cause some performance issues with your app.
Here's what you could do:

*

*Arrange 2 images (1 for the clear image and the other for the
maximum blur version) so that the blur image is placed exactly on
top of the clear image. The easiest way would be placing 2 ImageViews in a FrameLayout

*To achieve the "slow" blur effect, initially set the blur image's alpha to 0.

*Then, using one of the view, issue a postDelayed event to slowly increase the blur image's alpha to 255.


text:
Q: Evaluate $\lim_{x\to-2}(3x^4+2x^2-x+1)$ $$\lim_{x\to-2}(3x^4+2x^2-x+1)$$
I have to evaluate this limit without using 'continuity ideas'. So I assume I cannot substitute $-2$ into the function and find the limit, can I? How do I go about finding this limit then?

A: We can guess that $\lim_{x \to -2} (3x^{4}+2x^{2}-x+1)=59$ and to prove this we can use definition to show that $\forall \varepsilon>0 \: \exists \delta>0 \:\forall x\: |x-(-2)|=|x+2|<\delta$ we have
$$|3x^4+2x^2-x+1-59|=|x+2||3x^3-6x^2+14x-29|\le \varepsilon$$
then assume wlog $|x+2|<1$ that is $-3<x<-1$ then
$$|x+2||3x^3-6x^2+14x-29|\le \delta|3x^3-6x^2+14x-29| \le 206 \,\delta$$
since $f(x)=x^3-6x^2+14x-29$ is negative strictly increasing for $x\in[-3,-1]$ and $|f(-3)|=206$, then it suffices to assume
$$\delta \le \frac{\varepsilon}{206}$$
Refer also to the related

*

*Finding a "suitable" $\delta$ given a limit

*A question regarding (ε, δ)-definition of limit

A: Since that
$$lim_{x \to -2} 3x^{2}=3(-2)^{4},$$
$$\lim_{x\to -2}2x^{2}=2(-2)^{2},$$
$$\lim_{x\to -2}-x=-(-2)$$and $$\lim_{x \to -2}1=1$$Therefore you can conclude that $$\lim_{x \to -2} (3x^{4}+2x^{2}-x+1)$$exists and also $$\lim_{x \to -2} (3x^{4}+2x^{2}-x+1)=3(-2)^{4}+2(-2)^{2}-(-2)+1=59.$$
Note that you only need the property's of limits.


text:
Q: How to use the R implementation of the Apriori or FP-Growth algorithm starting from a CSV file? I have a CSV file with twelve fields: the first six represent events, the other six actions. For example:
q,w,e, , , ,a,s,d,f, ,
q,t,y,i, , ,s,f,g, , ,
w,r, , , , ,d,f,g,j,k,l

...and so on (I inserted the blank spaces only for ease of reading, but in the original file there are no spaces).
The order of events in the first six positions is not important (q,w is the same of w,q). The same applies to actions in the last six positions.
I need to find out all the rules like:
single event => list of actions (one or more)
...with a given support and a given confidence. How can I achieve this using the R implementation of the "Apriori" or "FP-Growth" algorithm?
Thanks in advance,
Tony


text:
Q: Google Calendar layout I have been working with this php code, which should modify Google Calendars layout. But when I put the code to page, it makes everything below it disappear. What's wrong with it?
<?php
$your_google_calendar=" PAGE ";
$url= parse_url($your_google_calendar);
$google_domain = $url['scheme'].'://'.$url['host'].dirname($url['path']).'/';

// Load and parse Google's raw calendar
$dom = new DOMDocument;
$dom->loadHTMLfile($your_google_calendar);

// Change Google's CSS file to use absolute URLs (assumes there's only one element)
$css = $dom->getElementByTagName('link')->item(0);
$css_href = $css->getAttributes('href');
$css->setAttributes('href', $google_domain . $css_href);

// Change Google's JS file to use absolute URLs
$scripts = $dom->getElementByTagName('script')->item(0);
foreach ($scripts as $script) {
$js_src = $script->getAttributes('src');
if ($js_src) { $script->setAttributes('src', $google_domain . $js_src); }
}

// Create a link to a new CSS file called custom_calendar.css
$element = $dom->createElement('link');
$element->setAttribute('type', 'text/css');
$element->setAttribute('rel', 'stylesheet');
$element->setAttribute('href', 'custom_calendar.css');

// Append this link at the end of the element
$head = $dom->getElementByTagName('head')->item(0);
$head->appendChild($element);

// Export the HTML
echo $dom->saveHTML();
?>

A: When I'm testing your code, I'm getting some errors because of wrong method call:
->getElementByTagName should be ->getElementsByTagName with s on Element
and
->setAttributes and ->getAttributes should be ->setAttribute and ->getAttribute without s at end.
I'm guessing that you don't have any error_reporting on, and because of that don't know anything went wrong?


text:
Q: is there any workaround for returning the value of res from readCsv() method instead of undefined? the scenario is i am having the file uploader, which accept .json,.csv file after having file, If i clicked on upload button ,then homeComponent call the service dataparser , which is having two function readJson readCsv, and readcsv
function
returning the observable other one returns array ,this is simple i have to call the both function
on if else and handle the subscriber and array on HomeComponent
But wait i do not want to handle these complexities at component level so i want to return only array of data on the home component page so, I have handle these on service but observable creating problem in this
**dataparser.service.ts having threee methods**
async uploadDocument() {
const type = this.checkType();
if(!type) return;
 let m = type == "csv" ?  await this.readCsv() : await this.readJson();
 if(m){
  console.log(m);
  return m;
}
console.log(" m is empty");
}

readJson method is returning array of objects and m is not empty if type of file is json its returning m to caller function on homeComponent
private  readJson() {
    return new Promise((resolve,reject) =>{
      const fr: FileReader = new FileReader();
      fr.readAsText(this.file);
      fr.onerror = () =>{
        fr.abort();
        reject(new DOMException("Problem parsing input  file."));
      }
      fr.onload = () =>{
        resolve(JSON.parse(fr.result as string));
      }})
  }

readCsv method is returning empty varaiable(res) due to subscribe method is there any workaround through which i could get valve of res from readCsv function and i do not want subscribe this method anywhere because i do not want handle these two result on homeComponent page, so then how can i get the value of this res varaible from readCsv
private async readCsv() {
    let res: any[];
     this.ngxCsvParser.parse(this.file, { header: this.header, delimiter: ',' })
    .pipe().subscribe((result: Array<any>) => {

      // console.log('Result', result);
       res = result;
    }, (error: NgxCSVParserError) => {
      console.log('Error', error);
    });
    if(res)
    {
      console.log(" i got m");
      return res;
    }
  }

A: You cannot await Observables directly, however, you can await a Promise. You can simply use the .toPromise() method on the observables subscription. Consider the following:
const date = await dateSubscription.toPromise();
private async readCsv() {
    let res: any[];
   res= await this.ngxCsvParser.
     parse(this.file, { header: this.header, delimiter: ',' }).toPromise()
    if(res)
    {
      console.log(" i got m");
      return res;
    }
  }


text:
Q: input data with angular i try to learn angular.
i want to create an input, when we input data then the data will show up on same page.
my code like this

{{name}}
          remove

    <form action="" ng-submit="addName()">
      first name :
      <input type="text" ng-model="firstname">
      last name :
      <input type="text" ng-model="lastname">
      <input type="submit" value="add">
    </form>

var myApp = angular.module('myApp', []);
        myApp.controller('nameCtrl',function($scope){
    // ARRAY
    $scope.names=['firstname1 lastname1','firstname2 lastname2','firstname3 lastname3'];
    // ADD NAME
    $scope.addName= function(){
    $scope.names.push($scope.firstname +' '+ $scope.lastname);
    $scope.firstname="";
    $scope.lastname="";
  };
    //REMOVENAME
    $scope.removename= function(name){
    var i= $scope.names.indexOf(name);
    $scope.names.splice(i,1);
    };
});

on local (my computer) its work, but when i try to test it with jsfiddle. it didnt work, doest this this mean the code can work at online?
here the example:
https://jsfiddle.net/hec57h2a/

A: aw silly me i forgot to bring tag html on jsfiddle, sorry.

A: Add ng-app in body , it will work

A:  replace first line

A: Add AngularJS in your HTML file.


text:
Q: Sharepoint REST API - Create InformationRightsManagementSettings To create IRM settings using REST API, I am referring to document https://msdn.microsoft.com/en-us/library/office/jj247077.aspx
As per documentation, it suggest below REST endpoint to create new IRM:
POST http://<sitecollection>/<site>/_api/web/lists(listid)/InformationRightsManagementSettings

Howerver the post body is not given in documentation. I tried using below as post body however API is returning Bad request.
POST body : {'policyTitle':'IRM'}

Need to understand how to set IRM setting object properties.


text:
Q: prevent session timeout in older tab I have an ASP.NET web application with an angular REST client, every user works on multiple tabs for long periods of time and session is timing out (inactivity) even if the user is active on the second tab.
Is there a way to prevent this behavior?
increasing session timeout is not a solution since users can be inactive in the tab but active in the browser up to 4 hours.
thanks in advance.


text:
Q: Поиск в небинарном дереве по ключу Поиск в небинарном дереве. Каждый узел в дереве имеет N-ное число потомков. Как осуществить поиск требуемого элемента?
Структура узла:
struct Node
{
    int key = 0; //ключ
    int id = 0; //индекс
    int level = 0; //уровень в иерархии
    Node* parent = nullptr; //указатель на родителя
    Node** son = nullptr; //массив указателей на сыновей
    int count_son = 0; //количество сыновей
};

Моя нерабочая функция рекурсивного поиска
Node* Find(Node* root, int key) // Ищет узел с указанным ключом
{
    if (root == NULL)
        return NULL;

    if (root)
    {
        Node* cur = root;
        for (int i = 0; i < cur->count_son; i++)
        {
            if (cur->key == key)
                return cur;
            cur = cur->son[i];
            Find(cur, key);
        }
    }
}


text:
Q: Heroku node.js and Flask application working locally but not in server I have a web application which uses node.js and communicates with a Flask application to retrieve some configurations and send jobs to the back-end. The Flask returns a JSON with the information
Flask file (REST.PY):
from flask import Flask, jsonify, request, redirect, url_for
import subprocess

import os
import json
from cross_domain import *
app = Flask(__name__)

...

@app.route('/api/v1.0/proteins', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_protein_names():
proteins = os.walk(TARGET).next()[1]
protein_lst = [{"filename": protein} for protein in sorted(proteins) if  protein != "scripts"]
return jsonify({"files": protein_lst})

if __name__ == '__main__':
app.run(debug=True,port=9000)

and here is the js code:
...

this.restAddr = "http://127.0.0.1:9000";

...

this.httpGet = function(url, callback) {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
  if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
    callback(xmlHttp.responseText);
  }
};

...

httpGet(restAddr + "/api/v1.0/proteins", populateProteins);

I'm currently using this buildback in order to run both commands in the Procfile. It works when I run locally with foreman start, but when I deploy to Heroku the frameworks doesn't communicate with each other anymore and there is no response in the XMLHTTPRequests. I can still work with the node.js part, though.
Here is the Heroku logs:
...
2016-06-16T20:08:59.174025+00:00 app[web.1]: buildpack=runit ps=python at=start
2016-06-16T20:08:59.174156+00:00 app[web.1]: buildpack=runit ps=node at=start
2016-06-16T20:09:04.490687+00:00 app[web.1]:  * Running on http://127.0.0.1:9000/ (Press CTRL+C to quit)
2016-06-16T20:09:04.515389+00:00 app[web.1]:  * Restarting with stat
2016-06-16T20:09:05.138990+00:00 heroku[web.1]: State changed from starting to up
2016-06-16T20:09:05.568687+00:00 app[web.1]:  * Debugger is active!
2016-06-16T20:09:05.593316+00:00 app[web.1]:  * Debugger pin code: 237-920-039
2016-06-16T20:09:06.730693+00:00 app[web.1]: Succeeded connected to: <MONGODB_URI> in port 35556

Here is what appears when running Foreman:
 $ foreman start -f Procfile.local
14:59:30 node.1   | started with pid 21241
14:59:30 python.1 | started with pid 21242
14:59:31 python.1 |  * Running on http://127.0.0.1:9000/ (Press CTRL+C to quit)
14:59:31 python.1 |  * Restarting with stat
14:59:31 python.1 |  * Debugger is active!
14:59:31 python.1 |  * Debugger pin code: 215-168-436
14:59:31 node.1   | Succeeded connected to: mongodb://localhost/algdock in port 3000

I need an insight about why is not working when it's deployed or if there is some another better approach to this problem.
EDIT: using gunicorn for python it gives the Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Procfile.web
web: node gui/web_app/AlGDock/bin/www
web: gunicorn --pythonpath gui/api --bind 127.0.0.1:9000 wsgi:app

wsgi.py
from REST import app
if __name__ == "__main__":
    app.run()

Heroku Logs:
2016-06-17T00:35:25.808594+00:00 heroku[web.1]: Starting process with command `bin/runsvdir-dyno`
2016-06-17T00:35:26.398041+00:00 heroku[web.1]: Process exited with status 0
2016-06-17T00:35:28.003708+00:00 app[web.1]: buildpack=runit ps=web at=start
2016-06-17T00:35:28.376799+00:00 app[web.1]: [2016-06-17 00:35:28 +0000] [15] [INFO] Starting gunicorn 19.6.0
2016-06-17T00:35:28.377454+00:00 app[web.1]: [2016-06-17 00:35:28 +0000] [15] [INFO] Listening at: http://127.0.0.1:9000 (15)
2016-06-17T00:35:28.377583+00:00 app[web.1]: [2016-06-17 00:35:28 +0000] [15] [INFO] Using worker: sync
2016-06-17T00:35:28.385995+00:00 app[web.1]: [2016-06-17 00:35:28 +0000] [20] [INFO] Booting worker with pid: 20
2016-06-17T00:35:28.826322+00:00 app[web.1]: /app/target/
2016-06-17T00:35:28.826340+00:00 app[web.1]: /app/AlGDock/
2016-06-17T00:36:25.826633+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

A: If you are running a web dyno then heroku needs to be able to connect to it within 60s or it assumes that it isn't working and shuts down the dyno. The port heroku uses isn't set so you need to grab the port from the dynos environment I had the same error when starting out as you have no control over what port heroku assigns.
The node + express version is
app.set('port', (process.env.PORT));
This question shows the how to grab this value when using flask Deploying Flask app to Heroku
Edit:
Also from heroku python docs
port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)


text:
Q: Mark the question as "Closed" or "Answered" Many questions (often old) holds the proper answers sometimes in the comment section, or as an answer but are not marked answered.

Suggestion:
What if users with high reputation could mark the question as "Closed" or "Answered". That could even need to be reviewed.
I'm not saying that they could choose which answer is the correct one. The point is to provide a way to close them, because those questions are still showing in the unanswered list even if in practice they answered.

I believe this is a problem because the community will tends to be reluctant to provide answers for old questions in general, because they might never be marked answered anyway.
Thus, the old questions that really needs answer are mixed up among them. So, it becomes harder to be efficient at looking for Unanswered questions.
Any opinion about that?

A:
I believe this is a problem because the community will tends to be reluctant to provide answers for old questions in general, because they might never be marked answered anyway.

I've seen no evidence of that. Good answers to questions, no matter how old, "bump" the question to the home page and tend to accumulate a sizable number of up-votes. And two up-votes are worth more than a single accept anyway—(10 + 10) > 15. There's no active disincentive for people to answer old questions; you even get badges for doing so!
This being your central justification, I therefore don't see much point in the feature you suggest. It would just introduce an extra layer of unneeded complexity to the system.
Moreover, consider that:

*

*Upvotes already provide sufficient indication of which answers are "useful", and if there's a highly-upvoted answer that has floated to the top, it should be pretty obvious that the question is "answered" or "resolved", regardless of how the question is otherwise marked.

*How and why should people other than the asker get to decide if their question has been sufficiently answered? It doesn't matter that we'd not be choosing a specific answer. The mere fact that we're deciding if and when a question has been answered is problematic. That should be something that is reserved exclusively for the person who asks the question in the first place.
As mentioned above, the way the community decides and indicates such is through voting on the answers.

*The labeling of questions that have been answered as "closed" is a really problematic one. On Stack Exchange sites, "closed" means something entirely different! In particular, it means that the question is not a good fit for the site and that no new answers are being accepted. That's very different than a question for which a good answer has already been provided. If someone else comes along later with a better answer, we encourage them to post it. We don't want to close these questions of which you speak, or even deter future users from attempting to answer them.

A: There is a way to mark a question as answered: upvote the correct answer. The definition of the "unanswered" view is "questions with no upvoted (or accepted) answers", so casting your vote will take it out of that view.
(If the answer is in a comment, then it should be transferred to an answer.)

A: As a brand new user I came to this page seeking how to close a question or vote the answer up (or at least give my answerer some kudos or something).
The answer came in the form of a comment. It was a simple question/answer.  While I can't speculate that some discussion couldn't take place still, I am satisfied the answer is good (it met all my criteria).
So I would like to mark it as closed but I can't.  I believe that actually unanswered question should be labeled as such, and those that have been answered should also be labeled as answered.
It would help when searching to divide answered from unanswered... and when posting, as it would make it easier to see if the question has been asked (I will only check so many pages of results to see if my question has been asked before).
At the very least a moderator should be able to mark a question answered upon request.
As to new answers to questions being relevant, true, but the answered category could still leave commenting available for discussion, and voting as well, maybe a "better" answer may be found, but more importantly, new comments to answered questions should bring it back to the top.


text:
Q: Can I upload App to App store developed in Xcode 10.1 and Swift 4.2 Recently I developed an app and I want to submit it to the App store, but I developed this app on Xcode 10.1 in which maximum support Swift version is 4.2 and deployment target in 12.1
       now question I want to ask as Apple released Xcode 10.2 with Swift 5. so can I upload this app to app store or it is necessary to develop this app in Xcode 10.2?

A: Apple required iOS app to be built with iOS 12 SDK which comes with Xcode 10 (reference).
Apple now requires iOS app to be built with Xcode 10.1. (reference).
So as long as you build your app with Xcode 10.1 or higher you will be fine for now.

A: I think you should use Application Loader or AppUpLoader to upload the build on appStore.


text:
Q: Show/hide buttons depending on screen size Is it possible to show/hide buttons depending on if the user is using 3.5 inch or 4 inch?
For example, if the view controller is loaded with 3.5 inch the button is hidden, and if it is loaded with a 4.0 inch device the button is shown?

A: You can't get the physical size of the screen, but you can get its resolution. The 4" iPhone 5 and the new iPod touch have 320×568 points, while the other iPhones have 320×480. You can get these dimensions using [[UIScreen mainScreen] bounds].size.
It's of course possible that Apple releases a new phone that has the same pixel dimensions as the 4" iPhone 5, but uses a 5" (or whatever) screen, or that they release a device that has completely different dimensions. Your code should ideally be prepared for that, and not make the assumption that these dimensions are set in stone. On the other hand, this kind of change typically doesn't happen overnight.
So, if you want to hide a button on devices with "small" screens, you could do something like this:
- (void)viewDidLoad {
    self.myButton.hidden = [[UIScreen mainScreen] bounds].size.height <= 480;
}


text:
Q: How to shutdown Ubuntu on the computer without power button I am searching for the way how to shutdown Ubuntu with no use of shutdown command.
I've ever done the shutdown on the computer with power button using /etc/acpi/events/powerbtn
This time, I have to physically shut down on the computer(Advantec EPC-T2285) with the power switch.
But, I don't know how to physically shut down Ubuntu.
Please give me the help to do this.

A: From a terminal / ssh prompt run sudo shutdown -h now to power down the server.
Also poweroff might work.

A: As any user as long as that user is the only one logged in it is possible to poweroff as follows as well. systemctl poweroff

A: You could just use sudo shutdown -h now or shutdown -r now
In order to give you more details please read the Ubuntu shutdown documentation
   -r     Requests that the system be rebooted after it has been brought down.

   -h     Requests  that the system be either halted or powered off after it has been brought
          down, with the choice as to which left up to the system.

A: as per the model number you provided in your question..(Advantec EPC-T2285)
it has power button

as a example: in Ubuntu 18.10 (may be similar up to some previous versions)
you can configure the options in settings

once, you configured it to poweroff and once you press physical button
it will prompt you with below options.. you can choose the options immediately or leave it for 60secs so that system will auto powroff..


text:
Q: Hex to character and print letter by letter Hello I'm working on a program that would have hex in an array:
data = ['000000'] #random dummy hex

and I'm trying to decode the hex and print the characters letter from letter as if someone was typing:
def typer(type):
s = bytearray.fromhex(type).decode()
for y in type:
 sleep(0.1)
 sys.stdout.write(y)
 sys.stdout.flush()

And what's happening is that it will print out the hex number from number instead of converting it to it's string and printing the string letters from letter. But when i put:
def typer(type):
s = bytearray.fromhex(type).decode()
for y in type:
 sleep(0.1)
 sys.stdout.write(s)
 sys.stdout.flush()

It spams the string instead, but i want it to do letter from letter as if someone was typing, and doesn't stop until it's at the end of the string. I've tried every method from doing those above, to having it decode the hex and print the string in a file then output it and try having it do it, and none of those won't work.
but the total code is:
data = ['0000'] #dummy hex
def typer(type):
  s = bytearray.fromhex(type).decode()
  for y in type:
   sleep(0.1)
   sys.stdout.write(y)
   sys.stdout.flush()

typer(data[0])


text:
Q: Filtering static/stationary areas I was trying to filter my sensor data. My objective is to filter the sensor data where the data is more or less stationary over a period of time. can anyone help me in this
time : 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

sensor : 121
115
122
123
116
117
113
116
113
114
115
112
116
129
123
125
130
120
121
122

this is a sample data, i need to take the first data and compare it to the next 20 seconds of data, if all the 20 datas is in the the range of +or- 10 then i need to filter these 20 datas to another column, and i need to continue this process of filtering

A: There is no sample data.  Generated.   Clearly filter on time could be two date times,  I've just picked certain hours.  For stable, example selected values that are between 45th & 55th percentile.
import numpy as np
t = pd.date_range(dt.date(2021,1,10), dt.date(2021,1,11), freq="min")
df = pd.DataFrame({"time":t, "val":np.random.dirichlet(np.ones(len(t)),size=1)[0]})
# filter on hour and val.  val between 45th and 55th percentile
df2 = df[df.time.dt.hour.between(3,4) & df.val.between(df.val.quantile(.45), df.val.quantile(.55))]

output
               time      val
2021-01-10 03:13:00 0.000499
2021-01-10 03:41:00 0.000512
2021-01-10 04:00:00 0.000541
2021-01-10 04:39:00 0.000413

rolling window
Question was updated to state stable is defined as next window rows with a +/- rng output in a new column.
Using this definition, using rolling() capability with a lambda function to check that all subsequent rows within window are within tolerance levels of the first observation in the window.  Any observation out of this range will return NaN. Also note last rows will return NaN as there are insufficient remaining rows to do test.
import pandas as pd
import io
import datetime as dt
import numpy as np
from distutils.version import StrictVersion
df = pd.read_csv(io.StringIO("""sensor
121
115
122
123
116
117
113
116
113
114
115
112
116
129
123
125
130
120
121
122"""))
df["time"] = pd.date_range(dt.date(2021,1,10), freq="s", periods=len(df))

# how many rows to compare
window = 5
# */- range
rng = 10
if StrictVersion(pd.__version__) < StrictVersion("1.0.0"):
    df["stable"] = df["sensor"].rolling(window).apply(lambda x: np.where(pd.Series(x).between(x[0]-rng,x[0]+rng).all(), x[0], np.nan)).shift(-(window-1))
else:
    df["stable"] = df.rolling(window).apply(lambda x: np.where(x.between(x.values[0]-rng,x.values[0]+rng).all(), x.values[0], np.nan)).shift(-(window-1))

output
 sensor                time  stable
    121 2021-01-10 00:00:00   121.0
    115 2021-01-10 00:00:01   115.0
    122 2021-01-10 00:00:02   122.0
    123 2021-01-10 00:00:03   123.0
    116 2021-01-10 00:00:04   116.0
    117 2021-01-10 00:00:05   117.0
    113 2021-01-10 00:00:06   113.0
    116 2021-01-10 00:00:07   116.0
    113 2021-01-10 00:00:08   113.0
    114 2021-01-10 00:00:09     NaN
    115 2021-01-10 00:00:10     NaN
    112 2021-01-10 00:00:11     NaN
    116 2021-01-10 00:00:12     NaN
    129 2021-01-10 00:00:13   129.0
    123 2021-01-10 00:00:14   123.0
    125 2021-01-10 00:00:15   125.0
    130 2021-01-10 00:00:16     NaN
    120 2021-01-10 00:00:17     NaN
    121 2021-01-10 00:00:18     NaN
    122 2021-01-10 00:00:19     NaN

A: However your question is not very clear but from my understanding what you want is between time duration of 20 seconds if the sensor is in between the range of +10 and -10 from the first reading then you have to append those values to new column and above or below that should not be considered. I tried replicating your DataFrame and you could go ahead in this way:
import pandas as pd
data = {'time':[1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],
        'sensor':[121, 115, 122, 123,116,117,113,116,113,114,115,112,116,129,123,125,130,120,121,122,123,124,144]}

df_new = pd.DataFrame(data) #I am taking time duration of 23 seconds where 23rd second data is out of range as 144 - 121 > 10

    time  sensor
0      1     121
1      2     115
2      3     122
3      4     123
4      5     116
5      6     117
6      7     113
7      8     116
8      9     113
9     10     114
10    11     115
11    12     112
12    13     116
13    14     129
14    15     123
15    16     125
16    17     130
17    18     120
18    19     121
19    20     122
20    21     123
21    22     124
22    23     144

list = []
for i in range(0, len(df_new['sensor'])):
    if 0 <= df_new['time'][i] - df_new['time'][0] <= 23: #you take here 20 which is your requirement instead of 23 as I am doing to demonstrate for the value of 144
        if -10 < df_new['sensor'][0] - df_new['sensor'][i] < 10:
            list.append(df_new['sensor'][i])
        else:
            list.append('out of range')
    else:
        break

df_new['result'] = list

df_new

    time  sensor          result
0      1     121           121
1      2     115           115
2      3     122           122
3      4     123           123
4      5     116           116
5      6     117           117
6      7     113           113
7      8     116           116
8      9     113           113
9     10     114           114
10    11     115           115
11    12     112           112
12    13     116           116
13    14     129           129
14    15     123           123
15    16     125           125
16    17     130           130
17    18     120           120
18    19     121           121
19    20     122           122
20    21     123           123
21    22     124           124
22    23     144  out of range


text:
Q: pandas groupby, then aggregate by a 2nd column and find corresponding value in a 3rd column I have a table with 3 main columns. I would like to first group the data by Company ID, then get the Highest Post Valuation per Company ID, and its corresponding Deal Date.
Question: How do I add corresponding Deal Date in?
The data:

Company ID
Post Valuation
Deal Date

60
119616-85
NaN
2022-03-01

80
160988-50
6.77
2022-02-10

85
108827-47
NaN
2022-02-01

89
154876-33
1.40
2022-01-27

104
435509-92
6.16
2022-01-05

107
186777-73
17.26
2022-01-03

111
232001-47
NaN
2022-01-01

113
160988-50
NaN
2021-12-31

119
114196-78
NaN
2021-12-15

128
481375-00
2.82
2021-12-01

130
128348-20
NaN
2021-11-25

131
166855-60
658.36
2021-11-25

150
113503-87
NaN
2021-10-20

156
178448-68
21.75
2021-10-07

170
479007-64
NaN
2021-09-13

182
128479-51
NaN
2021-09-01

185
113503-87
NaN
2021-08-31

186
128348-20
NaN
2021-08-30

191
108643-42
8.02
2021-08-13

192
186272-74
NaN
2021-08-12

The attempt
df_X.sort_values('Post Valuation', ascending=True).groupby('Company ID', as_index=False)['Post Valuation'].first()

A: Sort and drop duplicates:
result = df.sort_values('Post Valuation').drop_duplicates(subset='Company ID', keep='last')


text:
Q: Transforming of a nilpotent matrix to a specific form I wish to build a question in the field of discrete state spaces representation (control theory). The canonical form has a very unique, but not singular, representation. I am focusing on the $A$ matrix of the representation of the form:
$$\begin{bmatrix}
-a_1   & -a_2   & \cdots & -a_{N-1}& -a_N\\
1      & 0      & \cdots & 0       & 0   \\
0      & 1      & \cdots & \cdots  & 0   \\
\vdots & \vdots & \vdots & \ddots  & \vdots   \\
0      & 0      & \cdots & 1       &0   \\
\end{bmatrix}$$
That is a subdiagonal matrix + a matrix of the same size where only the first row has specific values.
Other representations can be generated using a transformation matrix $T$ by $T^{-1}AT$. In my case, $A\in3\times3$.
I want to use a representation with a nilpotentic matrix $B$. Given, $A$ and $B$ which answer these definitions, is there a way to calculate $T$ which transition between them so that  $B=T^{-1}AT$? I do not mind the values of $a_1,\ldots,a_N$ being dictated by $B$. All I care about is the form of the resulting $A$.
For example:
$$B=\begin{bmatrix}
2 & 2 & -2\\
5 & 1 & -3\\
1 & 5 & -3\\
\end{bmatrix},
A=\begin{bmatrix}
-a_1 & -a_2 & -a_3\\
1 & 0 & 0\\
0 & 1 & 0\\
\end{bmatrix}$$
Is it even possible to transform between the two or am I missing a limitation here? If it is possible, is there a close solution for $T$?

A: It is impossible for any regular matrix $A$. Proof:
Let's suppose that there is a regular matrix $T$ for such $B = T^{-1}AT$ is nilpotent. Therefore there exists $n$ for such $B^n=0$.
$$
0 = B^n=(T^{-1}AT)^n=T^{-1}A^nT\\
T0T^{-1}=A^n\\
0=A^n
$$
However, $A$ is regular, so $A^n\neq0$. This is a contradiction.

A: This is an extended comment rather than a solution.
Your matrix $A$ is in what is called Rational Canonical Form. Note that the characteristic equation of $A$ is $X^n +a_1 X^{n-1} +\dots + a_n$.
If $B$ is nilpotent then the characteristic polynomial of $B$ is $X^n$.
Similar matrices have the same characteristic polynomial, so if you want $A$ to be in this shape, and want it to be similar to a nilpotent matrix $B$ then we must have that all the $a_j=0$.
Now if you start with a nilpotent $B$ then it is indeed similar to a matrix whose only non-zero elements lie on the subdiagonal, and are all either $1$ or $0$. There are algorithmic ways of finding an appropriate $T$: if you search for "finding a Jordan basis" you'll find them.
In the explicit case of the $3\times 3$ $B$ you give, you can do the following to find the columns of $T$: (i) find an eigenvector and call it $u_3$; (ii) find a solution of $Bx=u_3$ and call it $u_2$; (iii) find a solution of $Bx=u_2$ and call it $u_1$. (These steps just require us to solve linear equations.)


text:
Q: jQuery Masonry and UI Sortable There's this website I'm developing which can be found here. It's a photography website and my client asked for me to implement something that would allow her to move the photos around and change the order of which they appear. They come from a MySQL database and are displayed with jQuery Masonry.
I thought instantly of jQuery UI Sortable, and I've been trying to implement it with absolutely no luck at all.
How can I achieve this? Can someone point me in the right direction, please?
Thanks in advance!

A: I am struggling with the same issue, so far my answer has been to change classes with jquery's sortable start, stop, change and sort events. Like so:
$('#sortable').sortable({
        start:  function(event, ui) {
                 console.log(ui);
            ui.item.removeClass('masonry');
            ui.item.parent().masonry('reloadItems')
                },
        change: function(event, ui) {
            ui.item.parent().masonry('reloadItems');
                },
        stop:   function(event, ui) {
            ui.item.addClass('masonry');
            ui.item.parent().masonry('reloadItems');
});

Here is a working example  and a JS Fiddle on the subject. It's a start.
However, this is not a 'presto' solution, this examples work with older versions of masonry, the latest version has a few bugs implementing it since the "reload" method was replaced with layout() and reloadItems().
Or... you can use the old masonry versions, if it works for you.
Alternatively you can use jQuery.Shapeshift(), which does basically what you're looking for.


text:
Q: opencart - Authorize.net confirm button "please wait" no redirection We are using opencart-1.5.6 and installed authorize.net(AIM) and PayPal as the payment gateway.But while we checkout using authorize.net, the card is processed and cash is deducted from credit card successfully, but the page is not redirecting to the confirmation page.Mail is sent successfully to admin and also purchase status is also set as completed.But the page still stuck in showing a please wait message.
System is working in the sandbox mode and issue happens when its live.
I would greatly appreciate if you can help.

A: As SankarV is recommending, exploring the response for the confirm AJAX request is the best bet - there might be no direct error in console, but since AJAX response contains invalid JSON due to possible PHP errors being printed out, the redirect to a success page could not be performed. So again, explore the AJAX response for the confirm request and come back with anything suspicious within it.
And though some entry_company might not take place in the checkout, since it is echoed somewhere while not instantiated, the PHP Notice is raised thus making the JSON response invalid...


text:
Q: Spring MVC 3.0 Annotated controller not working with JQuery $.post() In the Spring MVC controller i am trying to access the name sent by the JQuery simple post.
I am getting error Could not find @PathVariable [name] in @RequestMapping*
Where i am going wrong?
JQuery Post
$.post("addName.htm",{ name: "John"});

Spring Controller
@RequestMapping(value = "/addName.htm", method = RequestMethod.POST)
public void setAllocations(@PathVariable String name) {

    System.out.println("inside Setting value.... ");
    System.out.println(name);
}

I am getting error
Could not find @PathVariable [name] in @RequestMapping

A: That is not a @PathVariable, you have to use a @RequestParam instead.  Try this:
@RequestMapping(value = "/addName.htm", method = RequestMethod.POST)
public void setAllocations(@RequestParam String name) {
    System.out.println(name);
}

This is the difference:

*

*PathVariable: http://yourhost/{name}/addName.html

*RequestParam: http://yourhost/addName.html?name={name}

A: You should use @RequestParam instead of @PathVariable
@RequestMapping(value = "/addName.htm", method = RequestMethod.POST)
public void setAllocations(@RequestParam String name) {
  System.out.println("inside Setting value.... ");
  System.out.println(name);
}

From the docs:

*

*@PathVariable annotated parameters for access to URI template variables.

*@RequestParam annotated parameters for access to specific Servlet request parameters.


text:
Q: Rename Form on Load MSVisual c++ Somebody have an idea how to rename form onLoad?
I tried:
private: System::Void General_Load(System::Object^  sender, System::EventArgs^  e) {
         String^ test = "test";
         String^ x= "General: " + test;
         this->Name = x;
         }

but it doesn't work.

A: I should use this->Text = x; not this->Name = x;


text:
Q: Prevent IIS app restart when saving an encrypted configuration section? I'm helping build an ASP.NET C# application with multiple custom configuration files.  We store these outside the web.config file using <configSections><section /></configSections> elements making sure to set restartOnExternalChanges="false" so file saves don't restart the application.
To manage these settings we've built ASPX pages to read, update and save the various sections and values. For plain text sections this works pretty well.  Admins log into the configuration section of the app, make changes, save and they take effect immediately.
But we have one section, in its own external file like all the others, that is also encrypted.  Whenever that section is saved, the IIS application restarts loosing the session.  That means the logged in admin making the configuration changes, and all end users logged into the user side of the app, have to login again which is frustrating.
Is there any way to avoid IIS application restart when an encrypted configuration section is saved?
Our current encrypted config section handling code looks like this:
public class CredentialsConfig : ConfigurationSection
{
    Configuration Config = null;
    CredentialsConfig Section = null;

    public static CredentialsConfig GetConfig()
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
        CredentialsConfig section = config.GetSection("credentials") as CredentialsConfig;

        // Ensure the current file is encrypted
        if (!section.SectionInformation.IsProtected)
        {
            section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            section.SectionInformation.ForceSave = true;
            config.Save();
        }

        return section;
    }

    public CredentialsConfig GetConfigForUpdate()
    {
        Config = WebConfigurationManager.OpenWebConfiguration("~");
        Section = Config.GetSection("credentials") as CredentialsConfig;
        return Section;
    }

    public void SaveConfig()
    {
        Section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
        Section.SectionInformation.ForceSave = true;
        Config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("credentials");
    }

    [ConfigurationProperty("administrator")]
    public AdministratorConfigurationElement Administrator
    {
        get
        {
            return this["administrator"] as AdministratorConfigurationElement;
        }
    }
}

And we're using it like:
CredentialsConfig credentialsConfig = new CredentialsConfig();
AdministratorConfigurationElement newConfig = credentialsConfig.GetConfigForUpdate().Administrator;
// setting attributes in the section's <administrator /> element
credentialsConfig.SaveConfig();
// frustrating app restart happens

A: No.  Modifications to the .config file are one of the automatic triggers that will always restart the application.
Personally, I'd recommend moving commonly modified items out of .config files and into a database, or the registry, or someplace else where it can be encrypted and protected, and where this isn't an issue.


text:
Q: How can I output the longest login time in minutes (not hh:mm)? I cannot cut out from the 10th argument which looks like this: (01:53) the hours and minutes.
My code looks like this:
#!/bin/bash

if [ ! $# -eq 1 ] #we need only one username
then echo usage: $0 Error!
     exit 1
fi

if [ $(finger $1 2>&1 >/dev/null | grep -c "no such user") -gt 0 ]
then    echo #this is a nonexistent username
        echo No such username
else    #existent username
        us=$1;
        last $1 | awk 'BEGIN {time=$10 }
                         ($10 > x) && ($10 != "in") {
                                time = $10
                         }
                        END{
                        print "Longest login time:" time  }'
fi

Output:
(01:53)

I need:
113

A: time="01:53"
IFS=: read hours minutes <<<"$time"
time_in_mins=$(( 60 * 10#$hours + 10#$minutes ))
echo "$time_in_mins"

I'm explicitly using base 10 for the variables, so that 08 and 09 are not interpreted as invalid octal numbers

grep -q is a good option for if conditions: instead of
if [ $(finger $1 2>&1 >/dev/null | grep -c "no such user") -gt 0 ]

use this
if finger $1 2>&1 >/dev/null | grep -q "no such user"

Taking a closer look at what you're doing, I'd do the calculations in the awk command: Note that the time output from last can include days.
  last "$1" | awk -F '[()]' '
      function to_minutes(time,    d, a, n) {
          n = split(time, a, /\+/)
          if (n == 2) {
              d = a[1]
              time = a[2]
          }
          n = split(time, a, /:/)
          return (1440*d + 60*a[1] + a[2])
      }
      {
          time = to_minutes($2 ? $2 : 0)
          max = time > max ? time : max
      }
      END {print max}
  '


text:
Q: Python Error converting value "AddmissionGuid" to System.GUID I am receiving data from a request as follows
[
  {
    "Info": {
      "SoftwareVersion": "111",
      "IpAddress": "111.111.11",
      "DeviceName": "1111222",
      "Type": "Tablet"
    },
    "DeviceIdentity": "Identity",
    "AdmissionGuid": "db128362-f942-47fb-b18e-c073aa03b95d",
    "UserId": "8c7be5ac-9f2e-42aa-8f17-4e935a85eff3",
    "ConnectionId": "f78f544e-0780-4b07-87ec-d4edbe4cb522",
    "PairingId": null
  }
]

Then I am trying to parse it in python everything works i get the value as expected but i get the following error, I have tried to convert it to Object, String, Hex but nothing works

Error converting value "AdmissionGuid" to System.GUID

Python script
from requests import Session
from signalr import Connection
import threading, time, json, logging
import urllib.request
import requests
import uuid

GetPatientID = requests.get('http://example-url.com/api/json')

 data = GetAdmissionID.json()
print (type(data))

AdmissionGuid= uuid.UUID(data[0]["AdmissionGuid"])
print (type(AdmissionGuid))

UserID = "8c7be5ac-9f2e-42aa-8f17-4e935a85eff3"
softwareVersion = "111"
IpAddress = "111.111.11"
machineName = "1111222"
DeviceType = "Tablet"
pairingId = "null"
def __init__(self, cli):
    self.cli = cli
    logging.info("registered the cli (main thread)")

with Session() as session:
    connection = Connection("http://example-url.com/signalr", session)
    print(connection)
    logging.info("got the connection")
    presenceservice = connection.register_hub('ClientRegistration')
    logging.info("got the hub")

    connection.start()
    def get_data(notificaition):
        print("Recived something?: ", notificaition)
    def print_error(error):
        print('error: ', error)
    connection.error += print_error
    presenceservice.server.invoke('IdentifyClient', 'devideIdentity', 'softwareVersion', 'ipAddress',
                                          'machineName', 'deviceType', 'patientAdmissionGuid', 'patientId', 'pairingId')
    key = input("Press E\n")
    if key == 'e':
        connection.wait(1)

        presenceservice.client.on('Notification', get_data)

        print ('Nothing Happned')

    connection.wait(30)

And the log
<class 'list'>
<class 'uuid.UUID'>
Press E
e
error:  Error converting value "AdmissionGuid" to type 'System.Guid'.

Note: I am also using Singal R libary to invoke a C# Hub to register a client.
AdmissionGuid is Generated in C# using the GUID library,
Is there a way to get in python ?
I have looked at this already 1, 2, But this does not solve my problem
EDIT
C# Function i am Calling with singal R
IdentifyClient(string devideIdentity, string softwareVersion, string ipAddress, string machineName, string deviceType, Guid AdmissionGuid, Guid UserID, string pairingId)

A: I have fixed my issue, I was Invoking the IdentifyClient() function with String rather than variables it was a simple fix.
Changed this
presenceservice.server.invoke('IdentifyClient', 'devideIdentity', 'softwareVersion', 'ipAddress',
                                          'machineName', 'deviceType', 'patientAdmissionGuid', 'patientId', 'pairingId')

To this
presenceservice.server.invoke('IdentifyClient', devideIdentity, softwareVersion, ipAddress,
                                          machineName, deviceType, patientAdmissionGuid, patientId, pairingId)


text:
Q: MySQL reorder Number values I have a table with values
ID(PK) MAIN_ID  SUB_ID
1         2        2
2         2        3
5         1        1
3         1        3
9         1        4
8         1        5
4         4        2
7         4        3
11        4        4
10        4        6
6         4        7
12        4        8

I want to reorder them in such a way that MAIN_ID's will contain 1 , 2 , 3 , 4 and SUB_IDs will container 1 , 2 , 3 , 4 , 5 etc. Basically i want to remove the missing numbers and make the MAIN_ID and SUB_ID follow numerical order without missing numbers
Desired result as requested
ID(PK)  MAIN_ID           SUB_ID
1         2                1(Prev 2)
2         2                2(Prev 3)
5         1                1
3         1                2(Prev 3)
9         1                3(Prev 4)
8         1                4(Prev 5)
4         3(Prev 4)        1(Prev 2)
7         3(Prev 4)        2(Prev 3)
11        3(Prev 4)        3(Prev 4)
10        3(Prev 4)        4(Prev 6)
6         3(Prev 4)        5(Prev 7)
12        3(Prev 4)        6(Prev 8)
```

A: Do you need this:
UPDATE test
JOIN ( SELECT ID,
              DENSE_RANK() OVER (ORDER BY MAIN_ID) dr,
              ROW_NUMBER() OVER (PARTITION BY MAIN_ID ORDER BY SUB_ID, ID) rn
       FROM test ) t USING (ID)
SET test.MAIN_ID = dr, test.SUB_ID = rn;

?
fiddle