text:
Q: Fitting MultinomialNB on multiple columns of data Given a table of data containing 100 rows, such as:
Place    | Text             | Value | Text_Two
europe   | some random text | 3.2   | some more random text
america  | the usa          | 4.1   | the white house
...

I am trying to classify with the following:
df = pd.read_csv('data.csv')
mnb = MultinomialNB()
tf = TfidfVectorizer()

df.loc[df['Place'] == 'europe','Place'] = 0
df.loc[df['Place'] == 'america','Place'] = 1

X = df[['Text', 'Value', 'Text_Two']]
y = df['Place']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)
X_train_tf = tf.fit_transform(X_train)

mnb.fit(X_train_tf, y_train)

The above produces the following error:

ValueError: Found input variables with inconsistent numbers of
  samples: [3, 100]

So from what I understand it's only seeing the categories that were set with X = df[['Text', 'Value', 'Text_Two']], not the data within those categories.
The code above works if I only specify X for one category, such as:
    X = df['Text']
Is it possible to fit the MultinomialNB on multiple categories of data?

A: I rather combine columns Text and Text_Two as one column then construct the classifier from there. MultinomialNB works only for one classifier. Below is the code that combines columns Text and Text_Two into one.
You might be interested on multi-class or multi-label classification but it refers to the target variables (Y) rather than the dependent variables (X).
http://scikit-learn.org/stable/modules/multiclass.html. Hope it helps.
import pandas as pd
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split

df = pd.read_csv('data.csv', header=0, sep='|')
df.columns = [x.strip() for x in df.columns]

mnb = MultinomialNB()
tf = TfidfVectorizer()

#df.loc[df['Place'] == 'europe','Place'] = 0
#df.loc[df['Place'] == 'america','Place'] = 1
#X = df[['Text', 'Value', 'Text_Two']]
X = df.Text + df.Text_Two
y = df['Place']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)
pipe = make_pipeline(TfidfVectorizer(), MultinomialNB())
pipe.fit(X_train, y_train)
pipe.predict(X_test)

A: This has nothing to do with MultinomialNB. It can handle multiple columns fine. The problem is TfidfVectorizer.
TfidfVectorizer only works on a an iterable of single dimension (single column of your dataframe) and will not do any kind of check on the shape or type of the input data.
It will only do this:
for doc in raw_documents:
...
...

When you pass a dataframe to it (be it a single column or multiple columns), for doc in raw_documents:, on a dataframe will only output the column names and not actual data. The data you pass in X has three columns, so only those columns are used as documents, and hence the error
ValueError: Found input variables with inconsistent numbers of samples: [3, 100]
because your y will have 100 length, and your X (even though it has length 100, but due to tfidfvectorizer it will only now have 3 length).
So to solve this, you have two options:
1) You need to do individual tf-idf vectorization for each text column (Text, Text_Two) and then combine the resultant matrices to form the feature matrix to be used with MultinomialNB.
2) You can combine the two text columns into a single column as @âńōŋŷxmoůŜ has suggested and then do tf-idf on that single column.
Both options will result in different feature vectors, so you need to first understand what each one does and choose what you want.


text:
Q: Error when executing method of element of object array in for/in statement. p5.js I'm native Korean, so I'm sorry for my poor English.
I made p5.js snake-game, but 'Food' object is not working.
I debugged my code, so I wrote only the part where the problem occurred in the code.
var foodArray;
var scl = 20;

function setup(){
  createCanvas(300, 300);

  foodArray = [];

  foodArray.push(new Food());
  foodArray.push(new Food());
  foodArray.push(new Food());

  frameRate(10);
}

function draw() {
  background(0);

  for(var food in foodArray){
    food.show(); // <- ERROR!!
    alert("for executing"); // <- NOT Executed
  }

  foodArray[1].show(); // <- this line executed well.
}

function Food() {
  this.location = createVector(parseInt(random(30)), parseInt(random(30)));

  this.show = function(){
    fill(242,242,242);
    rect(this.location.x*scl, this.location.y*scl, scl, scl);
  }
}

I want to know how to use for/in statement in p5.js, Thank you.

A: You need to use for...of instead of for...in. The difference is that for...in iterates over the keys (indices) of the list, and for...of iterates over the values.
For example, consider the following code:
function setup() {
  let lis = ["a", "b", "c", "d", "e"];
  print("for...in");
  for (let k in lis) {
    print(k);
  }
  print("for...of");
  for (let k of lis) {
    print(k);
  }
}

The for...in version prints the indices of the list, while the for...of version prints the values (letters). So when the computer sees food.show(), the variable food is just a number. Since there is no method .show() for numbers, you get an error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use a templated client display() function that takes a set as the parameter I have to write a templated client function called DisplaySet() that gets as an argument a set, and displays the contents of the set. I am confused on how I can output the set, which is part of a class, in a client function.
Here is my code:
"set.h"
template<class ItemType>
class Set
{
 public:
  Set();
  Set(const ItemType &an_item);
  int GetCurrentSize() const;
  bool IsEmpty() const;
  bool Add(const ItemType& new_entry);
  bool Remove(const ItemType& an_entry);
  void Clear();
  bool Contains(const ItemType& an_ntry) const;
  vector<ItemType> ToVector() const;
  void TestSetImplementation() const;

 private:
  static const int kDefaultSetSize_ = 6;
  ItemType items_[kDefaultSetSize_];
  int item_count_;
  int max_items_;
  int GetIndexOf(const ItemType& target) const;
};
template<class ItemType>
void DisplaySet(const Set<ItemType> &a_set);

"set.cpp"
template<class ItemType>
void DisplaySet(const Set<ItemType> &a_set){
    int a_size = a_set.GetCurrentSize(); //gets size of the set
    cout <<"Size display "<< a_size << endl;
    for (int i = 0; i < a_size; i++) {
        cout << a_set[i] << endl; //i know this does not work because a_set is part of a class
    }
}

"main.cpp"
#include <iostream>
#include <vector>
#include <string>
#include "Set.h"

using namespace std;

int main()
{
   Set<int> b_set;

   b_set.Add(setArray[1]);
   b_set.Add(setArray[2]);
   b_set.Add(setArray[4]);
   b_set.Add(setArray[8]);
   DisplaySet(b_set);

   return 0;
}

I hope someone can explain how to use the function. Let me know if I need to post more of the code

A: Your Set class does not have an overloaded operator[], so calling a_set[i] is not going to work in your DisplaySet function.
Assuming that your ToVector function returns a vector of the items in the set, the DisplayFuntion can look like this:
#include <iterator>
#include <algorithm>
#include <iostream>
//...
template<class ItemType>
void DisplaySet(const Set<ItemType> &a_set)
{
    std::vector<ItemType> v = a_set.ToVector();
    std::copy(v.begin(), v.end(), std::ostream_iterator<ItemType>(cout, "\n"));
}

Again, this is assuming that ToVector does as stated.


text:
Q: How to perform range comparison for integer in java eg .x>aHow to perform range comparison for integer in java eg .x>a

eg . i want to check if my integer a falls between range x and y
a>30 and a<40
Thanks in advance

A: You are almost there. If you struggling to put the correct syntax, just convert that and to &&
  int a = 35; // for ex
    if(a>30 && a<40) {
      // yes do something please
    }

A: You said that! You must use the logical AND operator like this:
if(a > x && a > y)
{
    // do something;
}

Hope this helps ;)


text:
Q: Can I require confirmation on all destructive operations on a MySQL database? I have a local MySQL database I'm playing with manually. I can use the safe-updates / i-am-a-dummy options to disallow unqualified delete statements:
DELETE FROM table;

However, I can still easily lose everything with an accidental
TRUNCATE TABLE table;

as this latter statement is not prevented by safe-updates. Apart from backing up the database, what's the best way to prevent data loss here? Is there some way to require confirmation before all destructive actions, not just delete?


text:
Q: Hide urls when printing a page I have this webpage:

It looks like this when I try to print it:

It's missing the last item (user management) intentionally so that's not a problem.
But I'd like to hide the "(/campaigns)" and "(/profanity)" from the print.
Is that possible using CSS?
--EDIT--
This is the HTML:

Campaigns

                Campaigns active
                1/1

                Total posts
                149

Profanity

                Created profanity filters
                0

                Total words filtered
                0

User management

A: The @media tag supports print.
So if you want your blocks not to be displayed when in print, use the following code:
@media print {
.noprint {
    display: none !important;
} }

Just add "noprint" to any element you want.

A: add a class to your CSS called noprint for paper:
@media print {.noprint{display:none;}}

and then append that class to your code
eg:

 ...

A: I recognize the classes, this is a bootstrap issue, as you will find in bootstrap.css this rule
@media print {
  ...
  a[href]:after {
    content: " (" attr(href) ")";
  }
  ...
}

overwrite this rule and you should be golden, eg content:none;


text:
Q: Click on element is present not working : error (AttributeError: 'str' object has no attribute 'presence_of_element_located') I want to click on an element when is present but I have this error message:
AttributeError: 'str' object has no attribute presence_of_element_located'

