text:
Q: React Native Bugsnag error: TypeError Properties can only be defined on Objects [native code] defineProperty We have an react-native app with 25k+ users and have gotten over 1000 crashes over the last 3 months reported in bugsnag. The crash typically happens within 1 sec of startup, but sometimes it takes a few seconds. We have not been able to reproduce this in development. It is happening on both ios and android. The only thing we have to go off of is the stacktrace provided by bugsnag:
iOS bugsnag stack trace:
TypeError Properties can only be defined on Objects.
    [native code] defineProperty
    node_modules/react-redux/lib/connect/mergeProps.js:54:21
    node_modules/react-native/node_modules/@babel/runtime/helpers/typeof.js:17:17 _get
    node_modules/react-redux/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js:100:11
    node_modules/react-native/node_modules/@babel/runtime/helpers/typeof.js:17:17 _get
    node_modules/react-native/node_modules/@babel/runtime/helpers/toConsumableArray.js:8:59 res
    node_modules/react-native/node_modules/@babel/runtime/helpers/toConsumableArray.js:8:59
    node_modules/react-native/node_modules/@babel/runtime/helpers/toConsumableArray.js:8:59 _toConsumableArray
    node_modules/react-native/node_modules/@babel/runtime/helpers/toConsumableArray.js:8:59 _defineProperties
    [native code] value

Android bugsnag stack trace:
TypeError Properties can only be defined on Objects.
    [native code] defineProperty
    node_modules/react-redux/lib/utils/isPlainObject.js:20:19
    node_modules/react-native/node_modules/@babel/runtime/helpers/typeof.js:17:17 _get
    node_modules/react-redux/lib/components/connectAdvanced.js:130:29
    node_modules/react-native/node_modules/@babel/runtime/helpers/typeof.js:17:17 _get
    node_modules/react-native/node_modules/@babel/runtime/helpers/toConsumableArray.js:8:59 _typeof2
    node_modules/react-native/node_modules/@babel/runtime/helpers/toConsumableArray.js:8:59
    node_modules/react-native/node_modules/@babel/runtime/helpers/toConsumableArray.js:8:59 RCTDeviceEventEmitter
    node_modules/react-native/node_modules/@babel/runtime/helpers/toConsumableArray.js:8:59 _defineProperties
    [native code] value

The stack traces leads me to believe it has something to do with react-redux.
However I don't believe this issue happened before upgrading to RN v 0.62 which leads me to believe it might have something to do with RN 0.62
here are the dependencies in the package.json:
"dependencies": {
    "@emotion/core": "^10.0.16",
    "@fragaria/address-formatter": "^2.0.5",
    "@react-native-community/art": "^1.0.3",
    "@react-native-community/async-storage": "^1.8.0",
    "@react-native-community/cameraroll": "^1.3.0",
    "@react-native-community/clipboard": "^1.2.2",
    "@react-native-community/datetimepicker": "^2.1.0",
    "@react-native-community/masked-view": "^0.1.6",
    "@react-native-community/netinfo": "^5.9.0",
    "@react-native-firebase/app": "^6.4.0",
    "@react-native-firebase/crashlytics": "^6.4.0",
    "@react-native-firebase/messaging": "^6.4.0",
    "@react-navigation/bottom-tabs": "^5.1.1",
    "@react-navigation/drawer": "^5.0.6",
    "@react-navigation/native": "^5.0.9",
    "@react-navigation/stack": "^5.1.1",
    "apisauce": "^0.14.3",
    "bugsnag-react-native": "^2.20.0",
    "bugsnag-sourcemaps": "^1.0.4",
    "emotion-theming": "^10.0.14",
    "lodash": "^4.17.10",
    "moment": "^2.22.2",
    "moment-round": "^1.0.1",
    "prop-types": "15.6.0",
    "react": "16.11.0",
    "react-native": "0.62.2",
    "react-native-app-auth": "^5.0.0",
    "react-native-audio-recorder-player": "^2.4.3",
    "react-native-call-detection": "^1.9.0",
    "react-native-camera": "git+https://git@github.com/react-native-community/react-native-camera.git",
    "react-native-config": "^0.12.0",
    "react-native-device-info": "^5.0.0",
    "react-native-fast-image": "^7.0.2",
    "react-native-geolocation-service": "^4.0.0",
    "react-native-gesture-handler": "^1.6.0",
    "react-native-google-places-autocomplete": "^1.4.1",
    "react-native-intercom": "^13.1.0",
    "react-native-keyboard-aware-scroll-view": "^0.9.1",
    "react-native-maps": "0.26.1",
    "react-native-modal": "^11.4.0",
    "react-native-notifications": "^3.1.2",
    "react-native-open-maps": "^0.3.4",
    "react-native-permissions": "~1.1.1",
    "react-native-pie": "^0.6.1",
    "react-native-progress": "^4.1.2",
    "react-native-rate": "1.1.10",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.3",
    "react-native-screens": "^2.0.0-beta.10",
    "react-native-snap-carousel": "^3.8.4",
    "react-native-sound-player": "^0.10.3",
    "react-native-splash-screen": "^3.2.0",
    "react-native-svg": "^12.0.3",
    "react-native-swipe-list-view": "^2.0.3",
    "react-native-vector-icons": "6.6.0",
    "react-native-video": "^4.4.5",
    "react-native-video-controls": "^2.6.0",
    "react-native-webview": "^8.1.1",
    "react-redux": "^7.1.0",
    "redux": "^4.0.5",
    "redux-logger": "^3.0.6",
    "redux-mock-store": "^1.5.4",
    "redux-persist": "^6.0.0",
    "redux-saga": "^1.1.3",
    "reselect": "^4.0.0",
    "rn-fetch-blob": "^0.12.0"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/plugin-proposal-class-properties": "^7.4.0",
    "@babel/preset-env": "^7.4.3",
    "@babel/runtime": "^7.9.6",
    "@storybook/addon-actions": "5.1.11",
    "@storybook/addon-knobs": "5.1.11",
    "@storybook/addon-links": "5.1.11",
    "@storybook/addon-notes": "5.1.11",
    "@storybook/addon-ondevice-actions": "5.1.11",
    "@storybook/addon-ondevice-knobs": "5.1.11",
    "@storybook/addon-ondevice-notes": "5.1.11",
    "@storybook/addon-storyshots": "5.1.11",
    "@storybook/addons": "5.1.11",
    "@storybook/react-native": "5.1.11",
    "babel-eslint": "^10.0.2",
    "babel-jest": "^24.9.0",
    "babel-loader": "^7.1.5",
    "babel-plugin-module-resolver": "^3.2.0",
    "babel-polyfill": "7.0.0-beta.3",
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^13.0.0",
    "eslint-import-resolver-babel-module": "^5.1.0",
    "eslint-plugin-import": "2.2.0",
    "eslint-plugin-jsx-a11y": "2.2.3",
    "eslint-plugin-react": "7.12.4",
    "jest": "24.9.0",
    "jest-plugin-context": "^2.9.0",
    "jetifier": "^1.6.4",
    "metro-react-native-babel-preset": "^0.58.0",
    "react-addons-test-utils": "~15.4.1",
    "react-dom": "16.8.3",
    "react-native-testing-library": "^2.1.0",
    "react-test-renderer": "^16.13.1",
    "wd": "^1.11.4"
  }

Any clues as to what the issue may be?

A: I met the same error "TypeError Properties can only be defined on Objects [native code] defineProperty". I solved it by replacing some code using @react-native-firebase/messaging.
you can try replacing the code
`
useEffect(() => {
    messaging().getToken().then(token => {
      //some logic code
    });
    return messaging().onTokenRefresh(token => {
      //some logic code
    });
}, []);
`

with
`
useEffect(() => {
    messaging().getToken().then(token => {
      //some logic code
    });
    messaging().onTokenRefresh(token => {
      //some logic code
    });
}, []);
`


text:
Q: Converting an array with values in log scale to a regular array I am trying to plot a histogram of elements of a downloaded .py file. The array had a shape (200, 3649, 13). So I had reshaped it to a 2D array by preforming the function
samples = chain[:,-2000:,:].reshape((-1,13))

I hence plotted the histogram by doing
plt.hist(samples[:,3])

The graph gave me values in log scale, but I need to plot it in a linear scale. How do I proceed?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mysql Query Grouping Issue I have the following mysql query
    SELECT  t2.country,t1.deposits

    FROM(
    SELECT Online_customer_activity_v2.Customers AS Player,
    sum(Real_Money) as Deposits
    FROM Online_customer_activity_v2
    group by Customers
    ) t1

    INNER JOIN

    (
        SELECT username as Player,
        `players`.`country` as country
        FROM `players`
    ) t2
    ON t1.`Player` = t2.`Player`

    ORDER BY t1.Deposits DESC

the result is:
+-------------------------+----------+
| country                 | deposits |
+-------------------------+----------+
| Saudi Arabia            | 773410   |
| Saudi Arabia            | 269845   |
| Kuwait                  | 132065   |
| Kuwait                  | 130245   |
| Saudi Arabia            | 114006   |
| Kuwait                  | 110920   |
| Kuwait                  | 98755    |
| Kuwait                  | 86180    |
| Kuwait                  | 86005    |
| Kuwait                  | 84545    |
| Saudi Arabia            | 71485    |
| Kuwait                  | 69247    |
| Saudi Arabia            | 65300    |
| Kuwait                  | 65000    |
| United Arab Emirates    | 63795    |
| Kuwait                  | 59935    |

Now when I try to Group by t2.country to get my query summarized by country,
SELECT  t2.country,t1.deposits
    FROM(
    SELECT Online_customer_activity_v2.Customers AS Player,
    sum(Real_Money) as Deposits
    FROM Online_customer_activity_v2
    group by Customers
    ) t1
    INNER JOIN
    (
        SELECT username as Player,
        `players`.`country` as country
        FROM `players`
    ) t2
    ON t1.`Player` = t2.`Player`
    GROUP BY t2.country
    ORDER BY t1.Deposits DESC

I get the following:
+-------------------------+----------+
| country                 | deposits |
+-------------------------+----------+
| Saudi Arabia            | 65300    |
| Bahrain                 | 6850     |
| Egypt                   | 700      |

It basically does no sum up by customer correctly...
What am I doing wrong and how should I correct this query to have it working?
Thanks!

A: If you want to get the sum(t1.deposits) based on t2.country use sum aggregate function like;
SELECT  t2.country, sum(t1.deposits) deposits
FROM(
    SELECT Customers AS Player,
    sum(Real_Money) as Deposits
    FROM Online_customer_activity_v2
    group by Customers
) t1
JOIN `players` t2
ON t1.`Player` = t2.`username`
GROUP BY t2.country
ORDER BY Sum(t1.Deposits) DESC


text:
Q: Multiple inheritance with Qt classes I have a class A that inherits QGraphicsItem, and another class B that inherits QgraphicsLineItem. How can B inherit class A
class A : public QObject, public QGraphicsItem {
}
class B : public QObject, public QGraphicsLineItem {
}
How can A be inherited by B?
My problem is as Under:
Class with virtual clone method()
#include <QGraphicsItem>

class getEntity : public QObject, public QGraphicsItem
{
public:
   getEntity(QObject *parent = 0) : QObject(parent) {}
   virtual ~getEntity() {}

   virtual getEntity *clone() { return 0; }
};

stack.h
#include <QStack>

#include "getEntity.h"

class clipboardStack
{
public:
    static clipboardStack *instance()
    {
        if (!inst)
            inst = new clipboardStack;
        return inst;
    }

    void push(getEntity *entity)
    {
        clips.push(entity);
    }

