text:
Q: How to split JTextArea to ranges of lines and save them to separate fiels? My simple program takes input from keyboard or text field and put it to JTextArea like this:
1111,1111;\n
2222,2222;\n
3333,3333;\n
.
.
.
\n

When I finish inputting data i want to save it to the txt file, but there is one condition - when there are more then 30 lines, data from jtextarea have to be split into smaller "packages" (every one have to have only 30 lines (or the last one less) and they have to be saved to separated txt files. Every file have to have empty line at the end (\n).
I know how to create files.
I can count into how many pieces i have to split data from jtextarea.
But i can't figure it out how to read 1-30 lines by scaner in the first run and save it to file, 31-60 in the second run and save etc etc.
String string = jtextarea.getText() gets all the lines

I try also something like this:
for (int i=1; i<31; i++)
{
    while(scaner.hasNext())
    pw.println(scaner.nextLine());
}

but it also reads all the lines
This also not working - gives only 30 characters - not lines:
String alltext = jtextare.getText();
String lines = alltext.substring(0, 30);

This example i don't understand:
String text = inputArea.getText();
int totalLines = inputArea.getLineCount();
for (int i=0; i < totalLines; i++) {
    int start = inputArea.getLineStartOffset(i);
    int end = inputArea.getLineEndOffset(i);
    String line = text.substring(start, end);

    outputArea.append(line + "\n");
}

Why bother when i can't point line number, only position in line.
Please help me with this problem - can you describe proper loop and commands for this?
SIMPLE DESCRIPTION OF PROBLEM
I have jTextArea with 100 lines of text. Every line ending with \n.
I want to split this 100 lines into groups of 30 lines per group, and write every group to txt file - every txt file will contain 30 lines of text (every line ending with \n), and last (31) line should be empty.
What is the easiest way to do this?

A: This works:
try
{
    Scanner sc = new Scanner(ta.getText());
    String s="";
    for(int i=1; i<=100; i++)
    {
        s+=sc.nextLine()+"\r\n";
        if(i%30==0)
        {
            File f = new File("File"+(i/30)+".txt");
            f.createNewFile();
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
            bw.write(s);
            bw.close();
            s="";
        }
    }
    File f = new File("File4.txt");
    f.createNewFile();
    BufferedWriter bw = new BufferedWriter(new FileWriter(f));
    bw.write(s);
    bw.close();
}catch(Exception e){}


text:
Q: Markov Decision Process - Utility Function Reward $R(S)$ in a Markov Decision Process is a mapping from a State $S \rightarrow$ Bounded number. I want to know how a Utility Function is defined for an MDP.
I think it has to be a mapping from a sequence of states to a bounded number - where the utility function is just the Summation of the rewards $R(S)$ of each of the states visited by an agent. Would that be correct?

A: Your notation is not completely clear to me (especially with regards to bounded number).
Markov Decision Process (MDP) is a Markov process (MP) where (probabilistic) control is allowed, that name usually refers to discrete-time processes. Probabilistic control means that at each step you choose just a distribution of the next value from the class of admissible distributions. Again, $$\text{MDP} = \text{MP} + \text{probabilistic control}.$$
Talking about the reward $R:S\to\mathbb R$ the name for the model I met in the literature (Computer Science as well) is Markov Reward Model (MRM): that is MP + reward function, not necessary with a control in general. The underlying process for MRM can be just MP or may be MDP.
Utility function can be defined e.g. as $U=\sum\limits_{i=0}^nR(X_i)$ given that  $X_0,X_1,...,X_n$ is a realization of the process. In the case when the underlying process is uncontrolled, one studies distribution of this function. In the case when control is allowed, optimal control problems are solved. On the other hand, nothing will prevent you from defining $U$ is another form and studying its properties.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to verify a document from QLDB in Node.js? I'm trying to verify a document from QLDB using nodejs. I have been following the Java verification example as much as I can, but I'm unable to calculate the same digest as stored on the ledger.
This is the code I have come up with. I query the proof and block hash from QLDB and then try to calculate digest in the same way as in Java example. But after concatinating the two hashes and calculating the new hash from the result I get the wrong output from crypto.createHash('sha256').update(c).digest("base64"). I have also tried using "base64" instead of "hex" with different, but also wrong result.
  const rBlock = makeReader(res.Revision.IonText);

  var block = [];

  rBlock.next();
  rBlock.stepIn();
  rBlock.next();
  while (rBlock.next() != null) {
    if (rBlock.fieldName() == 'hash') {
      block.push(Buffer.from(rBlock.byteValue()).toString('hex'));
    }
  }

  console.log(block);

  var proof = [];

  const rProof = makeReader(res.Proof.IonText);
  rProof.next();

  rProof.stepIn();
  while (rProof.next() != null) {
    proof.push(Buffer.from(rProof.byteValue()).toString('hex'));
  }

  var ph = block[0];
  var c;
  for (var i = 0; i < proof.length; i++) {
    console.log(proof[i])

    for (var j = 0; j < ph.length; j++) {
      if (parseInt(ph[j]) > parseInt(proof[i][j])){
        c = ph + proof[i];
        break;
      }
      if (parseInt(ph[j]) < parseInt(proof[i][j])){
        c = proof[i] + ph;
        break;
      }
    }

    ph = crypto.createHash('sha256').update(c).digest("hex");
    console.log(ph);
    console.log();
  }

A: I have figure it out. The problem was that I was converting the blobs to hex strings and hash them instead of the raw values. For anyone wanting to verify data in node, here is the bare solution:
ledgerInfo.getRevision(params).then(res => {
  console.log(res);

  const rBlock = makeReader(res.Revision.IonText);

  var ph;

  rBlock.next();
  rBlock.stepIn();
  rBlock.next();
  while (rBlock.next() != null) {
    if (rBlock.fieldName() == 'hash') {
      ph = rBlock.byteValue()
    }
  }

  var proof = [];

  const rProof = makeReader(res.Proof.IonText);
  rProof.next();

  rProof.stepIn();
  while (rProof.next() != null) {
    proof.push(rProof.byteValue());
  }

  for (var i = 0; i < proof.length; i++) {
    var c;

    if (hashComparator(ph, proof[i]) < 0) {
      c = concatTypedArrays(ph, proof[i]);
    }
    else {
      c = concatTypedArrays(proof[i], ph);
    }

    var buff = crypto.createHash('sha256').update(c).digest("hex");
    ph = Uint8Array.from(Buffer.from(buff, 'hex'));
  }

  console.log(Buffer.from(ph).toString('base64'));

}).catch(err => {
  console.log(err, err.stack)
});

function concatTypedArrays(a, b) {
  var c = new (a.constructor)(a.length + b.length);
  c.set(a, 0);
  c.set(b, a.length);
  return c;
}

function hashComparator(h1, h2) {
  for (var i = h1.length - 1; i >= 0; i--) {
    var diff = (h1[i]<<24>>24) - (h2[i]<<24>>24);
    if (diff != 0)
      return diff;
  }
  return 0;
}


text:
Q: CSS3 Animation - Infinite moving arrow In this website link an arrow is moving i want to know to how to set this effect in CSS
i have a code
-webkit-animation: new_icon 2s linear 0s infinite alternate;
But for the moment this dosnt work.

A: You need to declare your animation details for new_icon - see the code in the CSS file on the site you refrence.  You'll need to change the ID names accordingly.:
  @-webkit-keyframes new_icon {
    0% { -webkit-transform: translate(0px, 5px) ; }
    100% { -webkit-transform: translate(0px, -15px);  }
  }
  @-moz-keyframes new_icon {
        0% { background-position: 0 0; }
      100% { background-position: 0 600%; }
  }

    #lp-pom-image-350, #lp-pom-image-472, #lp-pom-image-473, #lp-pom-image-474, #lp-pom-image-475{
     animation: new_icon 1s linear 0s infinite alternate;
    -webkit-animation: new_icon 2s linear 0s infinite alternate;
  }

A: You need to set up a css animation. The following one should do the trick:
@-webkit-keyframes bounce {
50% {
-webkit-transform(translateY(-30px));
}
100% {
-webkit-transform(translateY(0px));
}
}
/* For firefox and others than webkit based browsers */
@keyframes bounce {
50% {
transform(translateY(-30px));
}
100% {
transform(translateY(0px));
}
}

And then add this to the arrow class:
.your_arrow_class
{
    -webkit-animation: bounce 2s linear 0s infinite alternate;
    animation: bounce 2s linear 0s infinite alternate;
}

A: its because you would also need the animation set.
in this case the animation is called:

new_icon