This is my code in Pycharm:
try:
    element = WebDriverWait(self.driver, 120).until(EC.presence_of_element_located(By.XPATH, '/html/body/div[1]/section/md-content/div/div/div/div[2]/div/div/div/div/md-content/md-tabs/md-tabs-content-wrapper/md-tab-content[1]/div/section[1]/h2/button[1]'))
    element.click()
finally:
    self.driver.quit()

A: Check whether you import Expected Conditions as
from selenium.webdriver.support import expected_conditions as EC

and then didn't overwrite EC variable, e.g.
EC = "//div"

... or something


text:
Q: How to get the values of a dynamically created table?
The above screenshot shows the actual correct form. For getting this I tried the below code. My  contains a heading as well as a subpoint, which are added dynamically. On click of the Submit button, I want to read the heading & subpoint corresponding to that heading. The data format is given below.
I'm adding the rows dynamically with the header and the data respectively. I'm trying to gather the data in an object before sending the data to the server via AJAX. I'm not able to read the data in the given format.
HTML CODE

Scorecard Metrics

<button class="btnn btnn--pill add-point">Add Sub-Point</button>
<button class="btnn btnn--pill add-heading">Add Heading</button>

            Metrics
            Weightage
            Target
            Actions

            L1
            L2
            L3
            L4

                
                
                

                
                
                

<button class="btnn btnn--pill submit" id="Scoresubmit">Submit</button>

JAVASCRIPT CODE

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
    var actions = $("table td:last-child").html();
    var menubar = $("table td:nth-last-child(2)").html();

    $(".add-heading").click(function(){
        $(this).attr("disabled", "disabled");

        var index = $("table tbody tr:last-child").index();

        var row = '
' +
        'Heading<input id="heading_label_input" class="heading_label-box" type="text" class="form-control">	' +
        'Total Weightage<input class="Tweightage" id="wei'+(wei) + '" type="number" >	' +
        'Divide Weightage<input class="heading_checkbox" name="Dividecheckbox" id="heading_checkbox" type="checkbox">' +
        '' + actions + '	' +
        '
';

        $("table").append(row);
        $("table tbody tr").eq(index + 1).find(".add, .edit").toggle();
        $('[data-toggle="tooltip"]').tooltip();
        wei ++;
    });

    $(".add-point").click(function(){
        $(this).attr("disabled", "disabled");
        var index = $("table tbody tr:last-child").index();  //TO ADD ROW AS LAST Child
        var lastCheckBox = $('[name="Dividecheckbox"]:last').prop("checked");   //get status of last checkbox
        if(lastCheckBox==false){
        //Enable row
        var row = '
' +
        '<input class="subpoint_label-box" type="text" class="form-control"id="metrics'+(unique_id) + '">	' +
        '<input disabled class="subpoint_weightage2"  id="weightage'+(unique_id) + '" type="number" >	' +
        '<input class="slider_min-value" type="text" id="ex0n'+i+'" value="20">%<input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="ex'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text"  id="ex1n'+(i)+'" value="80">%	' +
        '<input class="slider_min-value" type="text" id="lx0n'+(i)+'" value="20">%<input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="lx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="lx1n'+(i)+'" value="80">%	' +
        '<input class="slider_min-value" type="text" id="zx0n'+(i)+'" value="20">%<input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="zx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="zx1n'+(i)+'" value="80">%	' +
        '<input class="slider_min-value" type="text" id="yx0n'+(i)+'" value="20">%<input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="yx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="yx1n'+(i)+'" value="80">%	' +
        '' + menubar + '	' +
        '
';
}

        else if(lastCheckBox==true){
            var row = '
' +
            '<input class="subpoint_label-box" type="text" class="form-control"id="metrics'+(unique_id) + '">	' +
            '<input class="subpoint_weightage"  id="weightage'+(unique_id) + '" type="number" >	' +
            '<input class="slider_min-value" type="text" id="ex0n'+i+'" value="20">%<input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="ex'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text"  id="ex1n'+(i)+'" value="80">%	' +
            '<input class="slider_min-value" type="text" id="lx0n'+(i)+'" value="20">%<input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="lx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="lx1n'+(i)+'" value="80">%	' +
            '<input class="slider_min-value" type="text" id="zx0n'+(i)+'" value="20">%<input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="zx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="zx1n'+(i)+'" value="80">%	' +
            '<input class="slider_min-value" type="text" id="yx0n'+(i)+'" value="20">%<input class="subpoint-sbody" style="width: 120px;" name="n'+i+'" id="yx'+(unique_id) + '" type="text" data-slider-min="0" data-slider-max="100" data-slider-value="[20,80]"/><input class="slider_max-value" type="text" id="yx1n'+(i)+'" value="80">%	' +
            '' + menubar + '	' +
            '
';
        }
        else{
            alert("Please Add Heading!!");
        }
$("table").append(row);
$("table tbody tr").eq(index + 1).find(".plus, .update").toggle();
$('[data-toggle="tooltip"]').tooltip();

$("#ex"+unique_id).slider({});
$("#ex"+unique_id).on("slide", function(slideEvt) {
    var nid=$(this).attr('name');
    $("#ex0"+nid).val(slideEvt.value[0]);
    $("#ex1"+nid).val(slideEvt.value[1]);
});

$("#lx"+unique_id).slider({});
$("#lx"+unique_id).on("slide", function(slideEvt) {
    var nid=$(this).attr('name');
    $("#lx0"+nid).val(slideEvt.value[0]);
    $("#lx1"+nid).val(slideEvt.value[1]);
});

$("#zx"+unique_id).slider({});
$("#zx"+unique_id).on("slide", function(slideEvt) {
    var nid=$(this).attr('name');
    $("#zx0"+nid).val(slideEvt.value[0]);
    $("#zx1"+nid).val(slideEvt.value[1]);
});

$("#yx"+unique_id).slider({});
$("#yx"+unique_id).on("slide", function(slideEvt) {
    var nid=$(this).attr('name');
    $("#yx0"+nid).val(slideEvt.value[0]);
    $("#yx1"+nid).val(slideEvt.value[1]);
});
unique_id++
i++
});

WHAT I TRIED TO GET THE DATA

$('#Scoresubmit').click(function () {
    GetCoScoreCard();
//ajax calll
});

function GetCoScoreCard() {

$('#scorecard_co .heading').each(function () { //tr

    var TotalWeightage;
    var item = $(this).closest("tr").find('td');
$.each(item, function (key, value) {        //Heading

    if (key == 0) {
        Heading1 = ($(value).text());
        this.Heading1 = Heading1;
    }
    else if (key == 1) {
        TotalWeightage = ($(value).text());
    }
    else if (key == 2) {
        lastCheckBox = $('[name="Dividecheckbox"]:last').prop("checked");
    }
});

var parametername, param_Weightage;
$('#scorecard_co  .Parameters').each(function () { //td  //parameters
    var item2 = $(this).closest("tr").find('td');
    $.each(item2, function (key, value) {
        datalist = ($(value).text());
        if (key == 0) {
            parametername = ($(value).text());
        }
        if (key == 1) {
            param_Weightage = ($(value).text());
        }

        if (key == 2 || key == 3 || key == 4 || key == 5)
        {
            var res = datalist.substring(1, 3);
            var res2 = datalist.substring(6, 8);
            var key1 = 'L' + i;
            MyLevels[key1] = res + "," + res2;
            i++;
        }
    });

    parameters = {
        "Name": parametername,
        "Weightage": param_Weightage,
"Levels": MyLevels,    //array
}

paramarray.push(parameters); //paramNewArray
MyLevels = {};
i = 0;
});

metrics={

    'Heading':Heading1,
'TotalWeitage': TotalWeightage,   //metrics heading and parameters
'DivideWeightage': lastCheckBox,
'parameters': paramarray          // paramNewArray
//work in process
}

var stringyfydata = JSON.stringify(metrics);
data1.push(stringyfydata); alert("Title=" + data1);
console.log(data1);
data = {};
parameters = {};
i = 0;
});
}

EXPECTED DATA OUTPUT
 [
{"Heading":"SchduleAdherence","TotalWeitage":"20","DivideWeightage":true,"parameters":{"Name":"Scrunity","Weightage":"30","Levels":{"L1":"20,80","L2":"20,80","L3":"20,80","L4":"20,80"}}]},
{"Heading":"Attendence","TotalWeitage":"30","DivideWeightage":true,"parameters":{"Name":"self","Weightage":"30","Levels":{"L1":"20,80","L2":"20,80","L3":"20,80","L4":"20,80"}}]}

]

There are two classes (.Heading = to read the heading, e.g. attendance & another is .Parameter = to read the sub-points), my issue is that every time I try to loop through the data, all the parameters are getting added repeatedly in my object.

A: you need to re initialize your variable in go score code;
function GetCoScoreCard() {
    paramArray = [];
    data1 = [];
    .....
    .....
 }


text:
Q: How can I detect USB serial port connections in C on Windows and macOS? Using libudev in Linux I am able to add a handle to an event manger to detect on boot and upon plugging in a USB serial device by monitoring tty events.
self->udev_monitor = udev_monitor_new_from_netlink(self->udev, "udev");
udev_monitor_filter_add_match_subsystem_devtype(self->udev_monitor, "tty", NULL);
udev_monitor_enable_receiving(self->udev_monitor);