    getEntity *pasteEntity()
    {
        if (clips.count() == 0)
            return 0;
        return clips.last();
    }

    getEntity *pop()
    {
        if (clips.count() == 0)
            return 0;
        return clips.pop();
    }

    bool isEmpty() const
    {
        return clips.empty();
    }

private:
    QStack<getEntity *> clips;
    static clipboardStack *inst;
};

circle.h
#include <QPainter>
#include <QGraphicsItem>

#include "qmath.h"
#include "operations/getEntity.h"
#include "operations/clipboardstack.h"

class Circle : QGraphicsItem , public getEntity
{
    Q_OBJECT
public:
    Circle(QObject *parent = 0) : getEntity(parent) {}
    Circle(int, QPointF, QPointF);
    Circle(int, QPointF, qreal);
    QRectF boundingRect() const;
    virtual void paint(QPainter *painter,
                       const QStyleOptionGraphicsItem *option,
                       QWidget *widget);
    enum { Type = UserType + 3 };
    int type() const;
    int id;

    QPointF centerP, endP;
    qreal radius;

    getEntity *clone();

private:
    QVector<QPointF> stuff;
};

//Problem with Line
line.h
#include <QPainter>
#include <QGraphicsLineItem>

#include "operations/getEntity.h"
class Line : public QObject, public QGraphicsLineItem
{
    Q_OBJECT
public:
    Line(QObject *parent = 0) : getLine(parent) {}
    Line(int, QPointF, QPointF);
    QRectF boundingRect() const;
    virtual void paint(QPainter *painter,
                       const QStyleOptionGraphicsItem *option,
                       QWidget *widget);
    enum { Type = UserType + 2 };
    int type() const;
    int id;

    QPointF startP, endP;

private:
    QVector<QPointF> stuff;
};

cadgraphicsscene.cpp
 void CadGraphicsScene::cutEntity(getEntity *obj)
{
    removeItem(obj);
    clipboardStack::instance()->push(obj);
}

void CadGraphicsScene::copyEntity(getEntity *obj)
{
    clipboardStack::instance()->push(obj->clone());
}

void CadGraphicsScene::pasteEntity(const QPointF &pos)
{
    getEntity *pasteEntity = clipboardStack::instance()->pop();
    if (pasteEntity)
    {
        addItem(dynamic_cast<QGraphicsItem *>(pasteEntity));
        pasteEntity->setPos(pos);
        pasteEntity->setFlag(QGraphicsItem::ItemIsSelectable);
        pasteEntity->setFlag(QGraphicsItem::ItemIsMovable);
        mUndoStack->push(new CadCommandAdd(this, pasteEntity));
    }
}

A: You can use QGraphicsObject instead of QGraphicsItem, which provides the required signals / slots mechanism for you, without the need for multiple inheritance.
You also mention in  your comment:-

[inheriting] Line from QgraphicsLineItem and Text from QgraphicsTextItem

Rather than extending QGraphicsLineItem and QGraphicsTextItem, it would be better if you inherit from QGraphicsItem or QGraphicsObject, as you do for circle, ellipse and point.


text:
Q: IOS9 WKWebView Access-Control-Allow-Origin I load local html file on IOS WKWebview using loadFileURL: allowingReadAccessToURL..
But when I send ajax request, it fails.
The error is:

Origin null is not allowed by Access-Control-Allow-Origin.

Can I set some properties to fix this error, like in Android,we can use setAllowUniversalAccessFromFileURLs?

A: Have you tried setting it like this?
let config = WKWebViewConfiguration()
config.setValue(true, forKey: "allowUniversalAccessFromFileURLs")

A: When HTML is loaded locally (file URL) with WkWebView below configuration setting to WkWebView worked for me
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userContentController = [[WKUserContentController alloc] init];

[theConfiguration.preferences setValue:@"TRUE" forKey:@"allowFileAccessFromFileURLs"];
[theConfiguration setValue:@"TRUE" forKey:@"allowUniversalAccessFromFileURLs"];

When you set above setting, origin will be passed as "file://" instead of null

A: Try using loadRequest instead of loadFileURL. It worked for me :
NSString* path = [[NSBundle mainBundle] pathForResource:@"pageName" ofType:@"html"];
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
[self.webView loadRequest:request];

After that, my query worked fine while I had a 'Cannot make any requests from null' error before.

A: if you want to reading from localhtml file, you have to set allowReadAccess
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentsURL = URL(fileURLWithPath: documentsPath, isDirectory: true)
let finalURL = URL(string: htmlurl)
webview.loadFileURL(finalURL!, allowingReadAccessTo: documentsURL)

A: On Chrome, CORS requests won't work from localhost dispite proper CORS headers, just saying.. keep banging my head on that one


text:
Q: Scheme function to remove atoms? If I have a list like (e q(r))
How would I remove all the atoms and just return (())  ?

A: Hey, a technique known as tree-recursion is useful for this type of problem.
I agree with the general structure of the Greg's answer, but I think we need to explicitly filter atomic (non-list) values from nested lists.
(define (rem-atoms lst)
  (cond
    ((not (list? lst)) lst)
    ((null? lst) (list))
    (else
      (filter
        (lambda (a) (list? a))
        (cons (rem-atoms (car lst))
              (rem-atoms (cdr lst)))))))