for further information how it works read this about css3 animations
the new_icon animation would probably look like this:
so add this to your css ( don't forget to prefix it) and it should work.
@keyframes new_icon {
    0%   { top: 275px; }
    100% { top: 300px; }
}

greetings timmi


text:
Q: I am unable to read EAST: An Efficient and Accurate Scene Text Detector as .pb file in jupyter notebook I am working on extracting text from an Image (OCR) and it should display the text on boundary box using EAST. As EAST is .PB file and I am working on Jupyter notebook. I am unable to read the file. [net = cv2.dnn.readNet(args["east"] results in error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\dnn\src\dnn.cpp:3780: error: (-2:Unspecified error) Cannot determine an origin framework of files: C:/Python/resnet_v1_50.ckpt in function 'cv::dnn::dnn4_v20190122::readNet). Can someone help in solving the issue.
I have tried opening/converting the .pb file to other fromats using software such as Fantaisie Software, but they are paid ones, so i have failed. Are there any free softwares to read the model. Also i am unable to open two layers layerNames = ["feature_fusion/Conv_7/Sigmoid","feature_fusion/concat_3"].
import numpy as np
import cv2
from imutils.object_detection import non_max_suppression
import pytesseract
from matplotlib import pyplot as plt

args = {"image":"C:/Users/temp/Desktop/download.jpg", "east":"C:/Python/resnet_v1_50.ckpt", "min_confidence":0.5, "width":320, "height":320}

args['image']="C:/Users/temp/Desktop/Cheque.jpg"
image = cv2.imread(args['image'])

orig = image.copy()
(origH, origW) = image.shape[:2]

(newW, newH) = (args["width"], args["height"])

rW = origW / float(newW)
rH = origH / float(newH)

image = cv2.resize(image, (newW, newH))
(H, W) = image.shape[:2]

blob = cv2.dnn.blobFromImage(image, 1.0, (W, H),(123.68, 116.78, 103.94), swapRB=True, crop=False)

net = cv2.dnn.readNet(args["east"])

layerNames = ["feature_fusion/Conv_7/Sigmoid","feature_fusion/concat_3"]

net.setInput(blob)
(scores, geometry) = net.forward(layerNames)

soooooo...onnnnn
Unable to load, and run the model

A: *

*You should load your dnn file from this link.

*Extract your 'frozen_east_text_detection.pb' file to desktop.

*You need to change your code like this:
net = cv2.dnn.readNet('C:\\Users\\Desktop\\frozen_east_text_detection.pb')

It's going to load successfully.
EDIT: These errors occurs because of inability to file read.
    cv::dnn::dnn4_v20190122::readNet


text:
Q: representing 2 different metrics with different columns in line chart I am preparing a datastudio report.  The data studio report consists of the following columns below:

As seen in the picture it captures metric data at a particular time.
The date range is set as the end_time

The X axis will represent the end_time column and the breakdown dimension will be InstanceName  column and I am preparing to show it as line chart.
There are 2 metrics readops and writeops columns.
I need to represent these 2 metrics as 2 different lines in the same chart so that the read and write operation fluctuations for the instance at a particular time can be easily viewed.
I am not sure on how to represent this on data studio. If it is 1 metrics, i know it is straight forward. I can set instancename as breakdown dimension and end_time as dimension and date range is set to end_time and can represent it. But to represent the 2 metrics as 2 different lines for a particular Instance, with the time range on x axis, i don't know as I am very new to datastudio. I want to do it without drill-down. similar to the picture below which I got from google cloud console which shows ReadBytes the Big Triangle and the smaller one at the bottom in red for WriteBytes

Can anyone help me? Thanks

A: There are two approaches based on how the the charts need to be displayed:
1) Filter Control
If the aim is to only display 2 lines (2 Metrics):

*

*readops

*writeops
While allowing the user to select the required InstanceName, then a Filter Control (optionally with a default selection) could be used.
The chart would be set up using:

*

*Dimension: end_time

*Metric #1: readops

*Metric #2: writeops
Editable Google Data Studio Report and a GIF to expand on the above:

2) Multiple Metrics
If the objective is to display a line for each of the InstanceName values as well as both the Metrics (readops and writeops), then the below approach would be one way.
Currently, when using a Breakdown Dimension, Google Data Studio charts (such as a Time Series chart) support a single metric.
Using the Data Set below, based on the screenshot in the question (Editable Google Sheets):

One approach is to create and use multiple CASE statements at the Data Source; for example:

*

*readops_dum
CASE
  WHEN REGEXP_MATCH(InstanceName, "(dum)") THEN readops
  ELSE NULL
END

*writeops_dum
CASE
  WHEN REGEXP_MATCH(InstanceName, "(dum)") THEN writeops
  ELSE NULL
END

etc...
Editable Google Data Studio Data Source and an image to elaborate:

A Chart could then be created with end_time as the Dimension and using the newly created Metrics; Editable Google Data Studio Report and an image to visualise with a Time Series chart:


text:
Q: Distribute all rows in Each Months Mysql Hi I am new to mysql
Address        Type    MonthCreated       YearCreated
AddA1           M1     August                 2018
AddA1           I2     August                 2018
AddA1           K2     October                2018

Desired Output
is like this three rows will be distrubuted in every month like to january february march to december 2018
Select  AddA1,Type,MonthCreated,YearCreated
from tbltry
where YearCreated = '2018'

Desired Output is all the rows for each month since it is still in the same year I am just wondering if its possible really need help or advice
Address        Type    MonthCreated       YearCreated
AddA1           M1     January                2018
AddA1           I2     January                2018
AddA1           K2     January                2018
AddA1           M1     February               2018
AddA1           I2     February               2018
AddA1           K2     February               2018
AddA1           M1     March                  2018
AddA1           I2     March                  2018
AddA1           K2     March                  2018

up till december it will returns all the rows is it possible? Really need advice

A: *

*In a Derived Table, you can create a "Master Table" for all the months.

*In another Derived table, you can get the distinct combinations of AddA1 and Type for the year 2018.

*Simply do a CROSS JOIN between them to get all possible months.

Try:
SELECT dttry.*, all_months.*
FROM
(SELECT DISTINCT AddA1, Type, YearCreated
 FROM tbltry
 WHERE YearCreated = '2018') AS dttry
CROSS JOIN
(SELECT 'January' AS MonthCreated UNION ALL
 SELECT 'February' UNION ALL
 SELECT 'March' UNION ALL
 SELECT 'April' UNION ALL
 SELECT 'May' UNION ALL
 SELECT 'June' UNION ALL
 SELECT 'July' UNION ALL
 SELECT 'August' UNION ALL
 SELECT 'September' UNION ALL
 SELECT 'October' UNION ALL
 SELECT 'November' UNION ALL
 SELECT 'December') AS all_months


text:
Q: how to unlist my images list while keeping their dimensions? I'm new to R, i want to know if Iam reading images using readJPEG and it works, but gives me a list with one column, each row contains a 10*10 inside, the problem is I cant do operations on, because it's a list, i.e calculating the euclidean distance between images using "dist". how can I convert it to a matrix with the same dimensions without using "unlist"???

A: Try do.call("rbind",thelistobject).


text:
Q: recyclerView setAdapter is very slow I used recyclerView in my android app and filled it by a list with 120 items. my problem is that it takes a couple of time to load recyclerView. it seems that setAdapter() method is very slow . what can I do to fix it?
list.addAll(db.getKarevanMembers());
KarevanMembersAdapter adapter = new KarevanMembersAdapter(list);
binding.membersLayout.karevanMembersList.setAdapter(adapter);

A: Instead of setting new adapter change data of current adapter and call adapter.notifyDataSetChanged().
If you want to change/remove only some elements in the list, use the methods notifyItemInserted, notifyItemRangeInserted, notifyItemChanged, notifyItemRangeChanged, notifyItemRangeRemoved, notifyItemRemoved to update adapter (see https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html).


text:
Q: How to get an integer value to a complex dictionary Here the value of abc is an integer and total is a dictionary which contains another dictionaries.But when I run this line,
    total[div]['total_transport_allowance'] = abc

This error is shown : "KeyError: None"
Please Help
What I want from this statement is to get the abc's value to the key 'total_transport_allowance'
def print_excel_report(self,cr,uid,ids,data,context=None):
    result = self._get_lines(cr,uid,ids,data)
    filename= 'PayrollRegister.xls'
    workbook= xlwt.Workbook(encoding="UTF-8")
    sheet= workbook.add_sheet('Payroll Register',cell_overwrite_ok=True)
    style = xlwt.easyxf('font:height 400, bold True, name Arial; align: horiz center, vert center;borders: top medium,right medium,bottom medium,left medium')
    a = range(1,10)
    row = 1
    col =0
    header = ['Division','Basic','Transport Allowance']
    style2 = xlwt.easyxf('font: bold 1')
    total = {}

    for index,data in enumerate(result):
        div = data.get('Division',False)
        abc = data.get('transport_allowance',False) or 0

        if div:
            if div in total:
                total[div]['total_basic'] = total[div]['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] +  abc
            else:
                total[div] = {}
                total[div]['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc

        else:
            if 'Undefined' in total:
                total['Undefined']['total_basic'] = total['Undefined']['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] + abc

            else:
                total['Undefined'] = {}
                total['Undefined']['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc
        .......
        .....

A: To try and rescue something from all the downvotes:
You have an if statment checking the truthy of div. In the falsey case you then use div to access total.
ie you have:
if div:
    # stuff
else:
    # stuff
    total[div]['total_transport_allowance'] = abc

As total doesn't have the key div, this doesn't work.
you need something like total[div] = {}

A: You are getting this error because div is None:
 if div:
    ....
    ....
 else:
    ...
    ...
    # div here is None or False ..
    # you cannot use it as key!!
    total[div]['total_transport_allowance'] = abc

You need to define the key here first. so where
you want to put the abc when div is None.
EDIT
I don't know what the value of div should when it's not in data.get('Division',False):
    div = data.get('Division', False)
    ...
    ...
    if div:
       .....
    else:
        # assing a value to div
        div = 'NEW_VALUE'
        # add dictionary there
        total[div] = {}
        if 'Undefined' in total:
            ....
        ...
        ...

A: total[div]['total_transport_allowance'] = {}

This worked..
I have done like this in
total['Undefined']['total_transport_allowance'] = {}

also..
Thanks for everyone's help

A: KeyError is None means not defined dictionary. div is a dictionary should be defined.


text:
Q: Custom Admin component with custom dataprovider I need custom Admin component to update the list of Resource components dynamically.
The documentation provides an example:
import * as React from 'react';
import { useEffect, useState } from 'react';
import { AdminContext, AdminUI, Resource, ListGuesser, useDataProvider } from 'react-admin';

function App() {
    return (
        <AdminContext dataProvider={myDataProvider}>
            <AsyncResources />
        </AdminContext>
    );
}

function AsyncResources() {
    const [resources, setResources] = useState([]);
    const dataProvider = useDataProvider();

    useEffect(() => {
        // Note that the `getResources` is not provided by react-admin. You have to implement your own custom verb.
        dataProvider.getResources().then(r => setResources(r));
    }, []);

    return (
        <AdminUI>
            {resources.map(resource => (
                <Resource name={resource.name} key={resource.key} list={ListGuesser} />
            ))}
        </AdminUI>
    );
}

It is supposed to work with custom dataprovider that has getResources() function.
Ok. But how this function is supposed to look like? Or rather what it should return? Because tried many things and none is flying.
And also. There is a warning about React Hook useEffect missing a dependency: 'dataProvider'. Solutions online aren't usable so far. I don't think my example doesn't work because of that, but it's possible. How to fix that in that case?
So yeah, in short - how to make this provided in documentation example to work?
+++
Edit: In case anyone wondering here is how I apply my dataprovider:
import dataProvider from './dataprovider';

function App() {
    return (
        <AdminContext dataProvider={dataProvider}>
            <AsyncResources />
        </AdminContext>
    );
}

And here is my get_resources function:
getResources: () => {
    const url = `${apiUrl}/get_resources`;

    return httpClient(url).then(
        ({ headers, json }) => ({
        data: json["data"],
        total: json["total"]
    }));
},

Edit 2:
Problem maybe lies within dataprovider, since it fails with error message "TypeError: can't convert undefined to object" while trying to call "isDataProviderOptions" function from here: node_modules/ra-core/esm/dataProvider/getDataProviderCallArguments.js:19.
Or it's calling the wrong dataprovider. Not the custom one I've supplied to the AdminContext component.
Should I add the code of my custom dataprovider?


text:
Q: Write to a file from another file and delete line from file My file(outputfile6.txt) is:
1രാമന് 2സീതയെ 3കണ്ടു 4.
5അവന് 6അവള്‍ക്ക് 7പൂവ് 8കൊടുത്തു 9.
10അവള് 11അത് 12വാങ്ങി 13.
14അവര് 15ഒരുമിച്ച് 16കോട്ടയത്ത് 17പോയി 18.
19അവിടെ 20വെച്ച് 21അവര്‍ക്ക് 22പരീക്ഷ 23ഉണ്ട് 24ആയിരുന്നു 25.
26അവിടെ 27വെച്ച് 28രാമന് 29ലക്ഷ്മനനെ 30കണ്ടു 31.
32അവന് 33രാമനോടു 34സംസാരിച്ചു 35.
36ലക്ഷ്മണന് 37സീതയെ 38കണ്ടു 39.
40അവനെ 41അവള്‍ക്ക് 42ഇഷ്ടമായി 43.
44ഈ 45വഴ 46ആണ് 47അവര് 48പണ്ട് 49നടന്നത് 50.

Is it possible to write these lines to another file on the basis of line number?
For eg:
 print from line no: 1 to 5. After that i want to delete those lines written to another file. This should be continued until EOF.
Since the above concept is a part of my code, I can't reveal my whole code.
For my work. First i found my starting sentence. and then found the final sentence i want.
fp = codecs.open('outputfile6.txt', encoding='utf-8')
lines1 = fp.readlines()
fp.close()
fb = codecs.open('outputfile7.txt', 'w')
write=0
for l in lines1:
    if i in l:#i is my search item which contains in the starting sentence.
        write=1
    if write==1:
        fb.write(l.encode('UTF-8'))
    if line_upto in l:#line_upto is a string which contains in the lastsentence
        write=0
        break
fb.close()#Here i didn't get a code for deleting lines from the file.

My output is:
I always get outputfile7.txt same as outputfile6.txt
My expected outputfile7.txt is:
1രാമന് 2സീതയെ 3കണ്ടു 4.
5അവന് 6അവള്‍ക്ക് 7പൂവ് 8കൊടുത്തു 9.
10അവള് 11അത് 12വാങ്ങി 13.
14അവര് 15ഒരുമിച്ച് 16കോട്ടയത്ത് 17പോയി 18.
19അവിടെ 20വെച്ച് 21അവര്‍ക്ക് 22പരീക്ഷ 23ഉണ്ട് 24ആയിരുന്നു 25.

A: I got the code for deleting lines:
here end is the line number upto which i want to delete from the file.
fp = codecs.open('outputfile6.txt', encoding='utf-8')
lines1 = fp.readlines()
fp.close()
fb = codecs.open('outputfile6.txt', 'w')
for j in range(0,len(lines1)):
    if j>end:
        fb.write(lines1[j].encode('UTF-8'))

fb.close()

If properly attach this code to above code,expected output will be obtained.


text:
Q: Send AT command and read serial while 'OK' isn't in the response I cannot find an answer for this anywhere so I come to you hoping someone can help me with this.
I have a Python script which send AT commands to a ZigBee module via a serial connection and then reads the answer provided by the module. Actually I already can catch and read this answer but sometimes I have undesired characters ending it or no response at all. My goal is to have a perfect output containing the answer and only it.
Here is an example of this behavior
So, to avoid this I try to read the module response character by character until it contains 'OK' or another expected message returned by the command indicating it's end but the problem is that my code is looping indefinitely since then.
The method I use :
def sendAtCommand(command):

# vars
response = ''

if ser.inWaiting() > 0:
    #flush input buffer, discarding all its contents
    ser.flushInput()
    #flush output buffer, aborting current output
    #ser.flushOutput()

ser.write(command.encode('ascii')+'\r')
#response = ser.read(size=1024)

# while True:
    # response = ser.read(size=1024)
    # if 'OK' in response:
        # break

while True:
    response += ser.read(size=1)
    print(response)

    if 'OK' in response:
        break

print('--------------')
print('Msg received : ')
print('--------------')
print(response)
print('--------------')


text:
Q: Adjustable L200 PSU Help I want to build myself an adjustable bench power supply with adjustable current limiting, mainly for fun but also because I want something to help me with prototyping. I have previously built small voltage supplies using linear regulators and pots, but I want something with the current control also.
I found the L200 and it seems to do what I want it to do:

*

*Voltage between 0-24V

*Current limiting 10m-2A (these are approx)
Here's an example circuit from the L200 datasheet:

My questions are as follows:

*

*Is this a decent solution for such a device in the modern day? Are there better IC solutions than this one? Maybe one that uses less external components?

*Is there an easy way to control the voltage/current with an MCU? Will I have to use digital pots to replace the analogue ones, or something, to do this?

*When I want to set/measure the output current limit, do I simply short Vo to ground through an ammeter and adjust P1? (I am under the impression this is how you do it with retail PSUs, not sure if this works in the same way).

*What kind of wattage resistors should I use? My naive calculation tells me that if the max current possible is 1.5A, then the max power dissipation in R3 is 1.5^2 * 0.1 = 0.225W, so most garden variety resistors would be OK. Is this correct?
Thanks for any help!


text:
Q: Чтение координат из текстового файла Помогите пожалуйста, никак не могу додуматься как добавить в код чтение координат из текстового файла.
Вот мой изначальный код:
#include <stdio.h>
#include <stdlib.h>

int main()
{
int x1, y1;
int x2, y2;
int x3, y3;
int x4, y4;
printf("First quadrilateral\n");
printf("Coordinates for A: ");
scanf("%d%d",&x1,&y1);
printf("Coordinates for B: ");
scanf("%d%d",&x2,&y2);
printf("Coordinates for C: ");
scanf("%d%d",&x3,&y3);
printf("Coordinates for D: ");
scanf("%d%d",&x4,&y4);

int x5, y5;
int x6, y6;
int x7, y7;
int x8, y8;
printf("Second quadrilateral\n");
printf("Coordinates for E: ");
scanf("%d%d",&x5,&y5);
printf("Coordinates for F: ");
scanf("%d%d",&x6,&y6);
printf("Coordinates for G: ");
scanf("%d%d",&x7,&y7);
printf("Coordinates for H: ");
scanf("%d%d",&x8,&y8);

if ( (x1 < x5 && y1 < y5) && (x2 < x6 && y2 > y6) && (x3 > x7 && y3 > y7) && (x4 > x8 && y4 < y8) )
    printf("Inside");
else
    printf("Not inside");
return 0;

}
txt файл с координатами выглядит так:
3 2 3 10
15 10 15 2
5 4 5 8
12 8 12 4


text:
Q: Can I create an 'everyone can post' style site with wordpress? A friend and I came up with an extremely simple idea for a website. Essentially we want people to be able to visit the site and quickly post a piece of text without having to register or sign in etc. Like a blog where everyone can contribute.
I noticed that wordpress allow you to install their software on your own server, do they only offer conventional blogs, or would it be easy to set something like this up?
I could write the server read/write stuff myself, but I have no faith in my ability to design a nice looking site, so just using a template would be best.

A: You'd need to have people sign up but you could set-up the default account as contributor or editor or something like that. Sounds though you might be better using some wiki software instead?


text:
Q: seq and seq_along, best of both worlds? If I want to number all elements in two vectors, vector 1 gets all odd bumbers and vector 2 gets all even numbers, I can do this assuming the vectors are of length 10.
seq(1, 10, by=2)
[1] 1 3 5 7 9

seq(2, 11, by=2)
[1]  2  4  6  8 10

but if my vector has only one element I will run into problems:
 seq(2)
[1] 1 2

so I use:
seq_along(2)
[1] 1

BUT I cant use by= in seq_long(). How do i get the reliability of seq_along with the functionality of seq()?

This example might clear things.
Imagine I ahve two lists:
list1 <- list(4)
list2 <- list(4)

list1 must get even names along the element of the list.
list2 must get odd names along the element of the list.
I dont know how long the list elements will be.
seq_along(list1[[1]]) # this will know to only give one name but I cant make it even

seq(list2[[1]]) # this know to give 1 name
#and
seq(2, list1[[1]], by=2) # this gives me even but too nay names

A: Here's a function that adds a 'by' argument to seq_along:
seq_along_by = function(x, by=1L, from = 1L) (seq_along(x) - 1L) * by + from

and some test cases
> seq_along_by(integer(), 2L)
integer(0)
> seq_along_by(1, 2L)
[1] 1
> seq_along_by(1:4, 2L)
[1] 1 3 5 7
> seq_along_by(1:4, 2.2)
[1] 1.0 3.2 5.4 7.6
> seq_along_by(1:4, -2.2)
[1]  1.0 -1.2 -3.4 -5.6

A: one way i just found is:
  y <- seq_along(1:20)
  y[y %% 2 == 0 ]
  [1]  2  4  6  8 10 12 14 16 18 20
  y[ !y %% 2 == 0 ]
  [1]  1  3  5  7  9 11 13 15 17 19

But this will only work when my vectors are even. Must be able to do better.

A: If I understand correctly, what you really want is a to get the 'seq' function to return only odd or oven numbers 1..max or 2..max, respectively.  You would write that like so:
seq(1, max, by=2) # Odd numbers
seq(2, max, by=2) # Even numbers

Where max is the top number in your series.  The only time this will break is if max is less than 2.
Update 1: There seems to be a bit of discussion about what the OP is requesting.  If we assume there are two existing vectors to be numbered, we can obtain the total number of vector items using max <- length(c(vector1, vector2)) to obtain the maximum number being used.  Then, the indices would be assigned like so:
vector1 <- seq(1, max, by=2)
vector2 <- seq(2, max, by=2)

And this will work for any set EXCEPT when one vector does not have any elements at all.
Update 2: There is one final approach, which you can take if your vectors do not represent all values between 1 and max.  This is how it would work:
vector1 <- seq(1, length(vector1) * 2, by=2)
vector2 <- seq(1, length(vector2) * 2, by=2)

This independently assigns the values of vector1 and vector2 according to their own lengths.

A: I'm not sure what you are trying to do, but if you want to split odd and even elements in a vector, you can do just that:
x <- 1:19
split(x,x%%2)
$`0`
[1]  2  4  6  8 10 12 14 16 18

$`1`
 [1]  1  3  5  7  9 11 13 15 17 19

To extract the odd and even numbered elements, use lapply on this list using seq_along to enumerate the element numbers:
x <- rep(c("odd","even"),times=4)
lapply(split(seq_along(x),seq_along(x)%%2),function(y) "["(x,y))
$`0`
[1] "even" "even" "even" "even"

$`1`
[1] "odd" "odd" "odd" "odd"

This can of course be made into a function:
split_oe <- function(x) lapply(split(seq_along(x),seq_along(x)%%2),function(y) "["(x,y))
split_oe(1:10)
$`0`
[1]  2  4  6  8 10

$`1`
[1] 1 3 5 7 9

> split_oe(2)
$`1`
[1] 2

A: I'm adding another answer to address what may be your intent of the question rather than the question as you've stated it.
Let's assume you have a couple arrays, A1 and A2, with values, and you want to link an index to those values, so you can say index[n] and get a corresponding value from A1[n/2 + 1] if n is odd and A2[n/2] if n is even.
We would build a new vector, index, like so:
# Sample arrays
A1 <- sample(LETTERS, 5, rep=TRUE)
A2 <- sample(LETTERS, 5, rep=TRUE)

n_Max <- length(c(A1,A2))
index <- integer(n_Max)
index[seq(1,n_Max,by=2)] <- A1
index[seq(2,n_Max,by=2)] <- A2

Now, index[n] returns A1 values when n is odd, and returns A2 values when n is even.  This breaks if length(A2) is not equal to or one less than length(A1).


text:
Q: Flash shared object always gets reset So in my game, you want to make the potato as big as possible. The first time you play it, the highscores work fine,giving you a highscore and saving it. The problem is that whenever you play the game, the highscore is always reset to your current score, which means that even if you get a lower score then your previous highscore, it saves your current score as the highscore. my code looks like this:
var savedstuff:SharedObject = SharedObject.getLocal("myStuff");

if (savedstuff.data.bestScore = 0) {
     savedstuff.data.bestScore = 1
}

bigness.text = finish.toString();

if (finish > savedstuff.data.bestScore){
    savedstuff.data.bestScore = finish;
}
best.text = savedstuff.data.bestScore.toString();
savedstuff.flush();

where bigness is a textbox displaying your current score, best is a textbox displaying your highscore and bestScore is where the best score is stored. I have the line "if (finish > savedstuff.dada.bestScore)" which should make the overwrite only occur if you get a higher score, but it seems to just ignore that line. my game is here
http://www.kongregate.com/games/pwnedcat/grow-a-potato
any help is appreciated. I just started flash so I really don't know anything. :(

A: Check the condition, it should be
savedstuff.data.bestScore == 0

Instead of
savedstuff.data.bestScore = 0


text:
Q: WiX properties RefProjectOutputGroups RefTargetDir When referencing projects within WiX projects (*.wixproj) I often saw the code snippet
<ItemGroup>
  <ProjectReference Include="..\Foo.Bar\Foo.Bar.csproj">
    <Name>Foo.Bar</Name>
    <Project>{0bd367ce-5072-4161-8447-ff4deed97bd4}</Project>
    <Private>True</Private>
    <DoNotHarvest>True</DoNotHarvest>
    <RefProjectOutputGroups>Binaries;Content;Satellites</RefProjectOutputGroups>
    <RefTargetDir>INSTALLLOCATION</RefTargetDir>
  </ProjectReference>
</ItemGroup>

Can anyone explain to me what the properties DoNotHarvest, RefProjectOutputGroups, and RefTargetDir mean? Or point to some documentation? I couldn't find anything explaining the meaning of these properties (including the WiX documentation).

A: Those are disabled features for automatic reference project harvesting. The feature is disabled because it was found to have many bugs.

*

*When you change DoNotHarvest to false (double negatives are fun) the feature will sort of turn back on (but other things will be broken).

*RefProjectOutputGroups lists the project outputs from the referenced project to include in a generated ComponentGroup.

*RefTargetDir specifies the Directory that is used for all the generated Components.

As noted above, it's not documented because the feature does not currently work.


text:
Q: trailblazer reform gem, how to handle this type of input validation? We are looking at use the reform gem for validating input.
One of the issues we are facing is that we accept input in this format:
params = {
  records: {
    "record-id-23423424": {
      name:       'Joe Smith'
    }
    "record-id-43234233": {
      name:       'Jane Doe'
    }
    "record-id-345234555": {
      name:       'Fox trot'
    }
    "record-id-34234234": {
      name:       'Alex'
    }
  }
}

so if we were to create reform class
class RecordForm < Reform::Form
  property :records
  validates :records, presence: true

  # ?????????
end

How do we validate the contents of the records to make sure each one has a name?  The record-id-values are not known ahead of time.

A: Reform currently doesn't allow dynamic properties, and actually, it's not planned since Reform is supposed to be a UI-specific form object.
The solution would be to pre-parse your input into something what Laura suggests. You could then have nested properties for each field.
collection :records do
  property :id # manually parsed
  property :name
end


text:
Q: How to view the headers that were sent, using node-fetch? I'm trying to figure out how to access the headers that were sent by a node-fetch request. When i do this, for example:
const response = await fetch('http://playground.localhost')

The response object seems to contain only information about the response(like response headers, body, url, etc), without any "Request" object, like Axios exposes. In the latter you would be able to access the headers via response.request.headers.
Is there any way to show information about the actual request, and not just the response?

A: This might help: https://www.npmjs.com/package/node-fetch#accessing-headers-and-other-meta-data
    .then(res => {
        console.log(res.ok);
        console.log(res.status);
        console.log(res.statusText);
        console.log(res.headers.raw());
        console.log(res.headers.get('content-type'));
    });```


text:
Q: conditionally suppress field validation for SimpleSchema during Bulk Insert I am using Meteor 1.5 with MongoDB 3.2
I am using below Simple Schema to insert into Clients Collection.
import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';
SimpleSchema.extendOptions(['autoform']);

export const Clients = new Mongo.Collection('Clients');

ClientsSchema = new SimpleSchema({
  "gstNo": {
    type: String,
    label: "GST No.",
    regEx: /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/,
    optional: true,
  },
  "mobile": {
    type: String,
    label: "Mobile 1",
    regEx: /^[789]\d{9}$/,
  }
});

Clients.attachSchema( ClientsSchema );

With simple QuickForm using Aldeed's AutoForm 6.0 it works great.
Problem Scenario:
I perform Bulk Insert as I have Clients with count 3000. I Parse the "valid" excel sheet and then using loop I tried inserting data but the operation fails when regex did not match for Mobile No.
Question:
How to suppress SimpleSchema field validation when I perform "bulk insert" for a collection which already has a SimpleSchema attached to it? Also I want customer to put any Mobile no during Bulk Insert as User might not know the regex.

A: According to documentation you just have to suppress validation during your bulk insert:
Clients.insert(doc, { validate: false });

Added:
If you don't want to suppress the whole document validation, you can attach second schema to the same collection (with removed validation for particular field) and switch to it during bulk insert:
Clients.attachSchema(anotherSchema, { selector: { type: 'trustedMobile' } });
...
Clients.insert(doc, { selector: { type: 'trustedMobile' } });

Documentation for using multiple schemas.


text:
Q: How to get the current upload percentage using jquery + nodejs I m trying to upload a file using jquery, ajax, express and nodejs. Here I want to show the progress of upload. May be there is a plugin or something else. No need to post that answers. I want to study the technique behind that. So please help me if you know how to handle this. I have an ajax call to upload the file.
$.ajax({
    url:'/controller/action',
    //remaining parameters
});

A: I found this code. I think it will help you. Also you can use this plugin JQuery File Upload
this.uploadFile =  function(index) {
    //baseClass == this
    var file = baseClass.allFiles[index];

    //Creating instance of FormData
    var data = new FormData();
    //Adding file
    data.append('uploadFile', file.file);

    //Sending it with ajax
    $.ajax({
        url: '/',
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(response) {
            var message = file.element.find('td.message');
            if(response.status == 'ok') {
                message.html(response.text);
                file.element.find('button.uploadButton').remove();
            }
            else {
                message.html(response.errors);
            }
        },
        xhr: function() {
            var xhr = $.ajaxSettings.xhr();

            if ( xhr.upload ) {
                console.log('xhr upload');

                xhr.upload.onprogress = function(e) {
                    file.progressDone = e.position || e.loaded;
                    file.progressTotal = e.totalSize || e.total;
                    //updating downloading progress for the file
                    baseClass.updateFileProgress(index, file.progressDone, file.progressTotal, file.element);

                    //updating total progress
                    baseClass.totalProgressUpdated();
                };
            }

            return xhr;
        }
    });
};

A: you can use Multer to upload your file:
Multer


text:
Q: Can WSO2 IS 5.3.0 server generate SP metadata file ( for SAML2 SSO ) from the configuration I have configured the WSO2 IS 5.3.0 server to work with my application as the IDP of SAML2 based SSO system. Can I generate the metadata file from the configuration so that I could reuse it?

A: IS 5.3.0 doesn't support this option to download SP metadata as a file


text:
Q: return an attribute of the array   {{data.X}}\

scope.datas = [{ id: "1", name: "Moroni", startDate: '01/01/2012', homeLocation: "Houston"},
               { id: "2", name: "Dupont", startDate: '01/05/2011', homeLocation: "Johan"}];

I need to to get the attributes of my array (id, name, homeLocation) from the table
any idea?

A: Something along these lines:
{{ datas[0].id }}

Remember, whatever's in the brackets is just JavaScript.
Alternatively, you could use ng-repeat:

  {{ datum.id }}
  {{ datum.name }}
  {{ datum.homeLocation }}


text:
Q: How to create a clickable html table with php? I just tried creating a clickable table to show more information by clicking on a table row.
This is my code for the table creation:
while ($data= mysqli_fetch_assoc($query))
{
    echo "
";
    echo "" . $data['number'] . "	";
    echo "" . $data['name'] . "	";
    echo "
";
}

How can I create a click event on every specific table row which calls a function with the unique id of the entry?

A: while ($data= mysqli_fetch_assoc($query))
    {
    echo "
";
    echo "" . $data['number'] . "	";        echo "" . $datensatz['name'] . "	"; ?>

       <a href="yourprog.php?number=<? echo $data['number'] ?>&name=<? echo $data['name'] ?>" >
    	<?
    echo "
";
    }

A: There's lots of ways you can go about doing this.
The simplest way here would be to add an onclick listener to the row
while ($data= mysqli_fetch_assoc($query))
    {
        echo "
";
        echo "" . $data['number'] . "	";
        echo "" . $datensatz['name'] . "	";
        echo "
";
    }

And myfunction sends an ajax request or you preload the data and just display the data. The id serves as either mysql where clause or as a getter in case the data is preloaded


text:
Q: Making arrows parallel in commutative diagram in Tikz I would simply like to make all the arrows that should be parallel in my commutative square, actually parallel. Here is my diagram:

The outer square displays functions from the displayed domains and codomains. The inner square (the problem square) displays precisely the action of these functions on elements. I would like all respective lines to be parallel. Also, the right-bottom inner node invades into the outer node. How can I shift this away and get a proper square?
Here is my code:
\documentclass[12pt]{article}
\usepackage{pictexwd,dcpic}
\usepackage{amsmath,amsfonts,amsthm,dsfont,bbm}
\usepackage{tikz}
\usetikzlibrary{matrix,arrows,decorations.pathmorphing}
\usepackage{tikz-cd}
\usepackage{verbatim}

\begin{document}

\begin{tikzpicture}[baseline=(current  bounding  box.center), scale = 1.5]

\node (homa) at (2, 2) {$\text{hom}_{D}(a, a)$};
\node (homb) at (2,0) {$\text{hom}_{D}(a, b)$};
\node (Ta) at (6, 2) {$Ta$};
\node (Tb) at (6,0) {$Tb$};
\node (id) at (homa.south east) {$1_a$};
\node (f) at (homb.north east) {$f$};
\node (x) at (Ta.south west) {$x$};
\node (Tfx) at (Tb.north west) {$Tf(x)$};
\path[->]
(homa) edge node[left]{$\text{hom}_{D}(a, f)$} (homb)
(Ta) edge node[right] {$Tf$} (Tb)
(homa) edge node[above] {$\tau_a$} (Ta)
(homb) edge node[below] {$\tau_{b}$} (Tb);
\path[>=stealth,|->]
(id) edge (f)
(id) edge (x)
(f) edge (Tfx)
(x) edge (Tfx);
\end{tikzpicture}

\end{document}

I have used the (node.south west) prescription to position nodes in the inner square. I do want the nodes of the inner square to be just on the corners of the nodes of the outer square because the nodes of the inner square are members of the respective sets represented as nodes of the outer square.

A: An example with tikz-cd.
Output

Code
\documentclass{article}
\usepackage{tikz-cd}

\begin{document}
\[\begin{tikzcd}[row sep={6mm,between origins},column sep={1cm,between origins}]
hom_{D}(a,a) \arrow[rrrr, "\tau_{a}"] \arrow[ddd, "{hom_{D}(a,f)}", swap]
    & & & & Ta \arrow[ddd, "Tf"] \\
    & 1_{a} \arrow[rr, |->] \arrow[d, |->] & & x \arrow[d, |->] & \\[1cm]
    & f \arrow[rr, |->] & & Tf(x) \\
hom_{D}(a,b) \arrow[rrrr, "\tau_{b}", swap] & & & & Tb\\
\end{tikzcd}\]
\end{document}

A: For commutative diagrams I always use tikz's \matrix command together with matrix of math nodes. This gives an easy way of placing the nodes of your diagram into an array and then drawing lines between the nodes. To use this you need to have
\usetikzlibrary{matrix}

in your preamble. The basic idea is something like this:
\begin{tikzpicture}[auto]
  \matrix (M)[matrix of math nodes,row sep=1cm,column sep=16mm]{
     A&B\\
     C&D\\
   };
   \draw[->](M-1-1)--(M-1-2)--(M-2-2)--(M-2-1)--(M-1-1);
\end{tikzpicture}

which produces:

So you refer to the nodes as (M-<row>-<col>). The M is the first argument (M) to \matrix. You can make this whatever you like.
Normally the separation of the rows and columns, which is controlled by row sep=1cm,column sep=16mm, is constant for all rows and columns (again, choose the values to suit). For the OPs diagram we need to vary the spacing a little, which you can do with optional arguments inside the matrix as shown below. It is also good to specify that you want the row and column distances between origins as this leads to better spacing. The end result is:

Here is the code:
\documentclass{article}
\usepackage{mwe}
\usepackage{tikz}
\usetikzlibrary{matrix,arrows}
\usepackage{amsmath}

\begin{document}

  \begin{center}
    \begin{tikzpicture}[>=stealth,->,shorten >=2pt,looseness=.5,auto]
      \matrix (M)[matrix of math nodes,row sep={6mm,between origins},
                                       column sep={6mm,between origins}]{
        \hom_{D}(a, a)&      &[28mm] &  Ta\\% 28mm=extra space between cols 2&3
                      &  1_a & x     &    \\[16mm]% extra space between rows 2&3
                      &    f & Tf    &   \\
        \hom_{D}(a, a)&      &       & Tb\\
       };
       \draw[->](M-1-1)--node{$\tau_a$}(M-1-4);
       \draw[->](M-4-1)--node[below]{$\tau_b$}(M-4-4);
       \draw[->](M-1-1)--node[left]{$\hom_D(a,f)$}(M-4-1);
       \draw[->](M-1-4)--node{$Tf$}(M-4-4);
       % inner square
       \draw[|->](M-2-2)--(M-2-3);
       \draw[|->](M-3-2)--(M-3-3);
       \draw[|->](M-2-2)--(M-3-2);
       \draw[|->](M-2-3)--(M-3-3);
    \end{tikzpicture}
  \end{center}

\end{document}

Notice that I use \hom rather than \text{hom} for the hom-spaces. I have also used "stealth" arrows because I like them better.


text:
Q: Microsoft teams custom tab, sending notification to user's activity feed I'm designing a custom team tab using React that needs to send notifications to the users' activity feed. What is the best way to achieve this?
I'm aware of the existence of proactive messaging, is it the only way to do it? If it is, a pointer on how to implement it to a custom tab would be appreciated.
Or is there a better method to do it?

A: Yes, I think proactive messaging would be the best way. It means your app will need to feature a bot as well as the tab. To be clear, it's not your "tab" per se that would implement the messaging, rather your tab would call your backend/api, which would sent the proactive message via the bot to the notification feed. Regarding implementing it, give it a try first and post on this site if you have any questions/run into any trouble. (As a totally terrible plug, I'll be discussing proactive messaging later today, if you're interested, in a session at the TeamsDayOnline free event - see here for details).


text:
Q: Urban Airship Push code I've followed the UA tutorials and got my APID , and successfully recieved test push message on my android device.
Now the next thing that I like to do is to target my device using JAVA and send push messaged.
From what I've seen so far the best way to achieve this is using their web API.
However When I'm trying to send a post message I always get the following error :

java.io.IOException: Server returned HTTP response code: 401 for URL: https://go.urbanairship.com/api/push/
      at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
      at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
      at com.Sender.Sender.main(Sender.java:56)

This is the code that I use :
package com.Sender;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Sender {

/**
 * @param args
 */
public static void main(String[] args) {
    try {
        String responseString = "";
        String outputString = "";
        String username = "MWMoRVhmRXOG6IrvhMm-BA";
        String password = "ebsJS2iXR5aMJcOKe4rCcA";

        MyAuthenticator ma= new MyAuthenticator(username, password);

        Authenticator.setDefault(ma);

        URL url = new URL("https://go.urbanairship.com/api/push/");
        URLConnection urlConnection = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        String APID = "23eef280-19c8-40fc-b798-788f50e255a2";

        String postdata = "{\"android\": {\"alert\": \"Hello from JAVA!\"}, \"apids\": [\""+APID+"\"]}";
        byte[] buffer = new byte[postdata.length()];
        buffer = postdata.getBytes("UTF8");

        bout.write(buffer);
        byte[] b = bout.toByteArray();
        httpConn.setRequestProperty("Content-Length",
                String.valueOf(b.length));

        httpConn.setRequestProperty("Content-Type", "application/json");
        httpConn.setRequestMethod("POST");

        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);

        OutputStream out = httpConn.getOutputStream();
        out.write(b);
        out.close();

        InputStreamReader isr = new InputStreamReader(
                httpConn.getInputStream());
        BufferedReader in = new BufferedReader(isr);

        while ((responseString = in.readLine()) != null) {
            outputString = outputString + responseString;
        }
        System.out.println(outputString);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

}
Can you help me please ?

A: HTTP 401 represent Unauthorized access. In your code even though your created Authenticator, you didn't provide it as part of post request header. Here is tutorial on how to set authenticator for a URLConnection.


text:
Q: Most efficient design for these tables in Hadoop Hive? I have a huge dataset (1.5 TB compressed) already imported in HDFS. The data is divided in 3 collections: users, items and events. These collections are basically folders full of .bz2 files, each of which contains many records, in TAB separated format, one per row. The schemas are as follow:
users:

*

*id: string

*age: string

*sex: string
items:

*

*id: string

*data: string (JSON format)
events:

*

*user_id: string

*event_id: string

*time: bigint

*item_id: string

*pos: int

*city: string

*state: string

*device: string

*property: string

*interaction: int
I have several different queries I want to run on this dataset, most of them involve joining events and users or events and items on the corresponding *_id fields (which are foreign keys to said collections).
I have already imported all this data into HDFS and created external tables. The queries work but are extremely expensive. Particularly when involving the events table, whose compressed .bz2 files sum up to about 1 TB. I have very little experience with Hive, but I've read about partitions, clusters and indices. It seems that with a clever design, I can speed my queries, especially for joins.
My question is, what is your suggestion for an efficient design of the three tables? The queries I need frequently involve one the following operations:

*

*Joining events and users

*Joining events and items

*Joining all three tables

*Grouping or filtering by age, sex, state, city, or property (not at the same time) and aggregating

*Sorting and filtering by time and aggregating

I understand that perhaps not all of this can be accomplished efficiently with a single design, so I'm willing to create copies if necessary. I have around 18 TB of total available space in my cluster (I'm not accounting here for Hadoop's replication, so total space is actually less).
Data is static, i.e., it will not change in the future. For additional references, this is the Yahoo Y10 News Feed dataset.
Bonus: Ideally, if the data is stored in a format that is later easily accessible by Pig, even better!

A: Performance tuning is very specific to each case, there is no general solution, so you have to try many ways to get the best perf.
Here is some tips based on my experience, they are sorted starting by the most important :

*

*You need to buid your query that have a execution plan with the lowest number of MR jobs. If your query generate 4 MR jobs, it's not easy but its very efficient to make your query generate 3 MR jobs, you can use explain command for that.

*Consider partitioning your tables.

*A good choice for storage format for querying is ORC with SNAPPY compression.

*Use Hive join optimization

*Consider using Impala for querying and Hive for ETL.

There is a good idea that i didnt try it, its to make your dimension tables in HBase and the Fact one in Hive, you can read HBase data from Hive, see here.


text:
Q: How to make bash scripts print out every command before it executes? For example, I have a simple bash file
#!/bin/bash
cd ~/hello
ls

How can I make it display every command before executing it? Just the opposite effect of "@echo off" in windows batch scripting.

A: This should work:
set -o verbose #echo on
...
set +o verbose #echo off

A: set -o xtrace and set +o xtrace are your friends (it is more verbose, than -o verbose, and the output goes to STDERR, as opposed to verbose, which seems to log to STDOUT).
See more tips here

A: There are a few ways.
#!/usr/bin/env bash -x

as the shebang line.
Including set -x in the script itself will enable the functionality while set +x will disable it.
Both of these methods will also work with the more portable sh shell.
If I remember correctly perl also has the -x option.

A: These also work:
set -v

or
#!/bin/bash -v

But -v doesn't print the PS4 string before each script line and it doesn't trace the steps of a "for" statement (for example) individually. It does echo comments while -x doesn't.
Here's an example of the output using -v:
#!/bin/bash -v
# this is a comment
for i in {1..4}
do
    echo -n $i
done
1234echo

echo hello
hello

Here's the result of the same script with -x:
+ for i in '{1..4}'
+ echo -n 1
1+ for i in '{1..4}'
+ echo -n 2
2+ for i in '{1..4}'
+ echo -n 3
3+ for i in '{1..4}'
+ echo -n 4
4+ echo

+ echo hello
hello

Note that I included "echo -n" to add emphasis to the differences between -v and -x. Also, -v is the same as "-o verbose", but the latter seems not to work as part of a shebang.

A: bash -x script

or
set -x

in the script.
You can unset the option again with set +x. If you just want to do it for a few commands you can use a subshell: `(set -x; command1; command; ...;)

A: This should also work:
#!/bin/bash -x
cd ~/hello
ls

A: goes like
language -x script

language = python, perl, bash
-x = operator
script = filename
hope it helps.

A: #! /bin/bash -x does what you want.


text:
Q: How Do I relogin after getting a 401 back using URLSession and CombineAPI I'm new to combine and URLSession and I'm trying to find a way to log in after I get a 401 error back. My Set up for the URLSession.
APIErrors:
 enum APIError: Error {
  case requestFailed
  case jsonConversionFailure
  case invalidData
  case responseUnsuccessful
  case jsonParsingFailure
  case authorizationFailed

  var localizedDescription: String{
    switch self{
    case .requestFailed: return "Request Failed"
    case .invalidData: return "Invalid Data"
    case .responseUnsuccessful: return "Response Unsuccessful"
    case .jsonParsingFailure: return "JSON Parsing Failure"
    case .jsonConversionFailure: return "JSON Conversion Failure"
    case .authorizationFailed: return "Failed to login the user."
    }
  }
}

The CombinAPI itself, I'm trying to catch the 401 either in .catch or .tryCatch, but proving not as easy as I thought.
//1- A Protocol that has an URLSession and a function that returns a publisher.
protocol CombineAPI{
  var session: URLSession { get}
 // var authenticationFeed: AuthenticationFeed { get }

  func execute<T>(_ request: URLRequest, decodingType: T.Type, queue: DispatchQueue, retries: Int) -> AnyPublisher<T, Error> where T: Decodable
  //func reauthenticate<T>(_ request: URLRequest, decodingType: T.Type, queue: DispatchQueue, retries: Int) -> AnyPublisher<T, Error> where T: Decodable
}

//2 - Extending CombineAPI so we can have a default implementation.
extension CombineAPI {
 func authenticationFeed() -> URLRequest{
   return AuthenticationFeed.login(parameters: UserCredentials(userName: UserSettings.sharedInstance.getEmail(), password: UserSettings.sharedInstance.getPassword())).request
  }

  func execute<T>(_ request: URLRequest,
                  decodingType: T.Type,
                  queue: DispatchQueue = .main,
                  retries: Int = 0) -> AnyPublisher<T, Error> where T: Decodable{
    return session.dataTaskPublisher(for: request)
      .tryMap {
        guard let response = $0.response as? HTTPURLResponse, response.statusCode == 200 else{
          let response = $0.response as? HTTPURLResponse
          if response?.statusCode == 401{
            throw APIError.authorizationFailed
          }
          print(response!.statusCode)
          throw APIError.responseUnsuccessful
        }
        //Return the data if everything is good
        return $0.data
      }
      .catch(){ _ in
        //Try to relogin here or in tryCatch block

      }
    //      .tryCatch { error in
    //        if Error as? APIError == .authorizationFailed {
    //          let subcription = self.callFunction().switchToLatest().flatMap { session.dataTaskPublisher(for: request)}.eraseToAnyPublisher()
    //          return subcription
    //        }else{
    //          throw APIError.responseUnsuccessful
    //        }
    //      }
      .decode(type: T.self, decoder: JSONDecoder())
      .receive(on: queue)
      .retry(retries)
      .eraseToAnyPublisher()
  }

  func reauthenticate<T>( decodingType: Token.Type, queue: DispatchQueue = .main,retries: Int = 2) -> AnyPublisher<T, Error> where T: Decodable{
    return session.dataTaskPublisher(for: self.authenticationFeed())
      .tryMap{
        guard let response = $0.response as? HTTPURLResponse, response.statusCode == 200 else{
          let response = $0.response as? HTTPURLResponse
          if response?.statusCode == 401{
            throw APIError.authorizationFailed
          }
          print(response!.statusCode)
          throw APIError.responseUnsuccessful
        }
        //Return the data if everything is good
        return $0.data
      }
      .decode(type: T.self, decoder: JSONDecoder())
      .receive(on: queue)
      .retry(retries)
      .eraseToAnyPublisher()
  }

}

This is the feed that will create the URL request itself:
enum UserFeed{
  case getUser(userId: Int)
}

extension UserFeed: Endpoint{
  var base: String {
    return "http://192.168.1.15:8080"
  }

  var path: String {
    switch self{
    case .getUser(let userId): return "/api/v1/User/\(userId)"
    }
  }

  var request: URLRequest{
    let url = urlComponents.url!
    var request = URLRequest(url: url)
    switch self{
    case .getUser(_):
      request.httpMethod = CallType.get.rawValue
      request.setValue("*/*", forHTTPHeaderField: "accept")
      request.setValue("application/json", forHTTPHeaderField: "Content-Type")
      request.setValue(token,forHTTPHeaderField:  "tokenheader")
      print(token)
      return request
    }
  }
}

Then the client itself where you would create this would be in your viewModel, so you can make the web request for that type of data:
import Foundation
import Combine

final class UserClient: CombineAPI{
  var authenticate = PassthroughSubject<Token, Error>()

  var session: URLSession

  init(configuration: URLSessionConfiguration){
    self.session = URLSession(configuration: configuration)

  }

convenience init(){
    self.init(configuration: .default)
  }

  func getFeedUser(_ feedKind: UserFeed) -> AnyPublisher<User, Error>{
    return execute(feedKind.request, decodingType: User.self, retries: 2)
  }
}

I keep trying to make a new request to my authenticationClient, but it returns a different data type, so the ComineAPI doesn't like it. I'm not sure what I should do, otherwise, it works great until I have to authenticate, or get a new token? Any help would be appreciated, thanks.
I Just need it to log in, so I can save the new token to user settings and then continue on the request it left off with, If I can't get a new token, then I return an error to have the user login.

A: So if I understood correctly you want to be able to catch error 401 and send a different API request from the one you were previously using.
In that case you want to perform the following just as you wrote:
  func execute<T>(_ request: URLRequest,
                  decodingType: T.Type,
                  queue: DispatchQueue = .main,
                  retries: Int = 0) -> AnyPublisher<T, APIError> where T: Decodable{
    return session.dataTaskPublisher(for: request)
      .mapError { error in
          if error.statusCode == 401{
            return APIError.authorizationFailed
          }
          return APIError.someOtherGenericError
      }
      .map{$0}
      .decode(type: T.self, decoder: JSONDecoder())
      .catch(){ error in
           if error == .authorizationFailed {
                return session.dataTaskPublisher(for: request) // a new URLRequest that will call for the token generation.
           }

       }
      .receive(on: queue)
      .eraseToAnyPublisher()
  }

Now you can use the function catch, you need to return a publisher with the same value as you provided, meaning if you defined that you want a "User" object to be returned, then the catch new publisher will have to return the same type of object.
If you want to make it more generic, you can either handle the .catch request for generating token in the .sink closure, or maybe create a function specific for signing in and not using the generic one.
Sorry for giving so little choices, these solutions are the only things that came up from the top of my head.
Hope it helps.


text:
Q: Is it possible to transform python classes to cassandra object-model? I have following python class:
class Pet(Model):
  def __init__(self, id: int=None, name: str=None):
    self._id = id
    self._name = name

This python class was generated from a swagger spec. I want to transform this class to a corresponding cassandra object-model to be able to persist it. Cassandra object-model should look like:
class Pet(Model):
  id = UUID(primary_key=True)
  name = Text()

What is the best way to do it automatically knowing that I have a huge amount of classes to presist?


text:
Q: Element Cannot be Resolved as Variable error in a custom annotation for method interception New to Spring and AOP programming.  Working on a spring AOP tutorial to write aspects that intercept method calls.  Would like to enable time logging.
As instructed by the tutorial  I created a custom annotation for logging and an aspect to define what should be done when this annotation is called.
The code below is the TrackTime annotation:
package com.in28minutes.springboot.tutorial.basics.example.aop;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackTime {}

However Eclipse is displaying the errors –
"Element Cannot be Resolved as Variable/Retention Cannot be resolved to a variable"
I then created an aspect called MethodExecutionCalculationAspect with the 'TrackTime' annotation.
@Around("@annotation(com.in28minutes.springboot.tutorial.
basics.example.aop.TrackTime)")

MethodExecutionCalculationAspect
package com.in28minutes.springboot.tutorial.basics.example.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

@Aspect
@Configuration
public class MethodExecutionCalculationAspect {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

@Around("@annotation
(com.in28minutes.springboot.tutorial.basics.example.aop.TrackTime)")

    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

    joinPoint.proceed();
    long timeTaken = System.currentTimeMillis() - startTime;
    logger.info("Time Taken by {} is {}", joinPoint, timeTaken);
}

}
@Around uses an around advice. It intercepts the method call and uses joinPoint.proceed() to execute the method.
    @annotation(com.in28minutes.springboot.tutorial.basics.example.aop.TrackTime) is the pointcut to define interception based on an annotation — @annotation
followed by the complete type name of the annotation.
Once I correct the annotation and the advice, I'm hoping to use the annotation on methods for time tracking. as shown below:
@Service
public class Business1 {
    @TrackTime
    public String calculateSomething(){

Any help would be appreciated.
Information about the project is as follows:
SpringBootTutorialBasicsAplication.java:
The Spring Boot application class generated with Spring Initializer. This class acts as the launching point for the application.
• pom.xml: Contains all the dependencies needed to build this project using Spring Boot Starter AOP.
• Business1.java, Business2.java, Dao1.java, Dao2.java: Business classes are dependent on DAO classes.
• We would write aspects to intercept calls to these business and DAO classes.
• AfterAopAspect.java: Implements a few After advices.
• UserAccessAspect.java: Implements a Before advice to do an access check.
• BusinessAopSpringBootTest.java: The unit test that invokes the business methods.
• Maven 3.0+ is your build tool
• Eclipse.
• JDK 1.8+

A: Your TrackTime is missing imports for RetentionPolicy and Target.
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


text:
Q: Sumo random Trips Xml file not generating, As soon as the command randomTrips.py -n sumotest.net.xml -o sumotest.trips.xml is given pycharm is opening, Looking for help
Thanks,
Abhiram

A: Probably the file ending ".py" is not properly associated with the python executable. Try python randomTrips.py -n sumotest.net.xml -o sumotest.trips.xml.


text:
Q: How to finish a dungeon level? How do I finish a dungeon level? Am I obliged to kill all the monsters or are there other options?

A: By killing the monster(s) that is level 10. The level should register as completed, and you will be free to retire your character.


text:
Q: Automated web testing using shell script for Internet Explorer and Firefox I know I should be using other tools (like Selenium) for automated web tests but I have to use shell script. My problem is I need to open URLs in multiple IE and Firefox tabs. This is straight forward in Firefox but there doesn't seem to be any command line option to do this in IE. I need to be able to open one tab, wait, open another tab. Does anyone have any suggestions on how this could be achieved?
Thanks.

A: This can be done on Windows using JScript, basically you use the wscript (Bundled with IE) program to execute a JScript file that opens two instances of IE and then calls the method to open urls on these instance objects.
Another way of doing this is to dynamically write out a HTML file containing JavaScript that opens a URL then waits and then opens another URL etc.. and then when executing your browser of choice point it to the location of the HTML file. Example, iexplore.exe open_urls.html


text:
Q: Is a space first countable if and only if continuity and sequential continuity coincide? From what I understand, the point of first countability is to ensure sequences capture all topological information. It's not too difficult to prove that a set function from a first countable space to any space is continuous if and only if it's sequentially continuous.
My question is: does this equivalence characterize first countable spaces? I'm guessing it does but have no idea how to prove so.

A: It does not: it characterizes sequential spaces, as is noted in this answer. This isn't too hard to prove; once you get the definition of sequential space clear in your mind, you might try to prove it.
Sequential spaces are precisely those in which the convergent sequences completely determine the topology, so this is not really surprising. All first countable spaces are sequential, but there are many sequential spaces that are not first countable. Dan Ma's Topology Blog has a series of informative posts on sequential spaces, starting here.


text:
Q: Finite list of axioms of $\mathsf{ACA}_0$ - reference? It seems to be common knowledge that $\mathsf{ACA}_0$ can be finitely axiomatized, see for example
Can a finite axiomatization of PA be expressed in a finitely axiomatizable first order set theory?
However, I cannot seem to find a reference where $\mathsf{ACA}_0$ is given explicitly with the finite list of axioms. It is always defined as an extension of $\mathsf{PA}$ which already has an infinite axiom scheme.
Is there some reference giving the finite axiom list explicitly or is the above result of finite axiomatizability a non-constructive existential statement?
I hope this is the right place to ask for references. Delete this and PM/Mail me if not.

A: A finite axiomatisation for $\mathsf{ACA}_0$ is given by lemma VIII.1.5 of Simpson [2009], on pages 311–312. Fix a universal lightface $\Pi^0_1$ formula $\pi(e, m_1, X_1)$ with exactly the displayed free variables. Then we can give a finite axiomatisation of $\mathsf{ACA}_0$ as follows.
1) The basic axioms, essentially the axioms of Peano arithmetic minus the induction scheme (see definition I.2.4 on page 4 of Simpson [2009]).
2) A pairing axiom,
$$\forall{X}\forall{Y}\exists{Z} (Z = X \oplus Y).$$
3) $\Sigma^0_1$ induction in the form
$$\forall{X}(\neg\pi(e, 0, X) \wedge \forall{m}(\neg\pi(e, m, X) \rightarrow \neg\pi(e, m + 1, X))) \rightarrow \forall{m} \neg\pi(e, m, X)).$$
4) $\Sigma^0_1$ comprehension in the form
$$\forall{X}\exists{Y}\forall{m}(m \in Y \leftrightarrow \neg\pi(e, m, X)).$$
The universal $\Pi^0_1$ formula $\pi$ will of course be something of the sort discussed in Peter Smith's blog post.
S. G. Simpson. Subsystems of Second Order Arithmetic. Cambridge University Press, 2nd edition, 2009. doi:10.1017/cbo9780511581007.

A: I have a blogpost about this at http://www.logicmatters.net/2007/09/14/aca0-3-finite-axiomatizability/ (as has been pointed out!).
The finite axiomatization you get this way, however, is not particularly pretty or illuminating or, you might think, so "natural".


text:
Q: (Topology) To show inverse f is continuous. I know that for $X,\; Y$
  topological spaces
A map $f\,:\, X\rightarrow Y$
  is continuous iff for any open $u$
  in $Y$
 , $f^{-1}\left(u\right)$
  is open in $X$
 .
Then, to show $f^{-1}\,:\, Y\rightarrow X$
  is continuous,
can I say that for any open $u$
  in $X$
 , $f(u)$
  is open in $Y$
  ?

A: First, if $f$ is not bijective, then there is no function $f^{-1}: Y \to X$. So you need to assume this about $f$ to make any sense of your question. (There is always a map $f^{-1}: \mathcal{P}(Y) \to \mathcal{P}(X)$ which returns the inverse image of a subset of $Y$, but this is different from a map $f^{-1}: Y \to X$ inverting $f$; the notation is very confusing but is standard.)
Once you know that $f$ is bijective, then it's true that checking whether $f^{-1}$ is continuous is the same as checking that $f$ takes open sets to open sets, since $(f^{-1})^{-1}(U) = U$.
Note that $f$ being bijective and continuous does not imply that $f^{-1}$ is continuous; there are plenty of counterexamples, so this is something that has to be checked for each individual $f$.


text:
Q: Calculate the value of the expression for polynomial roots The roots of the polynomial equation: $ x ^ 3 - 3x -1 = 0 $ are: $ a, b $ and $ c $. Based on this, calculate the value of:$$ L = \frac {1} {a ^ 2-2a + 2} + \frac {1} {b ^ 2-2b + 2} + \frac {1} {c ^ 2-2c + 2} $$
Attemp:
$L=\frac{1}{(a-1)^2+1}+\frac{1}{(b-1)^2+1}+\frac{1}{(c-1)^2+1}$.
First, we want to find a polynomial whose roots are $a-1$, $b-1$ and $c-1$. This polynomial is just $(x+1)^3-3(x+1)-1=x^3+3x^2-3$. If we say the roots of this are $a'$, $b'$ and $c'$, we want to find $\frac{1}{a'^2+1}+\frac{1}{b'^2+1}+\frac{1}{c'^2+1}$.
Now we want to find what polynomial has roots $a'^2$, $b'^2$ and $c'^2$. In order to find what this polynomial is, we need to know $a'^2+b'^2+c'^2$, $a'^2b'^2+b'^2c'^2+c'^2a'^2$ and $a'^2b'^2c'^2$. $a'^2+b'^2+c'^2=(a'+b'+c')^2-2(a'b'+b'c'+c'a')=3^2-2(0)=9$. $a'^2b'^2+b'^2c'^2+c'^2a'^2=\frac{(a'^2+b'^2+c'^2)^2-a'^4-b'^4-c'^4}{2}$. To find $a'^4+b'^4+c'^4$, we can realize that $a'^3+b'^3+c'^3=(a'^2+b'^2+c'^2)(a'+b'+c')-(a'+b'+c')(a'b'+b'c'+c'a')+$ $a'b'c'(a'^0+b'^0+c'^0)=-3(a'^2+b'^2+c'^2)+3(a^0+b^0+c^0)=-18$, and similarly $a'^4+b'^4+c'^4=-3(-18)+3(-3)=45$. Our expression is therefore $\frac{(a'^2+b'^2+c'^2)^2-a'^4-b'^4-c'^4}{2}=\frac{81-45}{2}=18$. Also, it's easy to see $(a'b'c')^2=9$. Our polynomial is $x^3-9x^2+18x-9$
Our sum is the sum of the reciprocals of the $(x-1)^3-9(x-1)^2+18(x-1)-9=x^3-12x^2+39x-37$ which equals $\frac{39}{37}$
attemp2: I also think about using the logarithmic derivative you can think that
$\frac{1}{(1 - a) ^2} + \frac{1}{(1 - b)^2} + \frac{1 }{(1 - c)^2} = \frac{(p (1) p '' (1) - p '(1)^2) } {p (1 )^2} = 2$, then there must be some magical way to make that 1 appear by adding to the denominator, without having to appeal to polynomial transforms
Am I right? Is there an easier way to solve this problem?

A: This page gives a nice summary of common polynomial root transforms, which we can employ here.
First, let's find a polynomial that has roots that are $a-1, b-1, c-1$. This is just $$Q(x) = P(x+1) = (x+1)^3 -3(x+1) -1 = x^3 +3x^2 -3.$$
Next, we find the polynomial that has roots $(a-1)^2, (b-1)^2, (c-1)^2.$ This is
$$R(x) = -Q(\sqrt{x}) Q(-\sqrt{x}) = x^3 - 9x^2 + 18x - 9$$
Then, the polynomial having roots $(a-1)^2 + 1, (b-1)^2 + 1, (c-1)^2 +1$ is
$$S(x) = R(x-1) = x^3 - 12x^2 + 39x - 37.$$
We could find the polynomial that has roots that are the reciprocals of the roots of $S(x)$, however, we can apply Vieta to obtain that the sum is indeed $\frac{39}{17}.$
What you did is of course correct, but you were more explicit with these computations. These tricks are nice to know so you don't have to do all the work every time!
As for your second approach, it's not clear to me how to proceed. Maybe someone else could shed some light?


text:
Q: How to get Java Doc (In Eclipse) to pop up without having to wait for it to popup I'm more of an iOS developer, so I'm using the analogy of option clicking a variable to get the documentation to popup in xcode. It's quick and snappy.
In eclipse, if I want to read the documentation for a class/variable/method, I have to hold the mouse over the variable like a chump for 1-2 seconds, if I move the mouse I lose it and then it requires waiting again, and doesn't always come back, breaking every law of User experience ever written.
Just wondering if anyone knows the best way to configure eclipse with this stuff, I had a search in the preferences panel but the closest thing I found was hover, but that still didn't address the delay that I must wait when I'm just wanting to write code.

A: When your cursor is within the item you want to view the docs for, you should be able to open/focus them by pressing F2.


text:
Q: Robot Framework IDE Automate WPF I'm trying to automate an application I developed in C# (WPF) using Robot Framework.
I already explored a bunch of alternatives:
White Library

*

*https://github.com/Omenia/robotframework-whitelibrary

*https://github.com/TestStack/White
Doesn't seem to be working.
AutoItLibrary:

*

*https://pypi.org/project/robotframework-autoitlibrary/

*https://github.com/HW71/AutoItLibrary

*https://github.com/qitaos/robotframework-autoitlibrary
Doesn't work for WPF C# applications - Doesn't detect components
Sikuli

*

*https://github.com/rainmanwy/robotframework-SikuliLibrary

*http://rainmanwy.github.io/robotframework-SikuliLibrary/
Image detection doesn't work very well in WPF C# applications.
Has anyone been able to automate WPF C# applications using Robot Framework IDE?
Regards

A: We just released first stable version of WhiteLibrary. It should do the job.
https://github.com/Omenia/robotframework-whitelibrary
pip install --upgrade robotframework-whitelibrary

A: Unfortunately, WhiteLibrary is build on the White automation framework which has been deprecated since December 11, 2019. While WhiteLibrary itself is not officially deprecated, the last release is also from 2019.
There appears to be a newer framework called FlaUI, which is wrapped by RobotFramework-FlaUI. This project is still under active development currently and likely a more future-proof choice than WhiteLibrary.


text:
Q: Powershell 5.0 Invoke-Restmethod Sucess Statuscode I want to get the Satuscode when the HTTP returns code 200, i know there is way to use try , Catch but thats to catch error StatusCode, what is the way to catch the sucessfull status code 200 using Invoke-Restmethod in Powershell 5.1 ?
Any help is appreciated


text:
Q: ¿Una clase se registra como tipo antes de definir sus atributos y por eso puede tener un tipo de la misma clase como atributo? ¿Una clase se registra como un tipo antes de definir sus atributos y por eso puede tener un tipo de la misma clase como atributo?
Esto significa que primero se registra la clase y posteriormente se le registran los campos que van a tener asociados los objetos de esta?
class Persona{
    private Persona persona;
    private Persona2 atributo_persona2;

}

class Persona2{
   private String atributo;
}

Puedo tener una clase declarada abajo y sin embargo puedo declarar un objeto de esta como atributo en la clase de arriba
¿Como hace Java para resolver esto? ¿Registra la clase de arriba y luego asigna los atributos menos el que es objeto de la clase de abajo? y mientras tanto sigue compilando el código para ver ver si hay una clase con ese nombre para posteriormente registrarla y ahora si dejar registrado como atributo un objeto de esa clase en la clase que declare arriba?

A: Este tipo de comportamiento es normal. De hecho en la API puedes encontrar casos así, como es el caso de LinkedList.Node:
private static class Node<E> {
    E item;
    LinkedList.Node<E> next;
    LinkedList.Node<E> prev;

    Node(LinkedList.Node<E> prev, E element, LinkedList.Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

Fíjate que lo que no ocurre es que se referencie a sí mismo en el constructor, es decir, lo que sí está prohibido es:
public class Stub {
    private Stub stub;

    public Stub(Stub stub) {
        this.stub = this;
    }
}

Te saltaría un StackOverflow.

A: En el caso planteado se permite esa sintaxis ya que java, en tiempo de compilación, reconoce el tipo de dato puesto como atributo de la clase. Será en tiempo de ejecución y al momento de instanciar ese atributo  private Persona persona = new Persona(); en donde te encontrarás con un StackOverFlowError.


text:
Q: Person name format globalization I have the first, last and middle names in a database and want to display them.  My first thought is to display: last, first middle but I figured that other languages/cultures probably use different formats and separators.
Does anyone know of a formater that will handle this on a culture basis?  Ideally part of .Net.

A: Instead of looking for formatter, assuming UI (or email template or whatever) is going to be translated, just externalize the pattern and use Format method:
        string firstName = "Paweł";
        string lastName = "Dyda";
        // externalize this pattern
        string firstLastNamePattern = "{0} {1}";
        string displayable = string.Format(firstLastNamePattern, firstName, lastName);

In other words, let the Translator decide how she/he want to translate it, i.e. Hungarian Translator would use "{1} {0}".

A: I'm with Pawel Dyda on this but I'd would go further still.
When you have complex data structures that need localization you'd be wise to wrap these things to support any scenario.
Now, when I say complex data structure, I'm not trying to complicate things, but what you tend to realize going international is that every country has their own way of doing things. Things like names, addresses, phone numbers that are largely culture specific need to be treated as such and you should have a presentation layer in your application that gets this. It should also be highly customizable if you wanna be successful.
The culture specific stuff in .NET is great, to some extent, but it's not enough to rely on composite formatting strings.


text:
Q: django- Use prefetch_related inside of another prefetch_related Closest thing to what I am asking can be found here
Say I have the following models:
class Division(models.Model):
    name = models.TextField()
    state = models.IntegerField()

class Team(models.Model):
    name2 = models.TextField()
    division = models.ForeignKey(Division, ...)

class Player(models.Model):
    name = models.TextField()
    hometown = models.IntegerField()
    team = models.ForeignKey(Team, ...)

Now I can already do the following for just one table:
players = Player.objects.prefetch_related('team')

How would I go about adding state to the queryset? My endgoal is to be able to do player.team.division.state inside of a template. The other alternative would be to use nested for loops but I would like to avoid that.

A: You don't need prefetch_related here. You can follow the foreign keys from Player to Team to Division using select_related().
players = Player.objects.select_related('team__division')

A use-case for prefetch_related is if you started with a Division queryset, and wanted to fetch the related teams at the same time.


text:
Q: How to make an element opaque in CSS without specifying the background? Can I make an element opaque (impossible to see content underneath it), without specifying the background color (should "inherit" it from whatever is beneath it)?
Example:

  Front div

  Back div

top half obscured by front div

Gives the desired effect, but only because I set background: white. I'd like the effect to work without having to specify the background color, so it'd work anywhere. But by default, not having a background obviously doesn't work.
As written, if the page is body { background: white; }, then the effect works. But if the page is body { background: green; }, then the div is  still white, but I'd want it to be green.

A: Rather than trying to cover the element, you could modify the opacity of the element that you're trying to hide.

body{
  background: green;
}
div{
  padding: 15px;
  background: red;
  opacity: .1;
}

 Hello world

A: use inherit.

body { background:green;}

  Front div

  Back div

top half obscured by front div

A: Use background-color: inherit; in that div.
Note that by explicitly specifying the background-color property rather than the more general background, it will iirc apply the solid color inherited the parent element to the background (even if the parent element happens to be transparent, the inherited background colour will still have a value), thus making the element opaque.


text:
Q: How can I allow a specific section to have multi selection? I'm working on step by step order, and I am so thankful for having received plenty of help from others already. I'm still not done asking, though!
My steps are divided into different
 and I would like to give a
 a class="multiple" to allow this specific section to have multiple selections. I use .selected to determine either the if
 has been selected or not.
This is my current code:
$('li').on('click', function(e) {
   e.preventDefault();
   // remove selected class from links after the current one
   $(this).closest('section').nextAll('section').find('li').removeClass('selected');
   // remove selected from siblings, toggle current selected class
   $(this).siblings('li').removeClass('selected').end().toggleClass('selected');
   var $target = $('#' + $(this).attr('data-id'));
   if ($target.length) {
       // hide any steps after the current one that may be shown
       $(this).closest('section').nextAll('section').find('.step').not($target).removeClass('active');
       // toggle display of selected step
       $target.toggleClass('active', $(this).hasClass('selected'));
   } else {
       console.log('do something else to end this thing');
   }
})

So my question is, what can I do with my code to make
 allowing multiple selected items?
This is my JSFiddle. Click on the items to get the last step, which should be the section that allows multiple selections.
Thanks for the help.

A: Among the possibilities I like these two approaches:

*

*Assign class="single" to previous sections and create two similar functions, one triggered on $('li .single').on('click',function(e)... and the other with $('li .multiple').on('click',function(e)....  The first you already have it. Modify the second taking $(this).siblings('li').removeClass('selected') out so you can select multiple items.

*Second option would be to keep the single '$('li .single').on('click',function(e)...' but put actions on the scope of an IF/THEN to check if the user clicked on a single or multiple section and again don't $(this).siblings('li').removeClass('selected') if inside the .multiple section

A: Check for .multiple before removing the .selected class from the menu li's. https://jsfiddle.net/979aL2g5/7/

$('li').on('click',function(e) {
  e.preventDefault();
  var $parent = $(this).closest('section')
  // remove selected class from links after the current one
  $parent.nextAll('section').find('li').removeClass('selected');
  // remove selected from siblings, toggle current selected class
  $(this).toggleClass('selected');
  (! $parent.hasClass('multiple')) && $(this).siblings('li').removeClass('selected');
  var $target = $('#'+$(this).attr('data-id'));
  if ($target.length) {
    // hide any steps after the current one that may be shown
    $parent.nextAll('section').find('.step').not($target).removeClass('active');
    // toggle display of selected step
    $target.toggleClass('active', $(this).hasClass('selected'));
  } else {
    console.log('do something else to end this thing');
  }
})
body { color: #333; }
h1 {
  font-size: 20px;
}
.step {
  display: none;
}
.active {
  display: block;
}
.selected {
  background: #27ae60 !important;
  color: #fff !important;
}
ul {
  padding:0;
}
li {
  list-style: none;
}
.bananas {
  padding: 20px;
  color: #7f8c8d;
  background: #ecf0f1;
  display: inline-block;
  border-radius: 10px;
  cursor: pointer;
  width: 25%;
  text-align: center;
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 5px;
}
.bananas.special.selected {
  background: #3498db !important;
}

.hi {
  color: #27ae60;
  border-bottom: 2px dotted #27ae60;
}
h1 {
  margin-top: 30px;
  margin-bottom: 30px;
}
.hi.special {
  border-bottom: 2px dotted #3498db;
  color: #3498db;
}

#same_target {
  margin-top: 30px;
  background: #9b59b6;
  padding: 20px;
  color: #fff;
}

#same_target p {
  margin-bottom:0;
}

.nomarking {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

First step, please choose something

          Sprite

          King Kong

          Astronauts

Second step for Sprite - choose another

          McDonalds

          Burger King

          Tim Hortons

Second step for King Kong - choose another

          McDonalds

          Burger King

          Tim Hortons

Second step for Astronauts - choose another

          McDonalds

          Burger King

          Tim Hortons

Multiple selections section - choose under

          Hamburger

          Coffee

          Stackoverflow

          Australia

          Oldschool

          Deadpool

A: I would change this:
// remove selected from siblings, toggle current selected class
$(this).siblings('li').removeClass('selected').end().toggleClass('selected');

to this:
// remove selected from siblings if not multiple
if (!$(this).closest('section').hasClass('multiple')) {
    $(this).siblings('li').removeClass('selected');
}
// toggle current selected class
$(this).toggleClass('selected');


text:
Q: Volume of this solid of revolution? I'm currently taking Calculus II as an undergrad, and I am having a lot of issues understanding solids of revolution. Unfortunately neither my professor or my textbook has been much help and I'm feeling very "black boxed"--that is, when the formula doesn't work I am completely lost as to how to fix it.
The current problem I am having difficulty with is the following:
The area bounded by the y-axis and the curves $x=1+(y-2)^2$ and $x=2$ is rotated about the x-axis. Find the volume of the solid created by using the method of cylindrical shells.
I have attempted this problem and got the following integral: $ \int_1^2 (2 \pi)(y)(1+(y-2)^2dx $, which evaluates to $\frac{23 \pi}{6}$. The textbook gives the answer as $\frac{16 \pi }{3} $ with no explanation for this answer. I am completely lost and could really use an explanation of why my integral isn't working and what will work.

A: For this problem, the region is in the first quadrant, and it is bounded on the left by part of a parabola opening to the right, and on the right by a vertical line. Its bottom tip is the point $(2,1)$, its top tip is the point $(2,3)$, and its left-most point is $(1,2)$.
Since it's being revolved around the $x$-axis, we could either use a $dx$ integral with the "washers" method, or else a $dy$ integral with the "shells" method. The first option would have us cut up the region into vertical slices, expressing the edges as functions of $x$, which seems annoying. The second option allows us to use the fact that we already have the left and right edges expressed as functions of $y$.
We need to integrate from bottom to top, i.e., from $y=1$ to $y=3$. The integrand, with the shell method, is given by the cylindrical lateral area formula: $A=2\pi r h$. We have $r=y$, and $h=2-(1+(y-2)^2)$, because that's the right edge, minus the left edge. Putting that together, we get:
$$\begin{align}
\int_1^3 2\pi\cdot y\cdot(2-(1+(y-2)^2) \,dy &= 2\pi\int_1^3 y(2-(1+y^2-4y+4))\,dy\\
&=2\pi\int_1^3 y(-3+4y-y^2)\,dy\\
&=-2\pi\int_1^3 y^3-4y^2+3y\,dy\\
&=-2\pi\left[\frac{y^4}{4}-\frac{4y^3}{3}+\frac{3y^2}{2}\right]_1^3\\
&=\frac{16\pi}{3}
\end{align}$$
Does this help?

A: The first thing you want to do is to plot the function and evaluate what you have (see the figure below). The washer method tells us that for rotation about the $x$-axis,
$$V=\pi\int_1^2(y_1^2-y_2^2)~dx$$
where
$$
y_1,y_2=2\pm\sqrt{x-1}\\
\begin{align}
y_1^2-y_2^2
&=(2+\sqrt{x-1})^2-(2-\sqrt{x-1})^2\\
&=8\sqrt{x-1}
\end{align}
$$
Then,
$$V=\pi\int_1^2(y_1^2-y_2^2)~dx=\pi\int_1^2 8\sqrt{x-1}~dx=\frac{16\pi}{3}$$

A: Looking at the graph we can see that the "top function" is $x=2$ and the bottom function is $x=1+(2-y)^2$ in your integral you forgot to account for the 2 functions. These intersect when $y=1$ and when $y=3$ so our shell formula is $2\pi\int_{a}^{b}y(f(y)-g(y))\,\mathrm{d}y$ plugging in all our values we get$2\pi\int_{1}^{3}y(2-(1+(2-y)^2)\,\mathrm{d}y$ Also in the future, a valuable strategy that I learned when functions are given in terms of $x=f(y)$ as opposed to the typical $y=f(x)$ as far as the integration and volume goes you can just swap the $x$'s and $y$'s in order for you to get a better mental picture of the region, all the bounds will be the same and if done correctly you'll get the same answer


text:
Q: How Matlab calculates the camera view angle? I am using matlab to visualise a scene. In order to zoom in the scene, I can do that by eather:
- Fix the cameraposition and the cameratarget and change the cameraviewangle.or
- Fix the cameratarget and the cameraview angle and moving the camera along the viewing line (defined by the cameraPosition and the cameraTarget).
I know how to set the values of cameraposition CameraTarget and viewangle, but I do not how to define the optimal view angle. In auto mode of cameraviewangle, matlab calculate the smalest view angle that capture all the scene from the specefied camera position. I appreciate any help in understanding this.
Iman

A: In MATLAB the camera view angle is basically the same as a "zoom" function because there is no perspective distortion. The smaller the view angle, the more the image is effectively magnified because the viewport is enlarged to fit the size of the figure window.
The documentation of 'camva' includes this example which creates two push-buttons to zoom in/out of a scene:
% Set the range checking in the callback statements to keep
% the values for the camera view angle in the range greater
% than zero and less than 180.
uicontrol('Style','pushbutton',...
  'String','Zoom In',...
  'Position',[20 20 60 20],...
  'Callback','if camva <= 1;return;else;camva(camva-1);end');
uicontrol('Style','pushbutton',...
  'String','Zoom Out',...
  'Position',[100 20 60 20],...
  'Callback','if camva >= 179;return;else;camva(camva+1);end');
% Now create a graph to zoom in and out on:
surf(peaks);

So if you want to zoom, adjust the view angle. If you want to automatically "zoom" to fit the entire scene, set:
camva('auto');

A: I may be oversimplifying this, but shouldn't it boil down to geometry? If you have the location of your camera relative to your scene, you should be able to use the width of the scene to determine the angle necessary to include all of it. For example, if your scene of width 'w' is distance 'd' away from your camera while viewed at a right angle, the minimum viewing angle required can be derived using the law of sines:
alpha=arcsin(w/sqrt(d^2+(w/2)^2))

So from the image:

Your camera would be positioned at C, and your scene width 'w' would be the line segment AB. The distance 'd' from your camera to your scene would be the line segment CD, and the minimum viewing angle would be ACB.


text:
Q: Maven repo for BigInsights / IOP I have a IBM BigInsights 4.2 cluster installed and I am trying to create native yarn jobs.
To compile the java code on my laptop (not on the cluster), I need the hadoop client libraries.
How can I get the hadoop java libraries for IBM BigInsigths 4.2 (IOP)?
At the same time, my java project use Maven. Is there a Maven repo for the BigInsights 4.2 (IOP) java libraries?


text:
Q: PHP: break file into lines only if they end with commas I have a PHP api that receives an uploaded .sql file and needs to break it into single queries and execute them one by one.
I tried doing
$queries = file( $_FILES['file']['tmp_name'] );

The problem is that the file can contain queries written on multiple lines that would get broken. So I tried
$queries = explode( ';'.PHP_EOL, file_get_contents($_FILES['file']['tmp_name']) );

The problem is now that PHP_EOL represents the end of line symbols for the server system, and the uploaded file may represent new lines in a different way.
How can I reliably break an .sql file content into an array of queries?