self->event_manager->addFD(
    self->event_manager
    ,_udevDeviceAnnounce
    ,udev_monitor_get_fd(self->udev_monitor)
    ,self
);

_findUdevDevices(self);

How can I achieve the same thing on Windows and macOS? I am trying to make a single service written in C compiled for each Windows, Mac and Linux.


text:
Q: How many processes this code going to generate? I am not sure how many processes going to be created in this program? I suppose there is going to be created three child process in a while loop. Then, each child process is going to fork two times which means there are going to be two child process plus the one created by that child process is also going to fork and there is going to be 4 child process for each state. In total, there are 12 processes. Is that true?
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>

int main(){
 pid_t childpid;
 int i=0;
 while((childpid>0) && (i<3))
 {
      childpid=fork();
      i++;
 }
 if(childpid==0){
      fork();
      fork();
 }
 exit(0);
}

A: The total number of processes is 13
 while((childpid>0) && (i<3))

will only execute for the parent since the fork() system call returns the pid of the child to the parent process and a 0 to the child process.
Thus the while loop will generate 3 child processes with the childpid variable value 0, and the main parent process which now has the childpid variable value equal to that of the last forked child.
Total processes till now 4
For the condition
if(childpid==0){
      fork();
      fork();
 }

each child process from before spawns 1 child in the first fork call. The second fork will spawn another two new processes from the two proceeses of the first fork. So for each child process we will have spawned processes a total of 3 new processes.
Thus for th 3 child processes from the while loop, we will generate 9 new processes.
So total number of processes would be 4 + 9 = 13


text:
Q: Oracle Procedure to return average in a list of student grades I have two tables:
SUBJECT
STDID   SUBJID   SEMESTER_YEAR  GRADE    FREQ   STATUS
1111    2         2/2018          6       75    ok
1111    13        2/2018          7       100   ok
1111    4         1/2018          5       90    ok
1111    7         1/2018          10      95    ok
1111    9         2/2018          8       75    ok
1122    2         2/2017          3       75    no
1122    13        2/2017          5       100   ok
1122    4         1/2017          5       90    ok
1122    7         1/2017          10      95    ok
1122    9         2/2017          8       75    ok
1113    2         2/2018          6       75    ok
1113    13        2/2018          7       100   ok
1113    4         1/2018          5       90    ok
1113    7         1/2018          4       95    no
1113    9         2/2018          8       75    ok
1132    2         2/2018          3       75    no
1132    13        2/2018          7       100   ok
1132    4         1/2018          5       90    ok
1132    7         1/2018          4       95    no
1132    9         2/2018          8       75    ok

And the other: STUDENT
            STDID     NAME      DATA_NASC
            1111    gabriel     12-APR-70
            1112    pedro       12-JUN-70
            1113    lucas       12-MAR-70
            1114    mariana     12-FEB-70
            1115    klemer      12-SEP-70
            1116    jose        12-DEC-70
            1117    vitor       12-NOV-70
            1118    artur       12-APR-70
            1119    bia         12-NOV-70
            1120    julia       12-MAR-70
            1121    rafaela     12-JAN-70
            1122    augusto     12-FEB-70
            1123    eneas       12-JUL-70
            1124    zezinho     12-APR-70
            1125    hugo        12-APR-70
            1126    matheus     12-APR-70
            1127    diana       12-APR-70
            1128    andre       12-APR-70
            1129    reco        12-APR-70

I'm trying to create a procedure that, given a semester/year, for each subject (SUBJID) within that semester, output the student ID, student name and their respective grades, frequencies and status on those subjects. For each subject listed, I need to show also the general average of students grades on that subject
Already done this, but I'm stuck, hope someone can help me with the procedure and selection:
SELECT STUDENT.NAME
     , SUBJECT.STDID
     , SUBJECT.SUBJID
     , SUBJECT.SEMESTER_YEAR
     , AVG(SUBJECT.GRADE)
          OVER (PARTITION BY SUBJECT.SUBJID) AS AVERAGE_GRADE_BY_SUBJ
FROM SUBJECT, STUDENT
     WHERE SUBJECT.SEMESTER_YEAR = '1/2018'
     AND SUBJECT.STDID = STUDENT.STDID
ORDER BY SUBJECT.SUBJID;

EXAMPLE OF OUTPUT I NEED:
NAME             STDID        SUBJID    SEMESTER_YEAR   AVERAGE_GRADE_BY_SUBJ
gabriel          1111           4         1/2018               5
lucas            1113           4         1/2018               5
marcello         1132           4         1/2018               5
lucas            1113           7         1/2018               6,5
marcello         1132           7         1/2018               6,5
gabriel          1111           7         1/2018               6,5


text:
Q: Layers reference from Geoprocessing using ArcObjects? I am using ArcObjects (ArcGIS 10.1) in .NET with some geoprocessing. It works great. There is an option to add the resulting feature class to the map. That works great too. However how do I get a reference to this layer to move it to a group layer?
Dim GP As GeoProcessor = New GeoProcessor
GP.AddOutputsToMap = True 'True if we want to add outputs to map, False if we dont.

Dim parameters As IVariantArray = New VarArray
parameters.Add(inDatasets)
parameters.Add(toPointFullName)
parameters.Add("")

Dim res As IGeoProcessorResult = GP.Execute("Merge_management", parameters, Nothing)
'todo: how do I get a reference to ILayer of the resulting layer added to map?

A: The following in VBA shows how to create a layer object that you could then add to a group layer in the map.
Dim res As IGeoProcessorResult
If res.Status = esriJobSucceeded Then
    Dim pGPUtil As IGPUtilities4
    Set pGPUtil = New GPUtilities
    Dim pFL As IFeatureLayer
    Set pFL = pGPUtil.OpenFeatureLayerFromString(toPointFullName)
End If


text:
Q: Windows Form - Change Array Elements from Textbox Input C# Create a change password program that allows users to change their password by entering their email and security pin, but code works fine but it doesn't seem to make changes to the textfile array when I input a new password into the password textbox.
string filename = "./userinfo.csv";
using (var path = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var reader = new StreamReader(path))
{
    string line = reader.ReadLine();
    while ((line = reader.ReadLine()) != null)
    {
        string[] fields = line.Split(',');
        if (fields[1] == email && fields[3] == txtPin.Text)
        {
            fields[2] = txtNewPassword.Text;
            MessageBox.Show("Password Changed");
            break;
        }
        else
        {
            MessageBox.Show("Please enter an valid Username or Pin");
        }
    }
}

When I enter input into the textbox it would go to the textfile and change that specific array.


text:
Q: Is it possible query if a single RingCentral user has Automatic Call Recording (ACR) enabled? Are there any APIs that we can query if current extension is added into auto recording list?
We have a web phone using the stop/start recording Call Control API but it doesn't work when auto recording is enabled, so in our app, we need to disable the recording button. We need a way to identify if a user has ACR enabled without retrieving all the users.
We can get extension list with the following account-wide API, but it doesn't take any query parameters to filter the results. If we check this way, we need to load all extensions which takes too long.
https://developers.ringcentral.com/api-reference/Rule-Management/listCallRecordingExtensions
GET /restapi/v1.0/account/{accountId}/call-recording/extensions

A: Information on whether an individual user has Automatic Call Recording (ACR) enabled is available in the extension endpoint and is separately controlled for inbound and outbound calls.
GET /restapi/v1.0/account/{accountId}/extension/{extensionId}

The extension response includes a serviceFeatures features property which is an array of features. Filter this property for a feature matching the following:

*

*featureName IN (AutomaticInboundCallRecording, AutomaticOutboundCallRecording)

*enabled = true

Here's an example response showing only the serviceFeatures property value for those two features:
{
  "serviceFeatures": [
    {
      "featureName": "AutomaticInboundCallRecording",
      "enabled": true
    },
    {
      "featureName": "AutomaticOutboundCallRecording",
      "enabled": false,
      "reason": "ExtensionLimitation"
    }
  ]
}

See more here:
https://developers.ringcentral.com/api-reference/User-Settings/readExtension


text:
Q: How to read font size of each word in a word document using POI? I am trying to find out whether there exist anything in the word document that has a font of 2. However, I have not been able to do this. To begin with, I've tried to read the font of each word in a sample word document that only has one line and 7 words. I am not getting the correct results.
Here is my code:
HWPFDocument doc = new HWPFDocument (fileStream);
WordExtractor we = new WordExtractor(doc);
Range range = doc.getRange()
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
  Paragraph pr = range.getParagraph(i);
  int k = 0
  while (true) {
     CharacterRun run = pr.getCharacterRun(k++);
     System.out.println("Color: " + run.getColor());
     System.out.println("Font: " + run.getFontName());
     System.out.println("Font Size: " + run.getFontSize());
     if (run.getEndOffSet() == pr.getEndOffSet())
       break;
  }
}

However, the above code always doubles the font size. i.e. if the actual font size in the document is 12 then it outputs 24 and if actual font is 8 then it outputs 16.
Is this the correct way to read font size from a word document ??

A: Yes, that's the correct way; the measurement is in half points.
In a docx, you'd have something like:
<w:rPr>

  <w:sz w:val="28" />

</w:rPr>

ECMA 376 spec on @sz defines the unit as ST_HpsMeasure (Measurement in Half-Points)
Its the same with the binary doc format, which HWPF supports. If you look at [MS-DOC], you'll see it also specifies the size of text in half-points.