(rem-atoms '(f (x y) z () (k ())))  ; --> (() () (()))
(rem-atoms '(f x (y)))              ; --> (())

Upon further inspection, a tiny amendment to Greg's good solution also now provides the correct results. Specifically: (not (list? xx)) rather than (not (pair? xx)).
(define (rem-atoms lat)
  (cond
    ((null? lat) lat)
    ((not (list? (car lat))) (rem-atoms (cdr lat)))
    (else
      (cons (rem-atoms (car lat))
            (rem-atoms (cdr lat)))))))

(rem-atoms '(f (x y) z () (k ())))  ; --> (() () (()))
(rem-atoms '(f x (y)))              ; --> (())

Hmm. I think I like this second version the best!
Note, I'm brand new here, but I hope this helps.

A: (define rem-atoms
 (lambda (lat)
  (cond
    ((null? lat) lat)
    ((not (pair? (car lat))) (rem-atoms (cdr lat)))
    (else
     (cons (rem-atoms (car lat)) (rem-atoms (cdr lat)))))))

If the list is empty, return the empty list. If it's an atom (or rather, not a list), just eliminate it. If it's a list, call the function recursively on both the car and the cdr of the list.


text:
Q: Numpy Array find most frequent items in each row I have a 2d matrix with a very large dimension (~10000 x 10000)
I want to find the frequency of the most common number in each row,
and select the row that has the least frequency.
For example,
if my 2d array is
[1, 2, 3, 3, 5]
[1, 1, 1, 2, 1]
[3, 2, 2, 1, 3]
[4, 5, 1, 2, 2]
[3, 5, 6, 7, 8]

,
The frequency of most common number in each row is [2, 4, 2, 2, 1].
I want to find the index 4 (the last row) because the frequency of most common items is 1, which is the lowest among all rows.
Right now I am just using for loops but is there a vectorized approach that is very fast?
Thank you in advance.

A: For the general case, your best option should be using scipy.stats.mode as already pointed out by a comment.
However, in the case that your array contains only non-negative values, and the values are limited in range (suppose the values are ranging from 0-10, or 0-100, or 0-1000) then it would be much faster to use np.bincount. For example:
import numpy as np
from scipy.stats import mode

def foo(a):
  return np.argmin(mode(a, axis=1)[1])

def bar(a):
  return np.argmin([np.bincount(r).max() for r in a])

# Testing on a 10000x10000 array
a = np.random.randint(0, 1000, (10000, 10000), np.int32)

print(foo(a))
# 491

print(bar(a))
# 491

# Time required:
%timeit -n 5 -r 1 foo(a)
# 6.75 s ± 0 ns per loop (mean ± std. dev. of 1 run, 5 loops each)

%timeit -n 5 -r 1 bar(a)
# 317 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 5 loops each)


text:
Q: VBA: Create a csv from an excel file xlsm/xlsx I'm using a code below to change an xlsm file into a csv . The goal is to concatenate the columns cells in the first column for each row:  So it works in a certain way but for some rows, the final csv doesn't concatenate all the cells  for the same row, I have 2 columns filled instead of only the first. Does anybody have another algo that concatenate each cells for the same row into the first cell and separate them by a ";" even if there is some text with comma into certain cells at first ?
example of a cell:
ID   Provider          Rationale
4    mister provider   the rationale describe an id, and there is some comma in it.

Example of expected output:
id;Provider;Rationale
4;mister provider;therationale describe an id; and there is some comma in it

    Dim Fe As Worksheet
    Dim Plage As Range
    Dim Cel As Range
    Dim Tbl() As String
    Dim Ligne As String
    Dim Dossier As String
    Dim Chemin As String
    Dim Fichier As String
    Dim i As Long
    Dim j As Long

    Dossier = "C:\my_path"

    Fichier = "My_Name " & Format(Now, "dd-mm-yyyy") & ".csv"

    'full path
    Chemin = Dossier & Fichier

    Set Fe = Worksheets("Upload")

    Set Plage = DefPlage(Fe, 1, 1)

    For i = 1 To Plage.Rows.Count

        For j = 1 To Plage.Columns.Count: Ligne = Ligne & Plage(i, j).Value & ",": Next j

        'delete the ; at the end
        Ligne = Left(Ligne, Len(Ligne) - 1)

        'store in a table
        ReDim Preserve Tbl(1 To i)
        Tbl(i) = Ligne

        'For the next on
        Ligne = ""

    Next i

    'create .csv file
    Open Chemin For Output As #1

        For i = 1 To UBound(Tbl): Print #1, Tbl(i): Next i

    Close #1

Function DefPlage(Fe As Worksheet, L As Long, C As Long) As Range

    On Error GoTo Fin

    With Fe

        Set DefPlage = .Range(.Cells(L, C), _
                       .Cells(.Cells.Find("*", .[A1], -4123, , _
                       1, 2).Row, .Cells.Find("*", .[A1], -4123, , _
                       2, 2).Column))

    End With

    Exit Function

Fin:

    Set DefPlage = Nothing

End Function

A: The problem is that the text has a separator, in this case is the ",". You must put some escape char to not count as a separator. If the csv will be open with excel, put all text between quotation marks (").
Example, change the line that concatenates the string:
For j = 1 To Plage.Columns.Count: Ligne = Ligne & """" & Plage(i, j).Value & """;": Next j


text:
Q: Can glob be used with boolean searches? I am hoping someone can help me. I am trying to use glob to find a filename. I want to find a file name that contains a 2 OR a 4 as the fifth character in the file name. For example, I want to write a glob that would find these file names:
00002.txt
00004.txt
12002.txt

I understand that I could use glob to find these files using a series such as:
ls ????[2-4]*

However, the above glob would also match files that had a 3 as the fifth character. Does anyone know how to glob for only files that contain a 2 OR 4 as the fifth character? Thanks very much for your time!

A: Using [24] will allow just 2 or 4, instead of the range [2-4], giving you:
ls ????[24]*


text:
Q: Devise create user and login on test setup app/controllers/categories_controller.rb:
class CategoriesController < ApplicationController
    before_action :set_category, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!, except: [:index, :show]

    # GET /categories
    # GET /categories.json
    def index
        @categories = Category.all
    end

    # GET /categories/1
    # GET /categories/1.json
    def show
        if session[:cart] then
            @cart = session[:cart]
        else
            @cart = {}
        end
    end

    # GET /categories/new
    def new
        if current_user.admin?
            @category = Category.new
        end
    end

    # GET /categories/1/edit
    def edit
        if current_user.admin?
        end
    end

    # POST /categories
    # POST /categories.json
    def create
        if current_user.admin?
            @category = Category.new(category_params)

            respond_to do |format|
                if @category.save
                    format.html { redirect_to @category, notice: 'Category was successfully created.' }
                    format.json { render :show, status: :created, location: @category }
                else
                    format.html { render :new }
                    format.json { render json: @category.errors, status: :unprocessable_entity }
                end
            end
        end
    end

    # PATCH/PUT /categories/1
    # PATCH/PUT /categories/1.json
    def update
        if current_user.admin?
            respond_to do |format|
                if @category.update(category_params)
                    format.html { redirect_to @category, notice: 'Category was successfully updated.' }
                    format.json { render :show, status: :ok, location: @category }
                else
                    format.html { render :edit }
                    format.json { render json: @category.errors, status: :unprocessable_entity }
                end
            end
        end
    end

    # DELETE /categories/1
    # DELETE /categories/1.json
    def destroy
        if current_user.admin?
            @category.destroy
            respond_to do |format|
                format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
                format.json { head :no_content }
            end
        end
    end

    private
        # Use callbacks to share common setup or constraints between actions.
        def set_category
            @category = Category.find(params[:id])
        end

        # Never trust parameters from the scary internet, only allow the white list through.
        def category_params
            params.require(:category).permit(:name, :desc)
        end
end

In the controller above I'm preventing standard users to create, update or destroy categories by checking if current_user.admin?. But it's causing some problems in the tests.
test/controllers/categories_controller.rb:
require 'test_helper'

class CategoriesControllerTest < ActionController::TestCase
  setup do
    @category = categories(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:categories)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create category" do
    assert_difference('Category.count') do
      post :create, category: { desc: @category.desc, name: @category.name }
    end

    assert_redirected_to category_path(assigns(:category))
  end

  test "should show category" do
    get :show, id: @category
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @category
    assert_response :success
  end

  test "should update category" do
    patch :update, id: @category, category: { desc: @category.desc, name: @category.name }
    assert_redirected_to category_path(assigns(:category))
  end

  test "should destroy category" do
    assert_difference('Category.count', -1) do
      delete :destroy, id: @category
    end

    assert_redirected_to categories_path
  end
end

Because of the restriction, tests related with create, update or destroy are failing. I think I need to create an admin user and login on test setup. But I don't know how to do this.
I'm using Devise gem for users part of the app.
I'm running my tests with rake test:functionals. How can I simulate user create and login in my tests?
If you want to look to the whole project: https://github.com/mertyildiran/SCOR

A: You can use fixtures to create an admin user in the test database (you probably already have a test/fixtures/users.yml file), and Devise's Test helpers to sign in:
sign_in :user, users(:admin)

If your users are confirmable, remember to set a confirmed_at date.
Check out the Devise wiki article on testing Rails controllers.


text:
Q: How to change byte[] to hex?
Possible Duplicates:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?
C# byte[] to hex string

I need to take this:
byte[] data = new byte[] { 1, 2, 3, 4 }

And turn it into something like this:
0x01020304

What is the best way to do this in C#?

A: For a single value:
String.Format("{0:X2}", value);
Depending on what the array represents you can then do some string concatenating to put all the bits together.

A: StringBuilder sb = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
       sb.AppendFormat("{0:x2}", b)
}
return sb.ToString();


text:
Q: Yup InferType for array of strings not working as expected I'm trying to use Yup to define a schema and generate a Typescript Type that I can use for my objects.
Using InferType seems to work fine for strings and objects, but there's unexpected behavior for arrays. When required() or defined() is used with of(), the types stop working as I would expect.
NOTE: the validation functionality is working fine; I'm only having trouble with InferType
Ideal: InferType combines all operations to the expected type string[]
const schema = yup.array().required().of(yup.string().required());
type SchemaType = yup.InferType<typeof schema>;

// Type should be `string[]`
const schemaInstance: SchemaType = ["string1"];

Actual Scenario 1: array is string[] | undefined
const schema = yup.array().required().of(yup.string().required());
type SchemaType = yup.InferType<typeof schema>;

// Type is `string[] | undefined` so the following line compiles
const schemaInstance: SchemaType = undefined;

Actual Scenario 2: array is any
const schema = yup.array().of(yup.string().required()).required();
type SchemaType = yup.InferType<typeof schema>;

// Type is `any` so the following line compiles
const schemaInstance: SchemaType = {};

Is there a way to make these types work as expected for an array of strings?

A: Try
const schema = yup.array().of(yup.string().required()).required();
type SchemaType = yup.InferType<typeof schema>;

It should work now, your error has been fixed.


text:
Q: Having a problem proving $\operatorname{rank}T = m$.
So, I have managed to do parts a,b and the first half of c, However I am struggling with showing that $\operatorname{rank} T = m$.
Any tips are really appreciated.
Thanks

A: So I will attempt to prove what you need without invoking the Rank-Nullity Theorem, as I feel that the whole point of this exercise is to prove it. If you already have access to it, then I think you can be more direct in your argumentation.
You are given an $n$-dimensional real vector space $V$, an $m$-dimensional subspace $U$, and you are told there is an inner product at your disposal. You are also given a basis $\{u_1,\cdots,u_m\}$ of $U$.
Now, choose a vector in $V\setminus U$, say $w_1$. Define $v_1=w_1-\sum u_i\frac{\langle u_i,w_1\rangle}{\langle u_i,u_i\rangle}$. Then it is clear that $v_1\neq \vec{0}$ (since that would imply that $w_1\in U$), and by construction $v_1\in U^\perp$. Now, choose a vector in $V\setminus \text{span}(U,\{v_1\})$, say $w_2\ldots$
Basically, repeat the arguemntation that gives you the Gram-Schmidt process, but use it to create new basis vectors that are orthogonal to everything you have so far. This process ends because $V$ is finite dimensional, and you will be left with a basis of $V$ of the form $\{u_1,\ldots,u_m,v_1,\ldots,v_{n-m}\}$ with precisely the properties you need.
If you have the Rank-Nullity Theorem you are then done, as you have pinned down the dimensions of the ambient space and the kernel. If you don't have that theorem, then you need to argue about the dimensions of the image of your transformation $T$, but that is probably even easier than what I have done here; the dimension of the image is the size of a basis for the image, and you need only show that the transformation is a surjection.
EDIT: I don't think I got enough sleep last night, I appear to have wandered a lot in my answer, and accidentally answered part (d) as well.


text:
Q: django Q as chained .filter() There are 2 models connected with a many-to-many relationship.
class Record():
    working_on_record = models.ManyToManyField(
        UserProfile, related_name="working_on_record", blank=True)

class UserProfile():
    name = CharField...

The UserProfile is just a basic user model.
Now I want to query a search for records and check if all keywords are matched but if I do:
query = Q()
c1 = UserProfile.objects.filter(name__icontains='peter')
query.add(Q(working_on_record__in=c1), Q.AND)

c2 = UserProfile.objects.filter(name__icontains='john')
query.add(Q(working_on_record__in=c2), Q.AND)

set3 = list(models.Record.objects.filter(query))

Set3 is empty, despite there is a record which has two people working on it whose names are "john smith" and "peter parker". If I replace "john" in c2 by "parker" I get all records where "peter parker" is working on it.
But if I chain the filter methods:
set4 = list(models.Record.objects
            .filter(working_on_record__in=c1)
            .filter(working_on_record__in=c2)
       )

set4 is not empty and contains the record I want.
Is it possible to change the Q-query so that I get the behavior I want?
Is it possible to filter with a Q-query on one many-to-many-relationship with different values from different objects connected with an AND?
I don't like the idea of chaining the filter methods, because of multiple possible usages of the Q-query, so I would have to iterate at multiple occasions through all queries and chain them.


text:
Q: Is the default behavior with Fluent NHibernate to lazy load HasMany collections? when I am setting up my fluent mappings, what is the default for collections? Do I need to explicitly set them as lazy-load, or is that the default?

A: Note this is changed as of current day to be inline with NHibernate standards which is lazy loading is enabled by default for everything.


text:
Q: Memory barrier problems for writing and reading an image OpenGL i'm having a problem trying to reading an image from a fragment shader, first i write into the image in shader porgram A (im just painting blue on the image) then i'm reading from another shader program B to display the image, but the reading part is not getting the right color i'm getting a black image
Unexpected result
This is my application code:
void GLAPIENTRY MessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam)
{
    std::cout << "GL CALLBACK: type = " << std::hex << type << ", severity = " << std::hex << severity << ", message = " << message << "\n"
    << (type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "") << std::endl;
}

class ImgRW
    : public Core
{
public:
    ImgRW()
        : Core(512, 512, "JFAD")
    {}

virtual void Start() override
{
    glEnable(GL_DEBUG_OUTPUT);
    glDebugMessageCallback(MessageCallback, nullptr);

    shader_w = new Shader("w_img.vert", "w_img.frag");
    shader_r = new Shader("r_img.vert", "r_img.frag");

    glGenTextures(1, &space);
    glBindTexture(GL_TEXTURE_2D, space);
    glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA32F, 512, 512);
    glBindImageTexture(0, space, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);

    glGenVertexArrays(1, &vertex_array);
    glBindVertexArray(vertex_array);
}

virtual void Update() override
{
    shader_w->use(); // writing shader
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

    shader_r->use(); // reading shader
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}

virtual void End() override
{
    delete shader_w;
    delete shader_r;

    glDeleteTextures(1, &space);

    glDeleteVertexArrays(1, &vertex_array);
}

private:
    Shader* shader_w;
    Shader* shader_r;

GLuint vertex_array;

GLuint space;
};

#if 1
CORE_MAIN(ImgRW)
#endif

and these are my fragment shaders:
Writing to image
Code glsl:
#version 430 core

layout (binding = 0, rgba32f) uniform image2D img;

out vec4 out_color;

void main()
{
    imageStore(img, ivec2(gl_FragCoord.xy), vec4(0.0f, 0.0f, 1.0f, 1.0f));
}

Reading from image
Code glsl:
#version 430 core

layout (binding = 0, rgba32f) uniform image2D img;

out vec4 out_color;

void main()
{
    vec4 color = imageLoad(img, ivec2(gl_FragCoord.xy));
    out_color = color;
}

The only way that i get the correct result is if i change the order of the drawing commands and i dont need the memory barriers, like this (in the Update fuction of above):
shader_r->use(); // reading shader
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

shader_w->use(); // writing shader
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

I don't know if the problem is the graphics card or the drivers or if i'm missing some kind of flag that enables memoryBarriers or if i put the wrong barrier bits or if i placed the barriers in the code in the wrong part
The Vertex shader for both shader programs is the next:
#version 430 core

void main()
{
    vec2 v[4] = vec2[4]
    (
        vec2(-1.0, -1.0),
        vec2( 1.0, -1.0),
        vec2(-1.0,  1.0),
        vec2( 1.0,  1.0)
    );

    vec4 p = vec4(v[gl_VertexID], 0.0, 1.0);
    gl_Position = p;
}

and in my init function is:
void Window::init()
{
    glfwInit();
    window = glfwCreateWindow(getWidth(), getHeight(), name, nullptr, nullptr);
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);
    glfwSetCursorPosCallback(window, cursorPosCallback);

    //glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    assert(gladLoadGLLoader((GLADloadproc)glfwGetProcAddress) && "Couldn't initilaize OpenGL");

    glEnable(GL_DEPTH_TEST);
}