text:
Q: What is the underlying type of a c++ enum? This may have been answered elsewhere but I could not find a suitable response.
I have this code:
enum enumWizardPage
{
    WP_NONE = 0x00,
    WP_CMDID = 0x01,
    WP_LEAGUES = 0x02,
    WP_TEAMS = 0x04,
    WP_COMP = 0x08,
    WP_DIVISIONS = 0x10,
    WP_FORMULAS = 0x20,
    WP_FINISHED = 0x40,
};

Which is legacy and I have to modify it by adding a few new values.
The issue is each value must be a unique bit so they may be OR combined to a bitmap.
The values are set using the #x## hex format, but I'm wondering if this is the max it can store?
What will be the effect, if any, if I change my code to
enum enumWizardPage
{
    WP_NONE = 0x0000,
    WP_CMDID = 0x0001,
    WP_LEAGUES = 0x0002,
    WP_TEAMS = 0x0004,
    WP_COMP = 0x0008,
    WP_DIVISIONS = 0x0010,
    WP_FORMULAS = 0x0020,
    WP_FINISHED = 0x0040,
};

A: The type of a C++ enum is the enum itself. Its range is rather arbitrary, but in practical terms, its underlying type is an int.
It is implicitly cast to int wherever it's used, though.
C++11 changes
This has changed since C++11, which introduced typed enums. An untyped enum now is defined as being at least the width of int (and wider if larger values are needed). However, given a typed enum defined as follows:
enum name : type {};

An enumeration of type name has an underlying type of type. For example, enum : char defines an enum the same width as char instead of int.
Further, an enum can be explicitly scoped as follows:
enum class name : type {
    value = 0,
    // ...
};

(Where name is required, but type is optional.) An enum declared this way will no longer implicitly cast to its underlying type (requiring a static_cast<>) and values must be referenced with a fully-qualified name. In this example, to assign value to a enum variable, you must refer to it as name::value.

A: From N4659 C++ 7.2/5:

For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. If no integral type can represent all the enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0.

A: IIRC its represented as int in memory. But gcc has switch -fshort-enum to make it a shortest integer type that fits all the values, if you need to save space. Other compilers will have something similar.


text:
Q: color change on data in dataset i have been working on a project which do contain categories and item,what i want is i want to change the forecolor of the item so that other person can easily identify the item,other than this i have applied italics to the text it is working very well but how can i apply forecolor and font size .....so i need a help...
    for (int iRow = 0; iRow < dsDetails.Tables[0].Rows.Count; iRow++)
    {
        DataRow[] drCatFilter;
        // Get the dish item name for the current mapping
        drCatFilter = dsCommon.Tables[0].Select("ID = '" + dsDetails.Tables[0].Rows[iRow]["catmappingid"].ToString() + "'");
        // Create the dish item
        item = new MenuItem();
        item.Value = dsDetails.Tables[0].Rows[iRow]["id"].ToString();
        item.Text = (""+dsDetails.Tables[0].Rows[iRow]["name"].ToString()+"";

        ![As the image shows category(food,beverages etc.) and items(Dosa,beer etc) i need to change the forecolor of itemms][1]

    [1]: http://i.stack.imgur.com/3ljsp.png

A: Did you try to set the "Foreground" and "FontSize" property of your MenuItem?
    item = new MenuItem();
    item.Value = dsDetails.Tables[0].Rows[iRow]["id"].ToString();
    item.Text = (""+dsDetails.Tables[0].Rows[iRow]["name"].ToString()+"";
    item.Foreground = "something"
    item.Fontsize = "something"

Or am I understanding your problem wrong?


text:
Q: What is the probability that two people orginally seated at the two ends are no longer at the ends after sit down again?
$7$ people are seated in a row . They all get up and sit down in random order.What is the probability that two people orginally seated at the two ends are no longer at the ends after sit down again ?

There are $7!$ arrangements for new siting without restriction. Moreover, for the numerator , $7!$ - the people  who were orginally in the ends are in the ends again. Then , $7! - 2!\times 5! =4800$
So ,answer is $4800/5040$
Am i correct ?

A: That is not correct. While $ 7! - 2 \cdot 5! \ $ excludes seating arrangements where both of them are seated at two ends but it includes arrangements where one of them is seated at one of the ends.
So the correct probability will be,
$ \displaystyle \cfrac{5 \cdot4 \cdot 5!}{7!} = \cfrac{10}{21}$
We seat those two specific persons in two of the five seats and then arrange rest five persons in remaining seats in $5!$ ways.

A: You can use probability directly to get a simpler solution.
$Pr = \dfrac57\cdot\dfrac46 = \dfrac{10}{21}$


text:
Q: Checking the String whether it is the Number(Double) of Question. It is necessary to make check the String whether it is the Number(Double)?
Exemple:
var s1:String = "df1231"
var s2:String = "1231,3123"
If s1.isDouble {
  Println("True.This Number!")
} else {
  Println("False.This not Number!") //Will give it
}
If s2.isDouble {
  Println("True.This Number!") //Will give it
} else {
  Println("False.This not Number!")
}

A: Not sure what your needs are exactly, but the most straightforward way to do it could be:
func isDouble(text:String) -> Bool {
    guard let _ = Double(text.stringByReplacingOccurrencesOfString(",", withString: ".")) else { return false }
    return true
}

isDouble("df1231") // returns false
isDouble("1231,3123") // returns true

You can copy paste it to Playground to see it work.


text:
Q: Getting maximum string length exeeded error when inserting a CLOB in HANA (longer than 7FFFFF) We are trying to insert a large string into a table column and getting an error "length can't exceed maximum length(8388607 bytes)". (0x7F FFFF). The input data field length exceeds 10MB.
HANA version SPS 9 (Rev 97)
Data type of variable and table column is CLOB
Using INSERT in a SQLSCRIPT Stored Procedure

The HANA data types documentation say that maximum length of any LOB object is 2GB (0x7FFF FFFF). Our string length is well within this limit. So this is very confounding. Will appreciate any hints to resolve this.
Thanks a lot.
---------- CODE
CREATE PROCEDURE XXX_SCHEMA.PROC_INSERT_INTO_CLOB
    ( IN DATA_CLOB CLOB,  )
    BEGIN
 LANGUAGE SQLSCRIPT SQL SECURITY INVOKER default schema XXX_SCHEMA AS
        INSERT INTO "XXX_SCHEMA"."XXX::DB_YY_CLOB"
            (
                'ABC'   ,
                CURRENT_TIMESTAMP ,
                DATA_CLOB
           )
            SELECT F1,
                  F2,
                  :DATA_CLOB
            FROM DUMMY ;
    END;

-- Table Defintion
table.schemaName =  "XXX_SCHEMA";
table.tableType = ROWSTORE;
table.columns = [
{name = "F1";sqlType = NVARCHAR;nullable = false; length = 3;},
{name = "F2";sqlType = TIMESTAMP;nullable = true;},
{name = "DATA_CLOB";sqlType = CLOB;nullable = true;}];

A: The reason for the error is that you seem to use string methods to deal with the CLOB data.
When I tried simple things like inserting a really long value generated via
update rclob set data_clob = lpad ('X', 2000000000, 'Y');

I also received the error message
Could not execute 'update rclob set data_clob = lpad ('X', 2000000000, 'Y')'
SAP DBTech JDBC: [384]: string is too long: length can't exceed maximum length(8388607bytes) at function lpad() (at pos 29)

Since LPAD produces a string before it gets entered into the CLOB, the error message is thrown before the CLOB column is actually touched.
Generally LOB columns can only be inserted by binding the data to a parameter in the insert statement.


text:
Q: How to animate RecyclerView items when they appear How can I animate the RecyclerView Items when there are appearing?
The default item animator only animates when a data is added or removed after the recycler data has been set.
How can this be achieved?

A: I animated fading in of Recyclerview items when they first appear as shown in the code below. Perhaps this will be of use to someone.
private final static int FADE_DURATION = 1000; //FADE_DURATION in milliseconds

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    holder.getTextView().setText("some text");

    // Set the view to fade in
    setFadeAnimation(holder.itemView);
}

private void setFadeAnimation(View view) {
    AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
    anim.setDuration(FADE_DURATION);
    view.startAnimation(anim);
}

You can also replace setFadeAnimation() with the following setScaleAnimation() to animate appearance of items by scaling them from a point:
private void setScaleAnimation(View view) {
    ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    anim.setDuration(FADE_DURATION);
    view.startAnimation(anim);
}

The code above has some warts in so far as when you scroll the RecyclerView items always fade or scale. If you wish you can add code to just allow the animation to happen when the fragment or activity containing the RecyclerView is first created (e.g. get the system time on creation and only allow animation for the first FADE_DURATION milliseconds).

A: Animating items in the recyclerview when they are binded in the adapter might not be the best idea as that can cause the items in the recyclerview to animate at different speeds. In my case, the item at the end of the recyclerview animate to their position quicker then the ones at the top as the ones at the top have further to travel so it made it look untidy.
The original code that I used to animate each item into the recyclerview can be found here:
http://frogermcs.github.io/Instagram-with-Material-Design-concept-is-getting-real/
But I will copy and paste the code in case the link breaks.
STEP 1: Set this inside your onCreate method so that you ensure the animation only run once:
if (savedInstanceState == null) {
    pendingIntroAnimation = true;
}

STEP 2: You will need to put this code into the method where you want to start the animation:
if (pendingIntroAnimation) {
    pendingIntroAnimation = false;
    startIntroAnimation();
}

In the link, the writer is animating the toolbar icons, so he put it inside this method:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    inboxMenuItem = menu.findItem(R.id.action_inbox);
    inboxMenuItem.setActionView(R.layout.menu_item_view);
    if (pendingIntroAnimation) {
        pendingIntroAnimation = false;
        startIntroAnimation();
    }
    return true;
}

STEP 3: Now write the logic for the startIntroAnimation():
private static final int ANIM_DURATION_TOOLBAR = 300;

private void startIntroAnimation() {
    btnCreate.setTranslationY(2 * getResources().getDimensionPixelOffset(R.dimen.btn_fab_size));

    int actionbarSize = Utils.dpToPx(56);
    toolbar.setTranslationY(-actionbarSize);
    ivLogo.setTranslationY(-actionbarSize);
    inboxMenuItem.getActionView().setTranslationY(-actionbarSize);

    toolbar.animate()
            .translationY(0)
            .setDuration(ANIM_DURATION_TOOLBAR)
            .setStartDelay(300);
    ivLogo.animate()
            .translationY(0)
            .setDuration(ANIM_DURATION_TOOLBAR)
            .setStartDelay(400);
    inboxMenuItem.getActionView().animate()
            .translationY(0)
            .setDuration(ANIM_DURATION_TOOLBAR)
            .setStartDelay(500)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    startContentAnimation();
                }
            })
            .start();
}

My preferred alternative:
I would rather animate the whole recyclerview instead of the items inside the recyclerview.
STEP 1 and 2 remains the same.
In STEP 3, as soon as your API call returns with your data, I would start the animation.
private void startIntroAnimation() {
    recyclerview.setTranslationY(latestPostRecyclerview.getHeight());
    recyclerview.setAlpha(0f);
    recyclerview.animate()
            .translationY(0)
            .setDuration(400)
            .alpha(1f)
            .setInterpolator(new AccelerateDecelerateInterpolator())
            .start();
}

This would animate your entire recyclerview so that it flys in from the bottom of the screen.

A: Create this method into your recyclerview Adapter
private void setZoomInAnimation(View view) {
        Animation zoomIn = AnimationUtils.loadAnimation(context, R.anim.zoomin);// animation file
        view.startAnimation(zoomIn);
    }

And finally add this line of code in onBindViewHolder
setZoomInAnimation(holder.itemView);

A: In 2019,
I would suggest putting all the item animations into the ItemAnimator.
Let's start with declaring the animator in the recycler-view:
with(view.recycler_view) {
adapter = Adapter()
itemAnimator = CustomAnimator()
}

Declare the custom animator then,
class CustomAnimator() : DefaultItemAnimator() {

     override fun animateAppearance(
       holder: RecyclerView.ViewHolder,
       preInfo: ItemHolderInfo?,
       postInfo: ItemHolderInfo): Boolean{} // declare  what happens when a item appears on the recycler view

     override fun animatePersistence(
       holder: RecyclerView.ViewHolder,
       preInfo: ItemHolderInfo,
       postInfo: ItemHolderInfo): Boolean {} // declare animation for items that persist in a recycler view even when the items change

}

Similar to the ones above there is one for disappearance animateDisappearance, for add animateAdd, for change animateChange and move animateMove.
One important point would be to call the correct animation-dispatchers inside them.

A: EDIT :
According to the ItemAnimator documentation :

This class defines the animations that take place on items as changes are made to the adapter.

So unless you add your items one by one to your RecyclerView and refresh the view at each iteration, I don't think ItemAnimator is the solution to your need.
Here is how you can animate the RecyclerView items when they appear using a CustomAdapter :
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder>
{
    private Context context;

    // The items to display in your RecyclerView
    private ArrayList<String> items;
    // Allows to remember the last item shown on screen
    private int lastPosition = -1;

    public static class ViewHolder extends RecyclerView.ViewHolder
    {
        TextView text;
        // You need to retrieve the container (ie the root ViewGroup from your custom_item_layout)
        // It's the view that will be animated
        FrameLayout container;

        public ViewHolder(View itemView)
        {
            super(itemView);
            container = (FrameLayout) itemView.findViewById(R.id.item_layout_container);
            text = (TextView) itemView.findViewById(R.id.item_layout_text);
        }
    }

    public CustomAdapter(ArrayList<String> items, Context context)
    {
        this.items = items;
        this.context = context;
    }

    @Override
    public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_item_layout, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position)
    {
        holder.text.setText(items.get(position));

        // Here you apply the animation when the view is bound
        setAnimation(holder.itemView, position);
    }

    /**
     * Here is the key method to apply the animation
     */
    private void setAnimation(View viewToAnimate, int position)
    {
        // If the bound view wasn't previously displayed on screen, it's animated
        if (position > lastPosition)
        {
            Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
        }
    }
}

And your custom_item_layout would look like this :
<FrameLayout
    android:id="@+id/item_layout_container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/item_layout_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:gravity="center_vertical"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"/>

</FrameLayout>

For more information about CustomAdapters and RecyclerView, refer to this training on the official documentation.
Problems on fast scroll
Using this method could cause problems with fast scrolling. The view could be reused while the animation is been happening. In order to avoid that is recommendable to clear the animation when is detached.
    @Override
    public void onViewDetachedFromWindow(final RecyclerView.ViewHolder holder)
    {
        ((CustomViewHolder)holder).clearAnimation();
    }

On CustomViewHolder:
    public void clearAnimation()
    {
        mRootLayout.clearAnimation();
    }

Old answer :
Give a look at Gabriele Mariotti's repo, I'm pretty sure you'll find what you need. He provides simple ItemAnimators for the RecyclerView, such as SlideInItemAnimator or SlideScaleItemAnimator.

A: I created animation from pbm's answer with little modification to make the aninmation run only once
in the other word the Animation appear with you scroll down only
private int lastPosition = -1;

private void setAnimation(View viewToAnimate, int position) {
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition) {
        ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        anim.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
        viewToAnimate.startAnimation(anim);
        lastPosition = position;
    }
}

and in onBindViewHolder call the function
@Override
public void onBindViewHolder(ViewHolder holder, int position) {

holder.getTextView().setText("some text");

// call Animation function
setAnimation(holder.itemView, position);
}

A: You can add a android:layoutAnimation="@anim/rv_item_animation" attribute to RecyclerView like this:
<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layoutAnimation="@anim/layout_animation_fall_down"
    />

thanks for the excellent article here:
https://proandroiddev.com/enter-animation-using-recyclerview-and-layoutanimation-part-1-list-75a874a5d213

A: Made Simple with XML only
Visit Gist Link
res/anim/layout_animation.xml
<?xml version="1.0" encoding="utf-8"?>
    <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:animation="@anim/item_animation_fall_down"
        android:animationOrder="normal"
        android:delay="15%" />

res/anim/item_animation_fall_down.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500">

    <translate
        android:fromYDelta="-20%"
        android:toYDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

    <scale
        android:fromXScale="105%"
        android:fromYScale="105%"
        android:toXScale="100%"
        android:toYScale="100%"
        android:pivotX="50%"
        android:pivotY="50%"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

</set>

Use in layouts and recylcerview like:
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layoutAnimation="@anim/layout_animation"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

A: A good place to start is this:
https://github.com/wasabeef/recyclerview-animators/blob/master/animators/src/main/java/jp/wasabeef/recyclerview/adapters/AnimationAdapter.java
You don't even need the full library, that class is enough.
Then if you just implement your Adapter class giving an animator like this:
@Override
protected Animator[] getAnimators(View view) {
    return new Animator[]{
            ObjectAnimator.ofFloat(view, "translationY", view.getMeasuredHeight(), 0)
    };
}

@Override
public long getItemId(final int position) {
    return getWrappedAdapter().getItemId(position);
}

you'll see items appearing from the bottom as they scroll, also avoiding the problem with the fast scroll.

A: Just extends your Adapter like below
public class RankingAdapter extends AnimatedRecyclerView<RankingAdapter.ViewHolder>

And add super method to onBindViewHolder
@Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        super.onBindViewHolder(holder, position);

It's automate way to create animated adapter like "Basheer AL-MOMANI"
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;

import java.util.Random;

/**
 * Created by eliaszkubala on 24.02.2017.
 */
public class AnimatedRecyclerView<T extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<T> {

    @Override
    public T onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(T holder, int position) {
        setAnimation(holder.itemView, position);
    }

    @Override
    public int getItemCount() {
        return 0;
    }

    protected int mLastPosition = -1;

    protected void setAnimation(View viewToAnimate, int position) {
        if (position > mLastPosition) {
            ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
            viewToAnimate.startAnimation(anim);
            mLastPosition = position;
        }
    }

}

A: I think, is better to use it like this: (in RecyclerView adapter override just a one method)
override fun onViewAttachedToWindow(holder: ViewHolder) {
    super.onViewAttachedToWindow(holder)

    setBindAnimation(holder)
}