and in my function run i'm calling my start, update and end functions
void Core::Run()
{
    std::cout << glGetString(GL_VERSION) << std::endl;

    Start();

    float lastFrame{ 0.0f };

    while (!window.close())
    {
        float currentFrame = static_cast<float>(glfwGetTime());
        Time::deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        glViewport(0, 0, getWidth(), getHeight());
        glClearBufferfv(GL_COLOR, 0, &color[0]);
        glClearBufferfi(GL_DEPTH_STENCIL, 0, 1.0f, 0);

        Update();

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    End();
}

A:
glEnable(GL_DEPTH_TEST);

As I suspected.
Just because a fragment shader doesn't write a color output doesn't mean that those fragments will not affect the depth buffer. If the fragment passes the depth test and the depth write mask is on (assuming no other state is involved), it will update the depth buffer with the current fragment's depth (and the color buffer with uninitialized values, but that's a different matter).
Since you're drawing the same geometry both times, the second rendering's fragments will get the same depth values as the corresponding fragments from the first rendering. But the default depth function is GL_LESS. Since any value is not less than itself, this means that all fragments from the second rendering fail the depth test.
And therefore, they don't get rendered.
So just turn off the depth test. And while you're at it, turn off color writes for your "writing" rendering pass, since you're not writing to the color buffers.

Now, you do properly need the memory barrier between the two draw calls. But you only need the GL_SHADER_IMAGE_ACCESS_BARRIER_BIT, since that's how you're reading the data (via image load/store, not samplers).


text:
Q: iOS - Is it possible to have different versions of UIView subclass in one XIB file? (Similar to UITableViewCell Prototypes) I created a custom notification view (UIView Subclass) in a XIB file. However, I want to have multple types (i.e. one would have one UILabel, another would have 2 UILabels for Title and Subtitle, etc.)
I do this a lot in UITableViewCells using prototypes and cell identifiers, and was wondering if it is possible to do this in one XIB file, and just call the actual view I want to use for the appropriate notification type.
Here is a screenshot of the XIB file I have so you can see what I mean:


text:
Q: AWS graphql does not update I have this query here:
export const econStatusUpdate = (
  groupRequestId: string,
  status: AnforderungEconStatusT
) => {
  console.log(status);
  return axios({
    url: envs.graphqlApiEndpoint!,
    method: "post",
    headers: {
      "x-api-key": envs.graphqlKey!,
    },
    data: {
      query: print(gql(updateGrouprequest)),
      variables: {
        input: {
          id: groupRequestId,
          [status]: true,
        },
      },
    },
  }).then((res) => console.log(res?.data.data));
};

And this is how the update looks like:
export const updateGrouprequest = /* GraphQL */ `
  mutation UpdateGrouprequest(
    $input: UpdateGrouprequestInput!
    $condition: ModelGrouprequestConditionInput
  ) {
    updateGrouprequest(input: $input, condition: $condition) {
      id
      requesterId
      groupId
      accepted
      message_received
      consent_granted
      get_degree
      createdAt
      updatedAt
      _version
      _deleted
      _lastChangedAt
    }
  }
`;

For some reason this does not update it. It also throws no error. My response what i get is always:
get_degree
{
  updateGrouprequest: {
    id: '327647e7-c267-4514-ba0e-5bb7fbefe586',
    requesterId: 'b54807ef-3b53-42ee-a559-0c1042d7a121',
    groupId: '32cdcbe8-646d-4680-bb64-8172452a46ca',
    accepted: false,
    message_received: false,
    consent_granted: false,
    get_degree: false,
    createdAt: '2022-06-29T18:16:31.766Z',
    updatedAt: '2022-06-29T18:16:31.766Z',
    _version: 17,
    _deleted: null,
    _lastChangedAt: 1656527657777
  }
}

Only the time and version changes, what i am i doing wrong?
Here is also my graphql schema:
type Grouprequest
  @model
  @auth(rules: [{ allow: private }, { allow: public, provider: apiKey }]) {
  id: ID!
  requesterId: ID!
  groupId: ID!
  accepted: Boolean @default(value: "false")

  message_received: Boolean @default(value: "false")
  consent_granted: Boolean @default(value: "false")
  get_degree: Boolean @default(value: "false")
}

A: You need to increase the _version.You either do it manually or automatic. I do it with Date.now()
export const econStatusUpdate = (
  groupRequestId: string,
  status: AnforderungEconStatusT
) => {
  console.log(status);
  return axios({
    url: envs.graphqlApiEndpoint!,
    method: "post",
    headers: {
      "x-api-key": envs.graphqlKey!,
    },
    data: {
      query: print(gql(updateGrouprequest)),
      variables: {
        input: {
          id: groupRequestId,
          [status]: true,
          _version: Date.now()
        },
      },
    },
  }).then((res) => console.log(res?.data.data));
};


text:
Q: How to evaluate $\lim_{n \to \infty} \sum_{i=1}^n \arcsin{(u \cdot i/n)}$ without Riemann-sums How to evaluate the limit $$\lim_{n \to \infty} \sum_{i=1}^n \dfrac{1}{n}\arcsin{(u \cdot i/n)}$$
Where $0 < u \leq 1$. There is a closed form expression, but I just don't know how to find it.
Without Riemann-summs.

A: Note that
$$\dfrac{1}{n}\arcsin{(u \cdot i/n)}=i\cdot \left(\frac{u}{n^2}+o\left(\frac1{n^2}\right)\right)$$
then
$$\sum_{i=1}^n \dfrac{1}{n}\arcsin{(u \cdot i/n)}=\left(\frac{u}{n^2}+o\left(\frac1{n^2}\right)\right)\sum_{i=1}^n i =\frac{u}{n^2}\frac{n(n+1)}2+o\left(\frac1{n^2}\right)\frac{n(n+1)}2=$$
$$=\frac{u}{2}\frac{n(n+1)}{n^2}+\frac{o\left(\frac1{n^2}\right)}{\frac1{n^2}}\frac{n(n+1)}{2n^2}\to \frac u 2$$


text:
Q: Mutate a result from "useResult" (Vue Apollo) I am using the Composition API. I have a component which queries the backend and returns a list of events:
const { result, loading, error } = useQuery(FindEvents, variables, { fetchPolicy: 'cache-and-network' })
let events = useResult(result, [], data => data.events)

This works fine, however, I have a child component with a form where the user can edit the data of a single event, which is then mutated back to the backend, and emits an update to the Event list. However my function which handles the update on the list throws an error saying that it cannot update a computed value:
  onEventUpdate (mutableEvent) {
    try {
      const index = _.findIndex(events.value, ({id}) => id === mutableEvent.id) // lodash
      if (index < 0) {
        events.value.push(mutableEvent);
      } else {
        events.value[index] = mutableEvent;
      }
    } catch (err) {
      console.error(`Couldn't assign value: ${err}`) // TypeError: Cannot assign to read only property '12' of object '[object Array]'
    }
  }

Is there some way to update this property?


text:
Q: R Shiny — get file size without uploading? Is there a way to "peek" at the file size without uploading files to R Shiny?

A: With suggestions provided by @ismirsehregal, we can modify the fileInput and add some JS to achieve your goal.
library(shiny)
ui <- fluidPage(
    fileInput("check", NULL, buttonLabel = "Upload to check", placeholder = "Check File Size"),
    # remove progress bar since we are not truely uploading
    tags$style("#check .shiny-file-input-progress {display: none}"),
    tags$script(
        "
        $('#check').on('change', function() {
          $(this)
            .parents('div.input-group')
            .find('.form-control')
            .attr('placeholder', `File size is ${this.files[0].size}`); // update text

          // If you want R server to also know the size, we can set up an input
          Shiny.setInputValue('check_size', this.files[0].size)
          $(this).val(''); // this prevents shiny to takeover the file and upload the file
        });
        "
    )
)
server <- function(input, output, session) {
    observe(print(input$check_size))
}

shinyApp(ui, server)

This will get you the file size both on UI and server. Hope this is what you want.