If You want every attach animation there in RV.


text:
Q: Extract submatrix at certain row/col values I need to slice a 2D input array from row/col indices and a slicing distance. In my example below, I can extract a 3x3 submatrix from an input matrix, but I cannot adapt this code to work for any search distance I would like, without resorting to manually writing down the indices:
Example:
import numpy as np

# create matrix
mat_A = np.arange(100).reshape((10, 10))

row = 5
col = 5

# Build 3x3 matrix around the centre point
matrix_three = ((row - 1, col - 1),
                (row, col - 1),
                (row + 1, col - 1),
                (row - 1, col),
                (row, col),  # centre point
                (row + 1, col),
                (row - 1, col + 1),
                (row, col + 1),
                (row + 1, col + 1))

list_matrix_max_values = []

for loc in matrix_three:
    val = mat_A[loc[0]][loc[1]]
    list_matrix_max_values.append(val)

submatrix = np.matrix(list_matrix_max_values)
print(submatrix)

Returns:
[[44 54 64 45 55 65 46 56 66]]

How can I do the same thing if i would like for example to extract a 5x5 matrix around the cell defined by my row/col indices?
Thanks in advance!

A: Numpy has matrix slicing, so you can slice on both rows and columns.
mat_A[4:7, 4:7]

returns
  [[44, 45, 46],
   [54, 55, 56],
   [64, 65, 66]]

A: S=3 # window "radius"; S=3 gives a 5x5 submatrix
mat_A[row-S+1:row+S,col-S+1:col+S]
#array([[33, 34, 35, 36, 37],
#       [43, 44, 45, 46, 47],
#       [53, 54, 55, 56, 57],
#       [63, 64, 65, 66, 67],
#       [73, 74, 75, 76, 77]])


text:
Q: Detecting When A Scatterview item is inertial The ManipluationDelta event has the IsInertial property.
Unfortunately it appears that a scatterview item 'ManipulationDelta' event does not fire. Only its ContainerManipulationDelta event fires, but the ContainerManipulationEventArgs does not expose the IsInertial property.
So is there any other way to determine when a scatterview item is being manipulated via inertia?

A: look at ScatterViewItem.AreAnyTouchesCaptured.   if that's false, then the item is being moved by inertia rather than by active touch inputs


text:
Q: Subtract 30 minutes from total hours I currently have a column TotalHours that contain a computed column specification with the following
(isnull(datediff(minute,[RegIn],[RegOut]),(0))/(60.0))

This gives me the total hours between 2 columns regin, and regout.
Now.  I am trying to subtract 30 minutes from the total hours when the computed hours is above 6.5 hours.
I tried doing it with case statement.  but got lost.
Appreciate any help or pointers
Thanks.

A: Here is one way:
coalesce((datediff(minute,[RegIn],[RegOut])/60.0 -
          (case when datediff(minute,[RegIn],[RegOut]) > 6.5*60 then 0.5 else 0 end),
         0)

A: Since you've got a complicated expression for the value, you'll have to use that expression multiple times.  One way to think it through is replace the complicated expression with a placeholder, like TotalHours, then put the expression back once you figure out the logic.
TotalHours -
    Case When TotalHours > 6.5 Then 0.5 Else 0 End

This says the total hours should be reduced by a value of 0.5 (30 minutes) when the total hours is larger than 6.5 hours.  Writing it the way above reduces the repitions of TotalHours. Now plug the original complex expression back in:
(isnull(datediff(minute,[RegIn],[RegOut]),(0))/(60.0)) -
    Case When (isnull(datediff(minute,[RegIn],[RegOut]),(0))/(60.0)) > 6.5
        Then 0.5 Else 0 End


text:
Q: Problems with creating a y axis in d3 I'm having some significant difficulties getting my y axis to appear on my graph.  You'll have to forgive me because I'm a relative beginner at this, and my code is probably not up to par with some standards.  Hopefully some of you are up to the challenge of helping me out with this.   I've gotten the x axis to work out just fine with my xscale, and when I append it I see it at the bottom.  The y axis is not working though, and I can't for the life of me figure out how to get my y axis to appear.  What am I doing wrong? My xScale and yScale are the two first scales, and I try to append the axes at the bottom.  Thanks in advance for any help with this.
<!DOCTYPE html>
<html>
<head>
    <title> Digital Humanities Latin Graph</title>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
<div id="graph">
</div>

<script type="text/javascript">

        var romandataset= [ {"year": 1800, "freq": 10.45 },
                    {"year": 1850, "freq": 9.49 },
                    {"year": 1900, "freq": 7.16 },
                    {"year": 1950, "freq": 6.28 },
                    {"year": 2000, "freq": 5.25 },
                    {"year": 2008, "freq": 5.18 } ];

        var greekdataset= [     {"year": 1800, "freq": 9.1 },
                    {"year": 1850, "freq": 7.86 },
                    {"year": 1900, "freq": 7.07 },
                    {"year": 1950, "freq": 8.00 },
                    {"year": 2000, "freq": 8.43 },
                    {"year": 2008, "freq": 8.49} ];

        var padding = 200
        var w = 1100
        var h = 800

        var xScale = d3.scale.linear()
                .domain([1800, 2010])
                .range([padding, w - padding])

        var yScale = d3.scale.linear()
                .domain([5.00, 11.00])
                .range([h - padding, padding])

        var romancolorscale = d3.scale.linear()
                .domain([3.00, 11])
                .range(["white", "blue"])

        var radiusscale = d3.scale.linear()
                .domain([5.18, 10.45])
                .range([10, 20])

        var greekcolorscale = d3.scale.linear()
                .domain([3.00, 12.00])
                .range(["white", "green"])

        var xAxis = d3.svg.axis()
                .scale(xScale)
                .ticks(6);

        var yAxis = d3.svg.axis()
                .scale(yScale)
                .orient("left")
                .ticks(5);

            var svg = d3.select("body")
            .append("svg")
            .attr("width", w)
            .attr("height", h);

            svg.selectAll("circle")
             .data(romandataset)
             .enter()
                     .append("circle")
                 .attr("cx", function (d) {return xScale(d.year) })
                     .attr("cy", function (d) {return yScale(d.freq) })
                     .attr("r", function (d) {return radiusscale(d.freq) })
                     .style("stroke", "gray")
             .style("fill", function (d) { return romancolorscale(d.freq)});

            svg.selectAll("rect")
                .data(greekdataset)
            .enter()
            .append("circle")

            .attr("cx", function (d) {return xScale(d.year) })
                    .attr("cy", function (d) {return yScale(d.freq) })
                    .attr("r", function (d) {return radiusscale(d.freq) })
                    .style("stroke", "gray")
            .style("fill", function (d) { return greekcolorscale(d.freq)});

            svg.append("g")
            .attr("transform", "translate(0," + (h - padding) + ")")
            .call(xAxis)
            .orient[("bottom")];

            svg.append("g")
                .attr("class", "axis")
             .attr("transform", "translate(" + padding + ",0)")
                 .call(yAxis);

    </script>
    </body>
    </html>

A: You're trying to orient the appended g element for the x axis, which gives an error and the following code (which would draw the y axis) isn't executed.
Simply remove the last line from
svg.append("g")
        .attr("transform", "translate(0," + (h - padding) + ")")
        .call(xAxis)
        .orient[("bottom")];

and put it where the axis is defined:
var xAxis = d3.svg.axis()
            .scale(xScale)
            .orient("bottom")
            .ticks(6);

(You also don't need the square brackets around it.)
Working code (that needs more work) here.


text:
Q: Rails app with Airbrake - 401 unauthroized I am successfully using airbrake in my ruby on rails app with one exception.
On visiting a specific view, I am occasionally getting a 401 unauthorized error:
POST https://api.airbrake.io/api/v3/projects/0/notices?key= 401 (Unauthorized)
api.airbrake.io/api/v3/projects/0/notices?key=:1
The key appears to be missing however it is only missing sometimes..
I am setting my airbrake credentials in my app.js file as follows:
// Airbrake project creds
// projectId, projectKey
Airbrake.setProject(projID, projKey);

window.onerror = function(message, file, line) {
  Airbrake.push({error: {message: message, fileName: file, lineNumber: line}});
}

Why might this fail sometimes but work other times on one specific view?

A: You see that error because Airbrake.setProject is not called in time or projID, projKey are undefined. But I can't say why without seeing full app.js contents and knowing how you load that file.
BTW you can find more robust onerror handler here.
Also I recommend you to open GitHub issue when you have airbrake-js specific questions.


text:
Q: Recommendations for Java + OpenPGP? I want to develop a small OpenPGP client and I'm searching for a Java library for OpenPGP.
Are there any (open source) recommendations for this approach?
Cryptix.org does not seem alive anymore...

A: I found the BouncyCastle library, for Java and C#. I haven't any experiences with it. I will try it and report here.
It provides:

*

*A lightweight cryptography API for Java and C#.

*A provider for the Java Cryptography Extension and the Java Cryptography Architecture.

*A clean room implementation of the JCE 1.2.1.

*A library for reading and writing encoded ASN.1 objects.

*A light weight client-side TLS API.

*Generators for Version 1 and Version 3 X.509 certificates, Version 2 CRLs, and PKCS12 files.

*Generators for Version 2 X.509 attribute certificates.

*Generators/Processors for S/MIME and CMS (PKCS7/RFC 3852).

*Generators/Processors for OCSP (RFC 2560).

*Generators/Processors for TSP (RFC 3161).

*Generators/Processors for OpenPGP (RFC 4880).

*A signed jar version suitable for JDK 1.4-1.6 and the Sun JCE.

(from BouncyCastle.org)

A: There is a commercial library on top of BouncyCastle: http://www.didisoft.com/ which greatly simplifies the BouncyCastle API.
I have not tried it just found it mentioned on jGuru.
I think it's safe to go with BouncyCastle alone. Their library is under development and they provider openpgp examples...

A: Just for completeness: our SecureBlackbox (Java edition) includes OpenPGP components for Java and Android, much richer than in BouncyCastle, and with support, samples and documentation.

A: There's PGPJava, but it's pretty old.

A: You might want to try PGPainless which is also based on Bouncycastle, and scores pretty good on the OpenPGP Interoperability Test Suite.


text:
Q: Nautilus now has small icon and only one window I run Ubuntu 10.10. At first, icons in Nautilus got smaller and zoom didn't work. Then when I started again it opens in only one window and lost his selections in "View". To show what I mean here is the screen shot:

Last time I installed PHP-GTK and all sorts of libraries that is needed for that and was working fine, but the next time I turn on computer I got this nautilus behaviour  and bluetooth icon in panel which I removed long time ago.
When I do sudo nautilus it opens fine except icons which are still smaller than before. It opens with this message:
Initializing nautilus-image-converter extension
Initializing nautilus-gdu extension

** (nautilus:8100): WARNING **: Failed to get the current CK session: GDBus.Error:org.freedesktop.ConsoleKit.Manager.GeneralError: Unable to lookup session information for process '8100'

(nautilus:8100): GConf-CRITICAL **: gconf_value_free: assertion `value != NULL' failed
Nautilus-Share-Message: Called "net usershare info" but it failed: 'net usershare' returned error 255: net usershare: cannot open usershare directory /var/lib/samba/usershares. Error No such file or directory
Please ask your system administrator to enable user sharing.

(nautilus:8100): GConf-CRITICAL **: gconf_value_free: assertion `value != NULL' failed

(nautilus:8100): GConf-CRITICAL **: gconf_value_free: assertion `value != NULL' failed

(nautilus:8100): GConf-CRITICAL **: gconf_value_free: assertion `value != NULL' failed

(nautilus:8100): GConf-CRITICAL **: gconf_value_free: assertion `value != NULL' failed

(nautilus:8100): GConf-CRITICAL **: gconf_value_free: assertion `value != NULL' failed

(nautilus:8100): GConf-CRITICAL **: gconf_value_free: assertion `value != NULL' failed

(nautilus:8100): GConf-CRITICAL **: gconf_value_free: assertion `value != NULL' failed
Nautilus-Share-Message: Called "net usershare info" but it failed: 'net usershare' returned error 255: net usershare: cannot open usershare directory /var/lib/samba/usershares. Error No such file or directory
Please ask your system administrator to enable user sharing.

How can I get back to the old nautilus?


text:
Q: c# OpenIdConnect authentication I'm trying to secure an API with keycloack. The API is called by a server. So there is no browser.
(Logging in via Browser works fine and i can access the api.)
When I try to call the API via curl or Postman, I get redirected to the login site of keycloak (just like in the browser). This happens regardless of me giving an Access Bearer Token.
Why can I not get access? The token is what should skip the login somehow...
These are the curl cmds I use:
export TOKEN=$(curl -k -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=test" \
  -d "username=test@test.de" \
  -d "password=123456" \
  -d "grant_type=password" \
  -d "client_secret=fefaefaefaseeas" \
  -X POST https://XXXXX/protocol/openid-connect/token | jq -r .access_token)

echo $TOKEN

curl -i -k -X GET -H "Authorization: Bearer $TOKEN" https://localhost:5001/api-test

This is the code where the API is:
.AddOpenIdConnect("oidc", options =>
 {
     options.Authority = "https://xxxxx/auth/realms/master";
     options.ClientId = "test";

     // For testing we disable https (should be true for production)
     options.RequireHttpsMetadata = false;
     options.SaveTokens = true;

     // Client secret shared with Keycloak
     options.ClientSecret = "fefaefaefaseeas";
     options.GetClaimsFromUserInfoEndpoint = true;

     // OpenID flow to use
     options.ResponseType = OpenIdConnectResponseType.Code;
});

A: An API's job is to validate access tokens, and there are no browser redirects. So your code should look like this:

services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.Authority = oidcMetadataEndpoint;
    options.TokenValidationParameters = new
    TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = "myissuer",
        ValidateAudience = true,
        ValudAudience = "api.mycompany.com",
    };
});

You are using the website tech stack which is causing the redirects. When using the above API tech stack, you will get a 401 error response if you send in an invalid token, rather than a redirect response.


text:
Q: Unable to connect to databricks cluster from Windows using databricks-connect I am trying to setup databricks-connect in my windows machine. While doing databricks-connect test I am getting the below error complaining java certificate is not found. ''
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306)
    at sun.security.validator.Validator.validate(Validator.java:271)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:312)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:275)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:140)
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:630)
    ... 27 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:434)
    ... 33 more

I have java 1.8 installed and I downloaded the browser certificate and installed it

I installed the certificate using below command.
   keytool -importcert -trustcacerts -alias repo -file C:\Users\ravi\Downloads\adbcert.crt -keystore cacerts "C:\Java\jdk1.8.0_333\jre\lib\security\cacerts" -storepass changeit

Still, I am facing the same issue.

A: Adding root certificate solved the problem.


text:
Q: method that takes a hash and returns an array I am trying to build a method that takes two arguments (source, in this case a hash of names, and thing_to_find, in this case an age as an integer) and returns just the hash keys with that integer. The output should be an array of the hash keys with that value (but not output the value).
I'm about fried trying to get this - help very much appreciated. here's what is given...
my_family_pets_ages = {"Evi" => 6, "Ditto" => 3, "Hoobie" => 3, "George" => 12, "Bogart" => 4, "Poly" => 4, "Annabelle" => 0}

def my_hash_finding_method(source, thing_to_find)
# here i've tried all manner of has_value?, map, include? etc. - I think I'm probably having a problem with syntax...am I close with this?
   source.select { |k, v| v.include? thing_to_find }
end

the output should look like
    my_hash_finding_method(my_family_pets_ages, 3)
    #=> should return ["Hoobie", "Ditto"]


text:
Q: Remove navigation back button after user logout I'm using Android Jetpack Navigation Component for my app. It has Two screen (Fragment) which are homeFragment and loginFragment. The homeFragment is the start destination. After logout from homeFragment to loginFragment, the navigation back button shows up, it will back to homeFragment again when click, that's not correct. I expect the back button not shown in loginFragment, and if user press system back app exit. The nav_graph.xml is setting properly as this post was told:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_graph"
    app:startDestination="@id/homeFragment">

    <fragment
        android:id="@+id/loginFragment"
        android:name="cn.helptool.qxscales.LoginFragment"
        android:label="Login" >
        <action
            android:id="@+id/action_loginFragment_to_homeFragment"
            app:destination="@id/homeFragment"
            app:popUpTo="@id/nav_graph"
            app:popUpToInclusive="true" />
    </fragment>
    <fragment
        android:id="@+id/homeFragment"
        android:name="cn.helptool.qxscales.HomeFragment"
        android:label="Home">
        <action
            android:id="@+id/action_homeFragment_to_loginFragment"
            app:destination="@id/loginFragment"
            app:popUpTo="@id/nav_graph"
            app:popUpToInclusive="true" />
    </fragment>
</navigation>

A: After read android docs

Add both of loginFragment and homeFragment as top level destinations, the problem fixed.
val appBarConfiguration = AppBarConfiguration.Builder(R.id.loginFragment, R.id.homeFragment).build()
setupActionBarWithNavController(navController, appBarConfiguration)


text:
Q: Cannot run jar outside intellij using javafx I am running an JavaFX project in IntelliJ successfully but when I am trying to build the artifacts and run the jar outside it won't open or it's opening and closing right away.
I tried to move the .fxml files into java directory and change the load but I get an error.
My project sturcture is this:

And my Main class is here:
public class Main extends Application {

    @Override
    public void start(final Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
        primaryStage.setTitle("xxxxxxxxxxxxx");
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

I have selected all jar libraries that I use and added them in artifacts. My guess is that it doesn't load the .fxml files outside IntelliJ.
If is needed my sample.fxml is here:
<?xml version="1.0" encoding="UTF-8"?>

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

<Pane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" prefHeight="650.0" prefWidth="550.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <TextField fx:id="username" alignment="CENTER" layoutX="151.0" layoutY="246.0" prefHeight="25.0" prefWidth="229.0" />
        <PasswordField fx:id="password" layoutX="152.0" layoutY="345.0" prefHeight="25.0" prefWidth="229.0" />
        <CheckBox fx:id="rememberMe" layoutX="207.0" layoutY="418.0" mnemonicParsing="false" text="Remember me ?">

        </CheckBox>
        <Button fx:id="login" layoutX="199.0" layoutY="542.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="153.0" text="OK" textAlignment="CENTER">

            </Button>
        <Hyperlink layoutX="203.0" layoutY="446.0" text="I forgot my password !" />

            <effect>
                <Lighting>
                    <bumpInput>
                        <Shadow />
                    </bumpInput>
                </Lighting>
            </effect>

            <effect>
                <Lighting>
                    <bumpInput>
                        <Shadow />
                    </bumpInput>
                </Lighting>
            </effect>

    </children>
</Pane>

Error:
Exception in Application start method
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unk
nown Source)
        at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Sou
rce)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
        at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown So