text:
Q: Trying to mock certain functions in ASP Identity (non-core) and will not compile I have been having trouble mocking some objects that are scattered around the AccountsController from the default project in ASP.NET 5 and it makes it so I can't unit test the controllers.
For example, I am trying to mock up the code for the Register action.
[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
            {
                FirstName = model.FirstName, LastName = model.LastName, UserName = model.Email, Email = model.Email,
                IsActive = false, NewRequest = true
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                var email = _settings.GetEmailLogic();// EmailLogic(_settings);
                var emailuser = new VGSEmail(_settings)
                {
                    Id = user.Id,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    ToEmail = new List<string> {model.Email},
                    FromEmail = _settings.GetFromEmail(),
                    Subject = EmailMessages.RegisterSubject(),
                    Body = EmailMessages.RegisterMessage(model.FirstName)
                };
                var message = email.CreateMailMessage(emailuser);
                email.Send(message);
                await SignInManager.SignInAsync(user, false, false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");

                return RedirectToAction("SelectOrganization");
            }

            AddErrors(result);
        }

I get to UserManager.CreateAsync and it dies from null. So I try the following:
var userManager = new Mock<ApplicationUserManager>();
        var identityresult = new Mock<IdentityResult>();
        identityresult.Setup(s => s.Succeeded).Returns(true);

        userManager.Setup(s => s.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
            .ReturnsAsync(Task.FromResult(identityresult);

But that second line will not compile and keeps complaining about :
'ISetup>' does not contain a definition for 'ReturnsAsync' and the best extension method overload 'SequenceExtensions.ReturnsAsync>>(ISetupSequentialResult>>>, Task>)' requires a receiver of type 'ISetupSequentialResult>>>'   OnlineRepoWebSite.Tests
I know it contains a definition for ReturnsAsync because I use it all the time.
For example, the following work fine:
userManager.Setup(s => s.FindById(It.IsAny<string>())).Returns(new ApplicationUser());
        userManager.Setup(s => s.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(new ApplicationUser()));

But I am also having similar trouble with SignInManage. For example, the second line won't compile either.
var signInManager = new Mock<ApplicationSignInManager>(userManager, authenticationManager.Object);
        signInManager.Setup(s => s.PasswordSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(),It.IsAny<bool>()))
            .ReturnsAsync(Task.FromResult(SignInStatus.Success));

Can anyone point out what I am doing wrong? Even better if any has a complete unit test of the default AccountController in MVC I would be greatly in your debt in case I run into more issues later.

A: When calling ReturnsAsync return the actual return object not a Task. ie:
userManager
    .Setup(_ => _.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
    .ReturnsAsync(identityresult); //<-- This here

and also for the other one
signInManager
    .Setup(_ => _.PasswordSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(),It.IsAny<bool>()))
    .ReturnsAsync(SignInStatus.Success);

.ReturnsAsync(TValue) is basically a wrapper for .Returns(Task.FromResult(TValue))
As for making the controller more testable, that is a broad topic.
Maybe the answer I gave here
Moving ApplicationUser and other models out of MVC project
might help but it does require a lot of refactoring to make the code more SOLID.


text:
Q: Using JaxWsProxyFactoryBean and Spring how do I make an HTTPS connection through a proxy? I am trying to use JaxWsProxyFactoryBean to connect to a TLS1.2 https service using spring boot and java config through a proxy.  I have been unable to find any samples, or information about how to configure this.  Im using wsdl2java to build all of the objects that eventually get returned from JaxWsProxyFactoryBean.  Any help would be greatly appreciated.  What I currently have:
 private <T> T cxfClient(String address, String user, String pass, Class<T> serviceClass) {
    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setAddress(address);
    factory.setUsername(user);
    factory.setPassword(pass);

    return factory.create(serviceClass);
}

and
@Bean
public Client client() {
    Client client = ClientProxy.getClient(lexisNexisClient());
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.getClient().setProxyServer("myproxy");
    http.getClient().setProxyServerPort(myport);
    http.getProxyAuthorization().setUserName("myuser");
    http.getProxyAuthorization().setPassword("mypass");
    return client;
}

I am currently getting an error:
Caused by: java.lang.NoSuchMethodError: org.apache.cxf.configuration.jsse.TLSClientParameters.getSslContext()Ljavax/net/ssl/SSLContext

Any help would be greatly appreciated.
Thanks,
Brian

A: Issue ended up being a dependency problem with CXF versions.  Apparently the Ljavax/net/ssl/SSLContext means there is a dependency version conflict.
Thanks,
Brian


text:
Q: $P(T_2 \ge T_1)$ Exponentially distributed functions I have a problem regarding probability.
The lifetime $T$ of a product is exponentially distributed.
Product 1 has expected lifetime: $F_1(t) = 1-e^{-t/1000} $
Product 2 has expected lifetime: $F_2(t) = 1-e^{-t/500} $
What is the probability that product 2 outlives product one? That is:
$P(T_2 \geq T_1)$

A: You need to know the joint distribution of $T_1$ and $T_2$ for that. I guess they are assumed to be independent in which case the probability is given by
$$ \int_0^\infty \int_0^\infty 1 \{ t_2 \geq t_1 \} f_1(t_1) f_2(t_2) dt_1 dt_2    $$
where $f_1$ and $f_2$ are the densities of the corresponding exponential distributions.

A: We have that
$$
P(T_1 \le T_2)=P(-T_2+T_1 \le 0)=F_{-T_2+T_1}(0)
$$
where $F_X$ denotes the cdf of a random variable $X.$
A reasonable assumption is that $-T_2$ and $T_1$ are independent. Then as a corollary of the convolution formula for the sum $-T_2+T_1$ we get that
$$
F_{-T_2+T_1}(z)=\int_0^\infty F_{-T_2}(z-t) f_{T_1}(t)dt
$$
where $f_{T_1}$ is the pdf of $F_{T_1}$ (which is your $F_1;$ details?). Since $F_1$ is continuously differentiable,
$$
f_{T_1}(t)=F_1'(t)=\frac{\mathrm{exp}(-t/1000)}{1000}.
$$
Now
$$
F_{-T_2+T_1}(0)=\int_0^\infty F_{-T_2}(-t) \frac{\mathrm{exp}(-t/1000)}{1000} dt
$$
and, observing that $F_{-T_2}(-t)=\mathrm{exp}(-t/500)$ (why?) we get that
$$
P(T_1 \le T_2) =\int_0^\infty \mathrm{exp}(-t/500) \frac{\mathrm{exp}(-t/1000)}{1000} dt=\frac 13.
$$

A: I'm going to guess that you intended these to be independent.  That assumption is often not mentioned but ought to be.
You can write either
$$
\int_0^\infty \left(\int_{t_1}^\infty \cdots\cdots \, dt_2 \right) \, dt_1
$$
or
$$
\int_0^\infty \left(\int_0^{t_2} \cdots\cdots \,  dt_1 \right) \, dt_2
$$
where the expression in place of "$\cdots\cdots$" is the joint density function.  Either way you're integrating over the part of the plane in which $t_2>t_1$.
If the two random variables are independent, then the joint density function is
$$\frac{1}{1000} e^{-t_1/1000}\cdot\frac{1}{500} e^{-t_2/500}$$
if $t_1,t_2\ge0$ and $0$ if either $t_1<0$ or $t_2<0$.
The first integral is slightly more convenient because you evaluate at $\infty$ and expression that approaches $0$ there.
\begin{align}
& {}\qquad \int_0^\infty \left(\int_{t_1}^\infty \frac{1}{1000} e^{-t_1/1000}\cdot\frac{1}{500} e^{-t_2/500} \, dt_2 \right) \, dt_1 \\
& = \int_0^\infty\left(\frac{1}{1000}e^{-t_t/1000} \int_{t_1}^\infty \frac{1}{500} e^{-t_2/500} \, dt_2 \right) \, dt_1 \\
& {}\qquad (\text{since the expression that was pulled out does not depend on }t_2) \\
& = \int_0^\infty \frac{1}{1000} e^{-t_1/1000} \cdot e^{-t_1/500} \, dt_1 \\
& {} \qquad (\text{The only variable still here is $t_1$ since the definite integral was evaluated.}) \\ & = \int_0^\infty \frac{1}{1000} e^{-3t_1/1000} \, dt_1 \\
& = \int_0^\infty e^{-3u}\,du = \frac 1 3.
\end{align}

A: Let's try an intuitive argument in addtion to three already posted.
One of these exponential random variables has an expected value of $1000$ and for the other it's $500$.  That means Product 2 must be replaced twice for every time Product 1 is replaced.  Therefore an average set of three expiration events consists of two expirations of Product 2 and one expiration of Product 1.  Hence the probability that the next to expire is Product 1 is $1/3$.


text:
Q: How to get linear function matrix $$T: \mathbb{R^2} \longrightarrow \mathbb{R^2}$$
$$Ker(T) = \mathbb{R}(1, 2)$$
$$T(2, 3) = (5, -2)$$
The matrix for the linear function is (this is the solution): $$\begin{vmatrix} 10  \quad -5 \\ -4 \quad 2 \end{vmatrix}$$
But, knowing that a linear function is uniquely determined by the vector on its basis (of $\mathbb{R^2}$ in this case), and that $\begin{vmatrix} 1 \\ 2 \end{vmatrix}$ and $\begin{vmatrix} 2 \\ 3 \end{vmatrix}$ are vectors of a $\mathbb{R^2}$ basis, I can only get $\begin{vmatrix}0 \quad 5 \\ 0 \quad -2 \end{vmatrix}$ as matrix of the $T$ linear function.
Can you help me, please?

A: Denote $e_1=(1,0)$ and $e_2=(0,1)$. So $(1,2)=e_1+2e_2$, $(2,3)=2e_1+3e_2$ and $(5,-2)=5e_1-2e_2$. We have
$$\begin{align}
T(1,2)=&T(e_1)+2T(e_2)=(0,0)\\
T(2,3)=&2T(e_1)+3T(e_2)=(5,-2)
\end{align}$$
Substituting $T(e_1)=-2T(e_2)$ in the second equation one gets
$$-T(e_2)=(5,-2)$$
And so $T(e_1)=(10,-4)$ and the matrix we're looking for is
$$\begin{bmatrix} 10 & -5\\-4 & 2\end{bmatrix}$$


text:
Q: kinect sdk 2.0 joint angles and tracking How  to check whether the joints you are accessing have a tracking state of Tracked. I am finding the angles of 8 of the joints and I can't seem to get the result to be displayed on my screen,
public double AngleBetweenTwoVectors(Vector3D vectorA, Vector3D vectorB)
    {
        double dotProduct = 0.0;
        vectorA.Normalize();
        vectorB.Normalize();

        dotProduct = Vector3D.DotProduct(vectorA, vectorB);

        return (double)Math.Acos(dotProduct) / Math.PI * 180;
    }

    public double[] GetVector(Body skeleton)
    {

        Vector3D Shoulder = new Vector3D(skeleton.Joints[JointType.SpineShoulder].Position.X, skeleton.Joints[JointType.SpineShoulder].Position.Y, skeleton.Joints[JointType.SpineShoulder].Position.Z);
        Vector3D RShoulder = new Vector3D(skeleton.Joints[JointType.ShoulderRight].Position.X, skeleton.Joints[JointType.ShoulderRight].Position.Y, skeleton.Joints[JointType.ShoulderRight].Position.Z);
        Vector3D LShoulder = new Vector3D(skeleton.Joints[JointType.ShoulderLeft].Position.X, skeleton.Joints[JointType.ShoulderLeft].Position.Y, skeleton.Joints[JointType.ShoulderLeft].Position.Z);
        Vector3D RElbow = new Vector3D(skeleton.Joints[JointType.ElbowRight].Position.X, skeleton.Joints[JointType.ElbowRight].Position.Y, skeleton.Joints[JointType.ElbowRight].Position.Z);
        Vector3D LElbow = new Vector3D(skeleton.Joints[JointType.ElbowLeft].Position.X, skeleton.Joints[JointType.ElbowLeft].Position.Y, skeleton.Joints[JointType.ElbowLeft].Position.Z);
        Vector3D RWrist = new Vector3D(skeleton.Joints[JointType.WristRight].Position.X, skeleton.Joints[JointType.WristRight].Position.Y, skeleton.Joints[JointType.WristRight].Position.Z);
        Vector3D LWrist = new Vector3D(skeleton.Joints[JointType.WristLeft].Position.X, skeleton.Joints[JointType.WristLeft].Position.Y, skeleton.Joints[JointType.WristLeft].Position.Z);
        Vector3D RKnee = new Vector3D(skeleton.Joints[JointType.KneeRight].Position.X, skeleton.Joints[JointType.KneeRight].Position.Y, skeleton.Joints[JointType.KneeRight].Position.Z);
        Vector3D LKnee = new Vector3D(skeleton.Joints[JointType.KneeLeft].Position.X, skeleton.Joints[JointType.KneeLeft].Position.Y, skeleton.Joints[JointType.KneeLeft].Position.Z);
        Vector3D RAnkle = new Vector3D(skeleton.Joints[JointType.AnkleRight].Position.X, skeleton.Joints[JointType.AnkleRight].Position.Y, skeleton.Joints[JointType.AnkleRight].Position.Z);
        Vector3D LAnkle = new Vector3D(skeleton.Joints[JointType.AnkleLeft].Position.X, skeleton.Joints[JointType.AnkleLeft].Position.Y, skeleton.Joints[JointType.AnkleLeft].Position.Z);
        Vector3D Hip = new Vector3D(skeleton.Joints[JointType.SpineBase].Position.X, skeleton.Joints[JointType.SpineBase].Position.Y, skeleton.Joints[JointType.SpineBase].Position.Z);
        Vector3D RHip = new Vector3D(skeleton.Joints[JointType.HipRight].Position.X, skeleton.Joints[JointType.HipRight].Position.Y, skeleton.Joints[JointType.HipRight].Position.Z);
        Vector3D LHip = new Vector3D(skeleton.Joints[JointType.HipLeft].Position.X, skeleton.Joints[JointType.HipLeft].Position.Y, skeleton.Joints[JointType.HipLeft].Position.Z);

        double AngleRElbow = AngleBetweenTwoVectors(RElbow - RShoulder, RElbow - RWrist);
        double AngleRShoulder = AngleBetweenTwoVectors(RShoulder - Shoulder, RShoulder - RElbow);
        double AngleLElbow = AngleBetweenTwoVectors(LElbow - LShoulder, LElbow - LWrist);
        double AngleLShoulder = AngleBetweenTwoVectors(LShoulder - Shoulder, LShoulder - LElbow);
        double AngleRKnee = AngleBetweenTwoVectors(RKnee - RHip, RKnee - RAnkle);
        double AngleLKnee = AngleBetweenTwoVectors(LKnee - LHip, LKnee - LAnkle);
        double AngleRHip = AngleBetweenTwoVectors(RHip - Hip, RHip - RKnee);
        double AngleLHip = AngleBetweenTwoVectors(LHip - Hip, LHip - LKnee);

        Results.Add(AngleLShoulder);
        Results.Add(AngleLElbow);
        Results.Add(AngleLKnee);
        Results.Add(AngleLHip);
        Results.Add(AngleRShoulder);
        Results.Add(AngleRElbow);
        Results.Add(AngleRKnee);
        Results.Add(AngleRHip);

        double[] resultsArray = Results.ToArray();

        return resultsArray;

    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        result1.Text = Results[4].ToString();
        result2.Text = Results[5].ToString();
        result3.Text = Results[6].ToString();
        result4.Text = Results[7].ToString();
        result5.Text = Results[0].ToString();
        result6.Text = Results[1].ToString();
        result7.Text = Results[2].ToString();
        result8.Text = Results[3].ToString();
    }

There is live feed coming from the kinect to the program, but when the button is pressed, there is a null pointer exception thrown for some reason. I am thinking it is because i am not sure if the joints are tracked. How do I go about doing that?
Also is my code to display the angles correct? I am using textbox for each result.

A: foreach (Joint joint in skeleton.Joints)
            {
                if (joint.TrackingState == JointTrackingState.Tracked)
                {
                    //Do something
                }
                else if (joint.TrackingState == JointTrackingState.Inferred)
                {
                    //Do something else
                }
            }

This loops through the Joints array and checks for every Joint if the JointTrackingState is Tracked, Inferred or NotTracked, see here. The program to calculate the angles is perfectly fine.
If you have more questions on how to calculate the angle of Joints see here.
If you want a working programm, I'll send it to you per e-mail. Or see here. Hope this helps :)


text:
Q: "Spring xd" versus storm I'm actively looking for a real time big data analysis solution.
for now I've identified a mature actor Twitter Storm and also a young challenger Spring XD.
Does anyone know if Spring XD could real time process log event streams or twitter streams as well as Storm would do ?
What are the know limitations of both technologies ?

A: SpringXD is a great tool if you are looking to string together several modules without having to write too much code.  We used it for a little bit in production and found that it let us scale.
SpringXD is worth using if you don't have to create too many custom modules, need containers for stability, and don't have too elastic of a load.
SpringXD also allows quick integration with several technologies (Redis, RabbitMQ, Hadoop to name a few) out of the box.  If you are looking to get something quickly distributed, it might be a great tool for your use case.  However, if you have a very elastic load, or want to deploy several different streams, then they don't currently recommend that.

A: I am interested in the same thing, I've worked with Spring for years, and recently Storm. my guess is that they both will perform very well..I am using Storm currently simply because it's more mature..However, if it was a Spring Based project..i would recommend giving Spring XD a shot before Storm.


text:
Q: how to rename a file if it's already exist I made a function auto add _(number) to a uploaded file if they are already exist. However i'm having a problem that if i upload an image like image_1.jpg it will turn to image_1_1.jpg . How to make it turn to image_2.jpg. Here is my function:
$scan=scandir($destination);
$destination='C:\xampp\htdocs\test\images\\';
function checkExist($name)
{

    global $scan;
    if(in_array($name,$scan))
    {
        $findDot=strpos($name,'.');
        $base=substr($name,0,$findDot);

        $extension=substr($name,$findDot);
        $i=1;
        $newName=$base.'_'.$i++.$extension;
        echo $newName;

        //the upload image will be renamed to .... in order to avoid same name
    }
    else
    {
        echo 'not found';
    }
}

A: you could check with preg_match if the new filename matches to the string. i.e:
preg_match("/^[\w]+\_+[\d]+.jpg/", $uploadedFile);

if so then split it, remove the last number...

A: There are several ways for renaming image in PHP before uploading to the server. appending timestamp, unique id, image dimensions plus random number etc.
First, Check if the image filename exists in the hosted image folder otherwise upload it. The while loop checks if the image file name exists and appends a unique id as shown below ...
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);

$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
    $actual_name = (string)$original_name.$i;
    $name = $actual_name.".".$extension;
    $i++;
}


text:
Q: If volume of cone is halved, how will it affect height and radius A cone glass with radius 8 cm and height 9 cm is filled to its brim. Half the liquid is thrown out. what is the height and radius of the new cone formed by the liquid?

A: For similar 3D shapes, if $L$ is some linear measure of the shape (e.g. radius, height, circumference, diagonal length, etc...) then the volume is proportional to $L^3$.
If $V_f$ is your final volume and $V_0$ is your initial volume, the problem tells you that $V_f=\frac{1}{2}V_0$. Thus, considering the radii you will have $r_f^3=\frac{1}{2}r_0^3$, hence $r_f=r_0\sqrt[3]{\frac{1}{2}}=8\sqrt[3]{\frac{1}{2}}$, and similarly the new height is $9\sqrt[3]{\frac{1}{2}}$.


text:
Q: I can´t return the date and footer functions on flask
im a beginner, take that in cosideration, so, i need to pass the the footer and date functions and i somehow missing the point here

from flask import Flask, render_template
from datetime import datetime

app = Flask("Timer Workout")

@app.route("/")
def Landing():
    return render_template("Landing_Page.html")

def footer():
    footerdb = open("footer.txt")
    for i in range (3):
        footerdb.write("footer.txt" + " by Carlos ")
    footerdb.close()
    return render_template("Landing_Page.html", footerdb)

The same here,i can´t return the date function, i don´t know exactly what should i do. Help appreciated. Thanks a lot.
    @app.route("/index.html/")
def Home():
    current_time = datetime.datetime.now()
    return render_template("index.html", current_time = current_time)

if "Timer Workout" == "__main__":
    app.run()

A: The function is not returning anything because it is not called.
Where do you want the date/time to be returned ?
If it's in /index.html you should do something like that :
@app.route("/index.html/")
def Home():
    current_time = datetime.datetime.now()
    return render_template("index.html", current_time=current_time)

And then in your template you can add the variable inside your HTML code like that for example:
Current Date and Time: {{ current_time }}}

Basically you can define variables values inside your python main script. Pass them as arguments to the render_template function and then use them inside your template with {{ your_var }}.
Have a look here : https://jinja.palletsprojects.com/en/2.11.x/templates/

A: I didn't have time either but I can look into it now.
I think you are lost because you have two views with two different templates. And I guess, as for now, you only want to render one page.
So now your project should look like that:
Your mainscript.py is:
from flask import Flask, render_template
from datetime import datetime

app = Flask("Timer Workout")

@app.route("/")
def Landing():
    return render_template("Landing_Page.html")

def footer():
    footerdb = open("footer.txt")
    for i in range (3):
        footerdb.write("footer.txt" + " by Carlos ")
    footerdb.close()
    return render_template("Landing_Page.html", footerdb)

@app.route("/index.html/")
def Home():
    current_time = datetime.datetime.now()
    return render_template("index.html", current_time = current_time)

if "Timer Workout" == "__main__":
    app.run()

And then you should have two HTML files, Landing_page.html and index.html.
But, I think you are trying to render one and only one page with your footer and the current date and time.
For that I'll give you an example that should work. Just delete your footer() function which is buggy and not called anywhere and we'll make only one routing to render one template.
In your mainscript.py:
from flask import Flask, render_template
from datetime import datetime

app = Flask("Timer Workout")

@app.route("/")
def home():
    current_time = datetime.datetime.now()
    footer = "Placeholder string just for debugging"
    return render_template("index.html", current_time = current_time, footer = footer)

if "Timer Workout" == "__main__":
    app.run()

Then in your index.html file put something like that:

    <title>Index page</title>

Current date/time is : {{ current_time }}

The footer would be just below :

{{ footer }}

Now when you access to yourwebsite.com/ you'll see index.html properly rendered.
Of course then you should find a better way to add the footer, you will look into template inheritance with the extends tag. But for now try my example to understand the basics that should work easily.


text:
Q: Is it possible to have disjoint nested views in marionette So basically what I'm trying to do is to have a layoutView and inside that layoutView have a subview that is wrapped with the layoutView. The catch is that layoutView should also render information from model.
Something like this: http://i.stack.imgur.com/oLODv.png
So far, I didn't have any joy or success in achieving this, because it seems to me that views are somehow unitary and homogeneous, ergo can't be disjoint
For the layoutView I'd have following template:

    Hi, <%= userName %>

Some other information needed from model: <%= someVariable %>

with #someRegion showing the subView.
Is this possible or is there any similar approach to achieve this kind of nesting/wrapping views?