urce)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(
Unknown Source)
        at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException: Location is required.
        at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
        at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
        at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
        at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
        at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
        at javafx.fxml.FXMLLoader.load(Unknown Source)
        at Main.start(Main.java:25)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162
(Unknown Source)
        at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown
 Source)
        at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Sourc
e)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown S
ource)
        at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
        ... 1 more
Exception running application Main


text:
Q: only instance of a python 3.7 application run I want to make my application by Python 3.7 run just in only one instance.
I have tried the code bellow codes but I didnt succed.
import psutil
import time

procs = [p for p in psutil.process_iter() if 'python.exe' in p.name() and __file__ in p.cmdline()]
if len(procs) > 1:
    print('Process is already running...')
    sys.exit(1)

for i in range(10):
    print('Running...')
    time.sleep(2)```


text:
Q: Python - to check if a char is in dictionary and if not to deal with it I am going about transliteration from one source language(input file) to a target language(target file) so I am checking for equivalent mappings in a dictionary in my source code, certain characters in the source code don't have an equivalent mapping like comma(,) and all other such special symbols. How do I check if the character belongs to the dictionary for which I have an equivalent mapping and to even take care of those special symbols to be printed in the target file which don't have an equivalent mapping in the dictionary. Thank you:).

A: My recommendation, given that rules is a mapping of the characters to their transliterated equivalents:
results = []
for char in source_text:
    results.append(rules.get(char, char))
return ''.join(results)    # turns the list back into a string

A dict's get method will return either the value for a key or a default value if the key does not exist - normally the default value is None, but in this case, we gave the same character as the default value (the second argument) so that if the key is not found it will just return itself.
A more compact way to write this using generator expressions would be:
''.join((rules.get(char, char) for char in source_text))

A: If you use the translate method of Unicode objects, as I recommended in answer to another question of yours, everything's done automatically for you exactly as you desire: each Unicode character c whose codepoints (ord(c)) is not in the transliteration dictionary is simply passed unchanged from input to output, just as you want.  Why reinvent the wheel?

A: I think you want something like this:
tokenMapping = {"&&" : "and"}

for token in source file: # <-- pseudocode
    translatedToken = tokenMapping[token] if token in tokenMapping else "transliteration unknown"

If there's a translation in the dictionary (e.g. "&&" -> "and"), it will use that. Else it will translate to "transliteration unknown".
Hope that helped.
EDIT: As LeafStorm suggested, a dictionary's get function can be used to simplify the above code. The code line in the loop would become
    translatedToken = tokenMapping.get(token, "transliteration unknown")

A: dictx = {}
for itm in my_source :
    dictx[itm] = dictx.get(itm, 0) + 1

I didn't completely understand the details of your question, but here's the simplest example i could think of that illustrates the pattern i think you are after.
The 'get' method i believe is what you want. It allows you to retrieve a key from a dictionary, but if the key is not there, you can set a default value--i.e., "i want dictx[itm] (the value assigned to the key 'itm') but if 'itm' is not in dictionary then create it and value of .'
This snippet will loop through your source document ('my_source') and count the frequency of the various items in it, adding those counts as values to the keys already in your dictionary, but when it reaches an item for which no key exists, no exception is thrown, a key is added and a value of '0' assigned.

A: This seems pretty straightforward. If your dictionary is char to char, then you would do something like
outstr = ''
for ch in instr:
    if ch in mydict:
        outstr += mydict[ch]
    else:
        outstr += ch

Here, instr is your input string and mydict contains your mapping of chars to chars.
If you want to check parts of words, I would recommend using two dictionaries: one that contains the characters that are contained in any word, and one that contains the words. You could use it like this:
outstr = ''
word = ''
for ch in instr:
    if ch in chardict:
        word += ch
    else:
        if len(word):
            if word in worddict:
                outstr += worddict[word]
            else:
                outstr += word
            word = ''
        outstr += ch
if len(word):
    outstr += worddict[word]
else:
    outstr += word

chardict might contain all of the alphabet for instance. Of course, you might want to do some parts a little bit differently (like use something other than chardict to check if a char is to be considered part of a valid word - perhaps something with a binary search), but hopefully you get the idea.


text:
Q: How to re-add a container in Bluemix When I try to add a container to space A in bluemix I receive the following error:

BXNUI0521E: While attempting to create a container from the image, an
  internal error with incident ID 747-1463152155.505-13996376 occurred.
  Some resources, such as an IP address or memory, were not available
  when the namespace was being retrieved.

Also when I run cf ic login in space A I receive:
{
    "code": "IC5005E",
    "description": "The maximum quota for this organization is 2 floating IPs and 2048 memory. The action you are trying to complete, such as logging into a new space, would exceed the maximum quota. The current floating IP usage is 2 and this action would require an additional 2. The current memory usage is 2048 and this action would require an additional 2048. Reduce usage for the organization or ask your organization manager to adjust the quota allocation in the Manage Organizations page.",
    "incident_id": "744-1463151704.272-14000754",
    "name": "IPAndMemoryQuotaExceeded",
    "rc": "500",
    "type": "Quota"
}

I believe this is because I created a container in space B, which assigned two IP addresses to it. I have since deleted this space. How do I reduce the floating IP usage down to 0?

A: Normally you would need the following steps:
At first you need to target the right org and space using:
cf target -o ORG -s SPACE

You can list all allocated public IP addresses (available or not) using:
cf ic ip list -a

Then you can release an IP using:
cf ic ip release [IPAddr]

However in your case you may not be able to release the IPs if they are bound to a deleted space. If the above steps don't fix the issue you may open a support request asking the IBM Containers team to release the IPs.

A: With this quota (2 IP addresses and 2048 MB) I am assuming you have a Bluemix free account.
In this case you can only create containers in one single space within your organization. Once you created containers in space B you cannot create any containers in space A (even if you have enough quota for that).
You mentioned you deleted space B (where you originally created containers), so you will have wait a while (usually within 24 hours or less) so your account is reset.
After that you will be able to login again to a new space, create a new namespace and start using containers again.


text:
Q: Stream media stops at 2Mb in Chrome, but Not MS Edge? investigating an interesting IE/Chrome thing I think.   So, we have a streaming audio service that can queue up audio files.  On average, the audio is less than 2Mb but occasionally we run across one that is slightly larger.   Our clients started to complain that our audio was stalling out.
So, we fired up an azure vm.   Figured that'd be a good neutral comparison, same firewall, same settings, everything.
This happens to be  a Windows 10 VM.  Nothing special about it.
So, in Edge, everything works fine.  We can stream audio of any size without any problem.
In Chrome though, they all stop at 2Mb.
I doubt it has anything to do with our service (it works fine in Edge, but not chrome).
If it was a network framing issue, I would expect it to affect both, it doesn't.
If it were virus protection then I'd expect it to be an issue for both.   (And for grins and giggles, I fired up a VM that didn't have antivirus, no difference).
I haven't tried firefox on it yet to see.
Anybody got any ideas of what it might be?
Thanks,
Nick

A: This comes down to a partial content request method.....  I found the answer here:
https://blogs.msdn.microsoft.com/webdev/2012/11/23/asp-net-web-api-and-http-byte-range-support/
It ended up being all of about 10 lines of code I had to add


text:
Q: Compile with clang instead of gcc I have downloaded openssh-6.4p1 for Linux and I want to compile it using clang instead of gcc. How can I tell the compilation engine to do this? Do I need to modify configure?

A: You can try to use the option command like this:
option(USE_CLANG "build application with clang" ON) # OFF is the default

and then you can wrap the clang-compiler settings in the if() condition like this:
if(USE_CLANG)
    SET (...)
    //...
endif(USE_CLANG)


text:
Q: Empathy: Account Manager Error "Message did not receive a reply (timeout by message bus)" I run Ubuntu Ocelotin italian language and since a week I get a strange error by Empathy:
"Message did not receive a reply (timeout by message bus)"
It seems that telepathy cannot contact the account manager,.
As said, Empathy starts but the most important part of it, the account manager, doesn't. I tried to purge Empathy and Telepathy, to disable its repository with Ubuntu Tweak, but without results. What do I have to do, I need to use Empathy !
Greetings,
Francesco

A: Temporary workaround:
killall -9 empathy
killall -9 /usr/lib/telepathy/mission-control-5

Then restart Empathy. It should work until it breaks again.

A: I received the same message, but only if empathy is a start up application.  If you deactivate empathy from starting at start up and activate it manually the problem seemed to go away.  My feeling is that empathy is starting prior to telepathy being ready to accept its request.