text:
Q: paste AuthorDocumentFragment (Oxygen) into TextArea (Java swing) I want to paste AuthorDocumentFragment (Oxygen) into TextArea (Java swing) of my modal dialog. But the element AuthorDocumentFragment is not supported for textarea. What do I do with this?
My code:
public void doOperation(final AuthorAccess authorAccess, final ArgumentsMap args)
        throws IllegalArgumentException, AuthorOperationException {
   AuthorNode[] nodeList2 = authorAccess.getDocumentController().findNodesByXPath("//*[@id]/child::node()", true, true, true);

    ArrayList<AuthorDocumentFragment> arrayList = new ArrayList<AuthorDocumentFragment>();

    for (AuthorNode i : nodeList2) {
        AuthorDocumentFragment newFragText = null;
        try {
            newFragText = authorAccess.getDocumentController().createDocumentFragment(i, true);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        arrayList.add(newFragText);
    }
}

void jList1MouseClicked(java.awt.event.MouseEvent evt) {
    textAreaRefs.setText(???);
}

A: The AuthorDocumentController API has a method to serialize an AuthorDocumentFragment to XML:
https://www.oxygenxml.com/InstData/Editor/SDK/javadoc/ro/sync/ecss/extensions/api/AuthorDocumentController.html#serializeFragmentToXML-ro.sync.ecss.extensions.api.node.AuthorDocumentFragment-


text:
Q: Novel in which aliens invade Earth, human teenagers look very similar to the alien teenagers The aliens have been winning the war and the humans realize that their teenagers look similar, so they train teenagers to be warriors to infiltrate their camp. On the way in, they are ambushed and the captain of the squad got separated from his team and knocked out.
The team believes their captain is dead, but they have to continue the mission. By the end of the book, it's found that their captain is alive and has been found by the enemy, but the one that is caring for him knows that he is human and won't tell anyone.

A: I initially just gave this suggestion in a comment, as I felt that some of the more significant details did not match the question. But from a reply posted by the OP it seems the answer is indeed "Assault" by Brian Falkner, the first book in the Recon Team Angel series.
The story takes place in a future where the Earth has been invaded by an alien race, the Bzadians, and the remaining humans are bunkered down in the Americas. The Recon Team Angel are a Special Forces unit composed of teenagers, recruited from around the world, who crucially are the right size and build to be disguised as aliens and infiltrate their base in Australia (actually at Uluru).
What I did not recognise is the detail given in the question "The team believes their captain is dead, but they have to continue the mission". From what I recall, it is rather the case that the team contains a traitor, a human who has been brainwashed by the aliens, and they have to try and discovery their identity while completing their mission.


text:
Q: Airflow, mark a task success or skip it before dag run We have a huge DAG, with many small and fast tasks and a few big and time consuming tasks.
We want to run just a part of the DAG, and the easiest way that we found is to not add the task that we don't want to run. The problem is that our DAG has many co-dependencies, so it became a real challenge to not broke the dag when we want to skip some tasks.
Its there a way to add a status to the task by default? (for every run), something like:
# get the skip list from a env variable
task_list = models.Variable.get('list_of_tasks_to_skip')

dag.skip(task_list)

or
for task in task_list:
    task.status = 'success'

A: As mentioned in the comments, you should use the BranchPythonOperator (or ShortCircuitOperator) to prevent the time-consuming tasks from executing. If you need downstream operators of these time-consuming tasks to run, you can use the TriggerRule.ALL_DONE to have those operators run, but note this will run even when the upstream operators fail.
You can use Airflow Variables to affect these BranchPythonOperators without having to update the DAG, eg:
from airflow.models import Variable

def branch_python_operator_callable()
  return Variable.get('time_consuming_operator_var')

and use branch_python_operator_callable as the Python callable for your BranchPythonOperator.

A: Have you considered using a decorator/higher order function around your callable?
I'm thinking of using something like the following:
def conf_task_id_skip(python_callable):
    def skip_if_configured(*args, **context):
        task_id = context["task_id"]
        dag_run = context["dag_run"]
        skip_task_ids = dag_run.conf.get("skip_task_ids", [])

        if skip_task_ids and task_id in skip_task_ids:
            return None
        else:
            return python_callable(*args, **context)

    return skip_if_configured

PythonOperator(
    task_id="task_id",
    python_callable=conf_task_id_skip(task_callable)
)

Then if I want I can pass manually the tasks I want to skip over (and still succeed).
If you wish so, you could also increase the robustness by adding a check for if skipping is disallowed (e.g. in prod):
def conf_task_id_skip(python_callable):
    def skip_if_configured(*args, **context):
        if Variable.get("disallow_conf_task_id_skip"):
            return python_callable(*args, **context)

        task_id = context["task_id"]
        dag_run = context["dag_run"]
        skip_task_ids = dag_run.conf.get("skip_task_ids", [])

        if skip_task_ids and task_id in skip_task_ids:
            return None
        else:
            return python_callable(*args, **context)

    return skip_if_configured


text:
Q: Strange Problem with File.Move command I have encountered a strange problem when using the File.Move command. The Programm actually moves and renames the file, but then throws me an exception that the sourcefile is not found; - what is expected because the File was moved.
The Program works fine if i catch the Exception but i'm wondering why i get these exception.
My Code:
  foreach (string str in CPM.prot.FKFinishedBad)
  {
        try
        {
          string dir = System.Configuration.ConfigurationSettings.AppSettings["ResultDir"] + "\\" + DateTime.Now.ToString("yyyy_MM_dd") + "_Bearbeitete Protokolle";
        if (!Directory.Exists(dir))
        {
          Directory.CreateDirectory(dir);
        }
          File.Move(System.Configuration.ConfigurationSettings.AppSettings["ResultDir"] + "\\" +  str + "_" + CPM.LastJob + ".txt", dir + "\\" + "\\" + str + "_" + CPM.LastJob + "_Nachproduziert" + ".txt");
        }
        catch (Exception e)
        {
        }
    }

A: Make sure that each item in CPM.prot.FKFinishedBad is unique - that may be a cause of the phenomenon.
Also, I'd recommend to refactor the code: the directory lines don't need to be repeated and should be outside of the loop.
And please learn to use String.Format and Path.Combine.

A: Try to suspend a thread for a half a second (or less) here:
if (!Directory.Exists(dir))
{
  Directory.CreateDirectory(dir);
  //suspend thread for 0.5 sec
}

This is probably related to fact that  you create a directory and immediately move a file. So suspend a thread to let "breath" to system.

A: Are you sure all of your files exist?
It might happen that one of them is missing (which explains the exception), while the others are processed correctly. you can also check them before the move with File.Exists.
Also, be careful when using empty catch blocks, they can cause a lot of headaches when debugging.

A: I have just been experiencing this problem, it took me a while to realise that there is a FileInfo.MoveTo command which appears to do the same thing.
However it doesn't throw an exception, and works.
It is a bit dodgy if there are two ways to do one thing and only one of them works.


text:
Q: Deseo evitar datos duplicados en google sheets con apps script Buenas taardes con todos.
Tengo este código que es GUARDAR realizado en apps script que es de google sheets.
Lo que quiero lograr es que no se me repitan datos duplicados de una celda especifica como por ejemplo el D8 y G8, pero por el momento deseo solo el D8.
Que en la hoja que se almacena se llama "BASE DE DATOS", allí quiero verificar que el número ya existen.
Me ayudarían muchísimo si me podrían ayudar, muchas gracias!
function Guardar(){
      var hojaActiva = SpreadsheetApp.getActiveSpreadsheet();
      var formulario = hojaActiva.getSheetByName("CONTACTO");
      var datos = hojaActiva.getSheetByName("BASE DE DATOS");

      const ss = SpreadsheetApp.getActive();
      const sh = ss.getSheetByName("CONTACTO");
      const rgl = sh.getRangeList(["D8","D10","D12","D14","D16","G8","G10","G12","G14","G16","K8","K10","K12","K14","K16","N8",    "N10","N12","N14"]);
      rgl.getRanges().forEach(r => {
         if(r.isBlank()){
          throw new Error(`${r.getA1Notation()} se encuentra vacía`)}
        });

      var valores = [[formulario.getRange("D8").getValue(),
                     formulario.getRange("D10").getValue(),
                     formulario.getRange("D12").getValue(),
                     formulario.getRange("D14").getValue(),
                     formulario.getRange("D16").getValue(),
                     formulario.getRange("G8").getValue(),
                     formulario.getRange("G10").getValue(),
                     formulario.getRange("G12").getValue(),
                     formulario.getRange("G14").getValue(),
                     formulario.getRange("G16").getValue(),
                     formulario.getRange("K8").getValue(),
                     formulario.getRange("K10").getValue(),
                     formulario.getRange("K12").getValue(),
                     formulario.getRange("K14").getValue(),
                     formulario.getRange("K16").getValue(),
                     formulario.getRange("N8").getValue(),
                     formulario.getRange("N10").getValue(),
                     formulario.getRange("N12").getValue(),
                     formulario.getRange("N14").getValue()]];

      datos.getRange(datos.getLastRow()+1,1,1,19).setValues(valores);

      Browser.msgBox("SE REGISTRO CORRECTAMENTE");

       Limpiar();
    }


text:
Q: Animating TextView's leftDrawable using ObjectAnimator I would like to animate leftDrawable of a TextView, I tried the following:
ObjectAnimator.ofFloat(drawable, "rotation", 0f, 360f).setDuration(300).start();
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);

But it doesn't seem to animate, in the past I've used AnimationDrawable and it works by putting several drawables in a <animation-list>, but apk size is a concern so I'm trying to avoid having multiple assets to achieve this.
Please let me know if I've done something wrong or this is not achievable using ObjectAnimator.
Thanks.

A: try this:
    TextView tv = new TextView(this);
    Drawable left = getResources().getDrawable(R.drawable.rotate);
    tv.setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
    final ObjectAnimator animator = ObjectAnimator.ofInt(left, "level", 0, 10000).setDuration(1000);
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick ");
            animator.start();
        }
    };
    tv.setOnClickListener(listener);
    tv.setGravity(Gravity.CENTER);
    tv.setTextSize(48);
    tv.setText("click me");
    setContentView(tv);

res/drawable/rotate.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0" android:toDegrees="720">
    <bitmap android:src="@drawable/ic_launcher"/>
</rotate>

A: I think that the problem is you call the animation to start before the drawable is drawn.
Try replace the order of the lines. Maybe you could add some delay.


text:
Q: Calculating angle between two Great Circles on a sphere I expected this to be simple, but I'm getting some strange results. I'd appreciate if someone could point out what I'm doing wrong.
I have 3 points (A, B, C) defined on the surface of the Earth (assumed to be a sphere) with [lat, long] coordinates for each point. I need to calculate the angle between the two Great Arcs formed by AC and AB.
I already have a function that calculates the Great Circle Distance (GCD), so I decided to solve this problem by getting the GCD for AC, AB and CA, reducing them to a unit sphere and then applying the  Spherical Law of Cosines to get at the angle BAC.
This appeared to work and gave me reasonable angles. However, I then tried to put all three points on the same Great Circle and a strange thing started happening. If B and C were within 1 degree, the results were reasonable, but as I started moving B and C further apart along the same Great Circle, the angle started growing!
For example:
A = 49, 1
B = 49, 10     => Angle: 0.0378
C = 49, 10.1

A = 49, 1
B = 49, 10     => Angle: 0.2270
C = 49, 10.6

A = 49, 1
B = 49, 10     => Angle: 3.7988
C = 49, 20

A = 49, 1
B = 49, 10     => Angle: 99.1027
C = 49, 200

Is this some sort of precision error, or is my formula wrong?
Here is the code (getDistance() is known to work):
  public static BigDecimal getAngle(
      final BigDecimal commonLat, final BigDecimal commonLong,
      final BigDecimal p1Lat, final BigDecimal p1Long,
      final BigDecimal p2Lat, final BigDecimal p2Long) {

    // Convert real distances to unit sphere distances
    //
    double a = getDistance(p1Lat, p1Long, commonLat, commonLong).doubleValue() / RADIUS_EARTH;
    double b = getDistance(p2Lat, p2Long, commonLat, commonLong).doubleValue() / RADIUS_EARTH;
    double c = getDistance(p1Lat, p1Long, p2Lat, p2Long).doubleValue() / RADIUS_EARTH;

    // Use the Spherical law of cosines to get at the angle between a and b
    //
    double numerator = Math.cos(c) - Math.cos(a) * Math.cos(b);
    double denominator = Math.sin(a) * Math.sin(b);
    double theta = Math.acos(numerator / denominator);

    // Back to degrees
    //
    double angleInDegrees = Math.toDegrees(theta);

    return new BigDecimal(angleInDegrees);
  }

Unfortunately for me, my application will often have points nearly on a line, so accuracy in this situation is important. What is going wrong here?
EDIT: As requested, here is the code for getDistance():
public static BigDecimal getDistance(final BigDecimal endLat, final BigDecimal endLong,
    final BigDecimal startLat, final BigDecimal startLong) {

  final double latDiff = Math.toRadians(endLat.doubleValue() - startLat.doubleValue());
  final double longDiff = Math.toRadians(endLong.doubleValue() - startLong.doubleValue());

  final double lat1 = Math.toRadians(startLat.doubleValue());
  final double lat2 = Math.toRadians(endLat.doubleValue());

  double a =
      Math.sin(latDiff / 2) * Math.sin(latDiff / 2) +
      Math.sin(longDiff / 2) * Math.sin(longDiff / 2) * Math.cos(lat1) * Math.cos(lat2);
  double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  double d = RADIUS_EARTH * c;

  return new BigDecimal(d);
}

The declaration of RADIUS_EARTH is irrelevant, b/c we multiply by it in distance calculation and then divide by it in angle calculation, so it is cancelled out.

A: A quick look on your coordinates say, that the latitude ist the same and longitude varies. But all circles made by latitude (except equator) aren't great circles. Did you try your program, if longitude is constant and latitude is varied?


text:
Q: how to use ag-grid (React version)'s API in chrome developer tools(F12) How to use ag-grid base on React API in chrome DevTools(F12).
test link: https://www.ag-grid.com/example/
such as
$("ag-root-wrapper").***.gridOptions.api.**

API:https://www.ag-grid.com/react-data-grid/grid-options/
my goal is in DevTools to use ag-grid's API to read/change the ag-grid table.
thanks.


text:
Q: SSO process - An acceptable solution? I need to implement a Single Sign On process for a site.  I'll refer to Site A as the site with the Sign on screen and site B as the site that needs to Auto sign on.  The two sites are on different domains and I do not have any control over site A.  But I need to suggest ideas for the process.
After some reading I have this suggestion.  Site A passes a ticket in the query string to site b.  Something like SiteB.aspx?Ticket={guid}.  This ticket must be a one time valid value that will be managed by Site A.  My site (Site B) will pass the Ticket back to site A in the form of a web service call.  The response from this call if the ticket is valid will contain an account ID that I can use to auto log in.
Does this seem an acceptable solution?  Site B will be under HTTPS.  Would passing the Ticket in the query string be secure or would the Ticket be best passed as an additional header?  Would the ticket still need to be encrypted if under https?

A: No, this does not seem like an acceptable solution to me, for a couple of reasons:

*

*The query string is not encrypted, even when using HTTPS

*Someone looking over the shoulder of a user could hijack that user's session

*You haven't specified a maximum lifetime of a ticket, which is important should the ticket be compromised (Kerberos tickets all use this functionality)

*You haven't established how Site B trusts Site A.  Sounds like someone could step in the middle and perhaps fool Site B into thinking it's Site A and Site B would authenticate them.

You could get both sites to share the same key so that they will honor each other's Forms Authentication cookie.


text:
Q: rename filename with a data column I hope this question is clear and feasible. I have many csv files labelled with a simple numeric ID (e.g., 1.csv, 2.csv, 3.csv, etc.).  Another csv file contains the actual data like below
ID  Site  Location Block
1    L1     1         a
2    L2     2         b
3 etc

My question is how to link the ID in the data file to rename the csv files. The output I would ideally like to have is L11a.csv, L22b.csv, etc. I think I need to concatenate each row observation's Site, Location, and Block into another column and then use that column as the filename for the write.table function?
I searched SO and this question is similar except in the reverse direction:
When importing CSV into R how to generate column with name of the CSV?
Many thanks for your assistance. This would save me hours in renaming files!

A: I have simulated your scenario with four csv files and the data in a file called info.txt with this content:
"ID","Site","Location","Block"
1,"L1",1,"a"
2,"L2",2,"b"
3,"L3",3,"c"
4,"L4",4,"d"

For this setup the following code will achieve what you want if my understanding is correct:
x <- list.files( pattern = ".csv" )
info <- read.table( file = "info.txt", sep = ",", header = TRUE,
                    row.names = FALSE, stringsAsFactors = FALSE )
y <- paste( info[ ,"Block" ], ".csv", sep = "" )
for( i in c( "Location", "Site" ) ) y <- paste( info[ ,i ], y, sep = "" )
file.rename( x, y )

list.files( pattern = ".csv" )
[1] "L11a.csv" "L22b.csv" "L33c.csv" "L44d.csv"

(Building on @joran's comments)

A: Here's another option:
info <- read.table( file = "info.txt", sep = ",", header = TRUE, row.names = NULL,
    stringsAsFactors = FALSE )

with(info, file.rename(paste0(ID, ".csv"), paste0(Site, Location, Block, ".csv")))


text:
Q: Why does my code for counting the knots of a tree work? I'm facing the classic "It works, but I don't know why!"-problem. I just applied a principle that I knew from another excercise with integers, but here I have to work with trees. The testing of the method was successfull. I am supposed to count the knots of a tree, and I do this bis traversing through it (in this case: inorder), and every time I traverse successfully (meaning: not facing an empty sub-tree), I count that as a knot. In this case, I'm wondering why this code doesn't count too much knots. For example, when I always go left and face an empty sub-tree, wouldn't I go up until I reach a knot where I can go right? Why does my code avoid this kind of problem?
public static int numberKnots (Tree b) {

  int count = 0;

  if (b.empty()) {
    return 0;
  }

  else {

  traverse.inorder(b.left());
  traverse.inorder(b.right());
  count = 1;
  }

  return count + numberKnots(b.left()) + numberKnots(b.right());

}

A: You do not really travel up and down the tree, you only travel down and visit each node once, and you do this by making your trees More and more simple.
Consider The following tree
  a
 / \
b   c
   / \
  d   e

So you start from the root and check if it is empty which it is not, so you return the result of 1 + numberKnots(left) + numberKnots(right). left and right are also trees and they are simpler than a
left  right
  b    c
      / \
     d   e

So now you check the b tree, which is empty so it just returns 0. Then you check the c tree, which is not empty so you return 1 + countKnots(left (of c)) + countKnots(right (of c)) and so on.
Each step of the calculation would be:
countKnots(a)
 = 1 + countKnots(b) + countKnots(c)
 = 1 + 0 + countKnots(c)
 = 1 + 0 + 1 + countKnots(d) + countKnots(e)
 = 1 + 0 + 1 + 0 + countKnots(e)
 = 1 + 0 + 1 + 0 + 0
 = 2

Your code could be simplified to
public static int numberKnots (Tree b) {
  if (b.empty()) {
    return 0;
  } else {
    return 1 + numberKnots(b.left()) + numberKnots(b.right());
  }
}

However, it does not seem to handle tree nodes which does not contain both left and right nodes, so the following tree would cause an error
a
 \
  c

A: Since you are using recursion,it does not transverse the same node twice.So your code works perfectly fine.consider (A) has two child nodes (B)&(C) further (B) has two childs (B1)&(B2).when transversing through recursion,it usses stack."(consider s to be our stack)". First the control reaches node(A) and since it has left child (A) is pushed into stack and control is trasferred to (B) now control is trasferred to (B)'s left child(B1) and (B) is pushed into stack, since (B1) does not have any childs it is counted and control is trasferred to top of stack i.e (B) and (B) is counted now control is trasffered to (B)'s right child it (B2)and (B2) is counted and control is trasferred to (B).Now (B) does not have any part of code left thus it is popped from stack and control is trasfered to (A) and (A) is counted and control is transfered to its right child (c).Similarly all nodes are counted without duplicating.
Hope it helps


text:
Q: php image crop by cordinates I have image info with all coordinates. I need to crop image exactly selected section.
I have created a c custom function in wordpress and pass all required fields. this code crop the image but not provided exactly output.
Here imageId is attachement id of image in wordpress
 <?php
      $ft_data = array(
                  "img_w" => 600,
                  "img_h" => 449.94375703037,
                  "w" => 120,
                  "h" => 80,
                  "s" => 100,
                  "x" => 42,
                  "y" => 0
                );

    $crop_coords => array(
                        "x" => 105,
                        "y" => 0,
                        "x2" => 405,
                        "y2" => 200,
                        "w" => 300,
                        "h" => 200
                    );
);

$imageId = 101;
       function imageCrop($ft_data , $crop_coords , $imageId){
       $json_string = stripslashes($ft_data);
        $data = json_decode($json_string, true);

        $x1     = $data['x'];
        $y1     = $data['y'];
        $width  = $data['w'];
        $height = $data['h'];

        $image_url = wp_get_attachment_url( $imageId );

        $info = pathinfo($image_url);

        // get the filename without the extension
        $image_name =  basename($image_url,'.'.$info['extension']);

        // get the extension without the image name
        $ext    = end(explode('.', $image_url));
        $im     = imagecreatefromfile($image_url);
        $size   = min(imagesx($im), imagesy($im));

        $to_crop_array = array('x' =>$x1 , 'y' => $y1, 'width' => $width, 'height'=> $height );

        $im2    = imagecrop($im, $to_crop_array );

        if ($im2 !== FALSE) {

          $NewImg = $image_name ."-new".date('d-m-y-H-i-s',time())."." . $ext;
          $upload_dir   = wp_upload_dir();

          $savePath = $upload_dir['path']."/".$NewImg;
          echo $newImgUrl = $upload_dir['url']."/".$NewImg;
            session_start();
          $_SESSION["cropedImage"] = $newImgUrl;
          // setcookie('cropedImage', $newImgUrl, time()+3600);
          // WC()->session->set( 'cropedImage', $newImgUrl);

          $res = imagepng($im2, $savePath );
          imagedestroy($im2);
          die;
        }
          imagedestroy($im);
       }

?>

I have image info with all coordinates. I need to crop image exactly selected section.
I have a custom function and pass all required fields. this code crop the image but not provided exactly output


text:
Q: ERROR : OverflowError: mktime argument out of range timestamp = []
for d, t in zip(data['Date'], data['Time']):
    try:
        ts = datetime.datetime.strptime(d+' '+t, '%m/%d/%Y %H:%M:%S')
        timestamp.append(time.mktime(ts.timetuple()))
    except ValueError:
        # print('ValueError')
        timestamp.append('ValueError')

ERROR :   OverflowError: mktime argument out of range
this is from code earthquake prediction using machine learning

A: I wanted to prove the issue is reproducible: I will add to this if I find a solution.
import time, datetime
d = '04/04/1000'
t = '12:40:00'
dj = d + ' ' + t
ts = datetime.datetime.strptime(dj, '%m/%d/%Y %H:%M:%S')
time.mktime(ts.timetuple())


text:
Q: Is it necessary to keep the products in the memory cache on the e-commerce site? If necessary, should the validation of the products to be entered (is there such a product before?) (the category of the product, the barcode of the product, the brand of the product etc.) should be done on the products kept in the memory cache or in the database?
For example, a product coming from the frontend and desired to be entered into the system must contain the correct brand ID, category ID and a unique barcode that is not in the system. Does this process need to be done in the database or in the memory cache?
CREATE PROCEDURE CheckInsertionProductModel @categoryID INT, @brandID INT, @modelCode NVARCHAR(16)
AS
BEGIN
        DECLARE @validateCategoryID INT; --Is there that categoryID in the system?
    SELECT @validateCategoryID = c.CategoryID
        FROM Categories AS c
        WHERE c.CategoryID = @categoryID AND c.IsDeleted = 0;
    IF (@validateCategoryID IS NOT NULL)
    BEGIN
        DECLARE @validateBrandID INT; --Is there that brandID in the system?
        SELECT @validateBrandID = b.BrandID
            FROM Brands AS b
            WHERE b.BrandID = @brandID AND b.IsDeleted = 0 AND b.IsConfirmed = 1;
        IF (@validateBrandID IS NOT NULL)
        BEGIN
            DECLARE @validateModelID INT;
            SELECT @validateModelID = pm.ModelID
                FROM ProductModels AS pm
                WHERE pm.ModelCode = @modelCode;
            IF (@validateModelID IS NULL)
            BEGIN
                            --SUCCESS
                ...
                --ELSE FAILED.
        ...
        --ELSE FAILED
...

Do dozens of features that need to be validated in this way need to be processed one by one in the database? Is it okay if we keep the category, brand and products in memory cache and validate it using the data in the cache and print it to the database? Note: this is an e-commerce site.


text:
Q: Eclipse templates I am using Eclipse Kepler on Ubuntu and was curious how to get templates defined in Preferences->PHP->Editor->Templates to show up on the top of the auto complete list. For example when I type "class" the template for the class is on the bottom of the auto complete drop down, how to I get it to show up on the top of the list?
Also there is a perspective view under Window->Show View->Other->General->Templates, I assume that this is supposed to be a list of templates available but when I show it, the tab contents are blank. Is there something that I have to set to get the list?
Thank you for the help!


text:
Q: Is there a way to measure features from a point cloud? Can MeshLab generate dimensionally-accurate circles, holes, features, etc from a point cloud? I'm considering using MeshLab for some metrology work, and I need to compare 3D scans to nominal 3D models/part dimensions to verify manufacturing processes.
Also, if this is possible, can we export these features/measurements for a report?

A: there!
After going through your proposal, I fully understood what your requirements are.
I'm going to explain my experience in extracting features from point cloud.
I got the point cloud of several mechanical parts such as spur gear, helical gear, aircraft propellers, and many other parts that have the specific design parameters such as diameter of circle...
I used FPP (fringe projection profilometry) to get the point cloud.
After getting the hole point cloud, I used LSODF (least squares orthogonal distance fitting) algorithm to extract the features from these point clouds.
In general, we know the model equation of the object that is represented by point coluds.
Say, you are going to extract the helical angle of the helical gear.
We got the point clouds of helical gear, so you already know the equation of helical gear represented in mathematically.
If we know the model equation and similar one and we have the measured point clouds of that objects, we can extract the features by using LSODF.
You can see that from this link.
https://www.researchgate.net/publication/221114214_Least_Squares_Orthogonal_Distance_Fitting_of_Implicit_Curves_and_Surfaces
Please share more information about your problems.