text:
Q: Dynamically added rows, setOnClickListener TextView I have a for loop that each time prints out a row with a TextView within. I want this TextView to be clickable, and when clicked it is supposed to start another activity and send an ID with the Intent. But it's this that I can't manage to work. All links shows up nicely in a table and the textviews are clickable, but all links sends me to the next activity with the same ID, the ID of the last link.
Here is a simplified version of the content of the for loop:
TextView title = new TextView(this);
title.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
title.setText(titleLine);
title.setClickable(true);
title.setId(rows);
rows++;

title.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        Intent myIntent = new Intent(a.this, b.class);
        myIntent.putExtra("id", idLine);
        a.this.startActivity(myIntent);
    }
});

contRight.addView(title);

I suppose the problem is that all textViews looks the same, so the last setOnClickListener works on all links. However, I have added an ID to each title, with this code: title.setId(rows);, so they are all supposed to be unique.
Anybody who can give some help? :) Thanks!

A: Shouldn't idLine be v.getId()? It's good for this value to be as "fresh" as possible so that you aren't reading an old value: in this case, the value of the last row which had probably been lurking in idLine. Hence, getting the value from the view directly is the safest method.
Also, the "tag" might be a better place to store information than the id. You can access the tag, and indeed store any number of arguments as tags on any view, without changing the id:
title.setTag(rows);

and then later:
intent.putExtra((Integer) v.getTag());

To store multiple objects (with keys) you can use:
title.setTag("rowid", rows);

and then retrieve it using:
intent.putExtra((Integer) v.getTag("rowid"));

and then you could add additional keys if you requirements changed.
In any case, the intention of the tag is to store information for later retrieval, whereas the id is meant to serve as an identifier for finding views in a hierarchy.


text:
Q: Understanding circular dependencies in ES6 I'm trying to create a sort of API. For that reason, there's the case where I try to import the main file (that exposes the API), which includes an export, of the file where the import call is coming from!
Confusing? Great!
Project structure:
/
/src
/src/js
/src/js/modules
/src/js/modules/moduleA/index|actions|components|selectors
/src/js/modules/moduleB/index|actions|components|selectors
/src/js/modules/moduleC/index|actions|components|selectors

See the example below where I expose a circular dependencies that doesn't work!
So, here's how a modular exposes the API (which works easily when exporting outside the module itself):
// src/modules/foobar/index.js
import * as actions from './actions'
import * as components from './components'
import * as containers from './containers'
import * as constants from './constants'
import reducer from './reducer'
import * as selectors from './selectors'
export default { actions, components, containers, constants, reducer, selectors }

Here's the import:
// src/modules/foobar/containers/index.js
import API from '../index.js'
// this is undefined
console.log('API', API)

The goal?
ModuleAPI.actions.foobar()
ModuleAPI.containers.foobar()

While I can see that it might be a bad practice (and honestly it seems common sense that a file can't import itself) I'd like to understand why this is not possible!

*

*just found a good read about this ( https://medium.com/content-uneditable/circular-dependencies-in-javascript-a-k-a-coding-is-not-a-rock-paper-scissors-game-9c2a9eccd4bc )

*may be worth researching https://www.npmjs.com/package/circular-dependency-plugin

A: It's perfectly possible to import the top-level module like that. It just isn't possible to synchronously use it during the initialisation of the containers module. What happens is basically
load foobar/index.js
initialise foobar/index.js:
    load foobar/containers/index.js
    initialise foobar/containers/index.js:
        load foobar/index.js
        it's already getting initialised so don't wait
        set up scope
        execute module code: `API` is still undefined in the log statement
    finish initialisation of foobar/containers/index.js
    set up scope
    execute module code: `API` is getting defined now
finish initialisation of foobar/index.js

So as soon as you place the console.log(API) in a function and call it later, it'll work. Notice that with circular dependencies you need to take extra care that you always load the top level module first to get consistent evaluation order.

A: Well, this is more of a metaphilosophical problem: your module dependency actually turned into a cyclic graph, not a DAG/tree, so the module loading order cannot practically be dispatched by a topological sort, and this is known as a very hard problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Comparing file name to string I have hit a road block in a program I am writing in Java. The program basically copies folders and files from multiple locations into one folder to make backing up code from multiple locations on my computer easier. The problem I have is that I don't want to copy specific folders, in this case "workspace/.metadata". The start of the code I am having issues with is below:
public void copyFolder(File in, File out, String loc)
        throws IOException{

        String check = in.getName().substring(1);
        System.out.println("loc:"+loc+"check: "+check);
        if(loc.equals("java")){
            if(check.equals("metadata")){
                System.out.println("failboat");
                //statusBox.append("failboat");
            }
}

And this is the result I see:
loc:java
check: orkspace2
loc:java
check: metadata
loc:java
check: lock

I've had other's look at the code and they agree it should work. I've even created a replica of the code in a test file:
String test = "fmetadata";
    String loc = "java";
    String check = test.substring(1);
    if(loc.equals("java")){
        if(check.equals("metadata")){
            System.out.print("failboat");
        }else{
            System.out.println("WTF");
            System.out.print(test+ ": :"+check);
        }
}

And the result?
failboat

There is a dent in my desk the size of my forehead from trying to figure this out.

A: If that output you posted is the actual output:
loc:java
check: orkspace2
loc:java
check: metadata
loc:java
check: lock

It does not match the code you've pasted, as you do not print a newline between the two items:
System.out.println("loc:"+loc+"check: "+check);

If this is truly what you are seeing with that code then I would say the problem is that loc has a stray newline at the end, and is actually "java\n" rather than "java" as you expect. So you should go back and examine how you generate the value you pass through loc to begin with before calling that function.

If this is the case, some suggestions for diagnostics improvements that could help you notice these kinds of issues sooner (in addition to stepping through with a debugger):
// quote your strings to spot whitespace, print length to spot unexpected
// unprintable characters.
System.out.println("loc: \""+loc+"\" "+loc.length());
System.out.println("check: \""+check+"\" "+check.length());

And:
if(loc.equals("java")){
    // make sure you're getting to this point, don't assume that the first
    // if condition was satisfied:
    System.out.println("grumpycat"); // <----
    if(check.equals("metadata")){
        System.out.println("failboat");
    }
}


text:
Q: Create new worksheet for each column within one excel file in R I am trying to take an excel file I have (let's say it has 4 columns named "one","two","three","four" and the excel file is called "test") and make a separate worksheet for each column.
So within in my "test" file, I would have 4 worksheets. In the first worksheet would be the all of the values in column "one", the next worksheet would be all of the values in column "two", etc.
I tried using a loop like this:
for(i in 1:ncol(test)){
write.xlsx(test[i,,], file="filename.xlsx", sheetName=names(test)[i])
}

But it didn't work.
Any help is appreciated!!!

A: One concern is you have two commas in the bracketed data frame reference, and the first bracketed argument will grab the row not the column. Also, unlike data frames, vectors do not have column names:
colnames(mtcars[,1])
NULL

First, I'll show the openxlsx code I used to produce what I believe you wanted. Then I show code with the xlsx package given the corruption error you are seeing with openxlsx. I hope the comments express sufficiently what the code does.
openxlsx package version
library(openxlsx)
# Create the workbook data structure as wb
wb <- createWorkbook()
for(i in 1:ncol(mtcars)){
# shtname will be the ith column name in mtcars
  shtname = names(mtcars)[i]
# add a sheet to wb that is named the ith column name
  addWorksheet(wb, shtname)
# Turn the ith column vector of mtcars into a dataframe
# so we can give the object a column name
  mtcars_col_frm <-  data.frame(mtcars[,i])
  colnames(mtcars_col_frm) <- shtname
# write into that sheet the ith column of mtcars
  writeData(wb, i, mtcars_col_frm, colNames = TRUE)
}
# save all of the created sheets into a workbook
# Note that I used overwrite = TRUE to avoid
# "File already exists" error you may experience
saveWorkbook(wb, file="filename.xlsx", overwrite = TRUE)

xlsx package version
library(xlsx)
# Create the workbook data structure as wb
wb <- xlsx::createWorkbook()
for(i in 1:ncol(mtcars)){
  # shtname will be the ith column name in mtcars
  shtname = names(mtcars)[i]
  # add a sheet to wb that is named the ith column name
  sht <- xlsx::createSheet(wb, shtname)
  # Turn the ith column vector of mtcars into a dataframe
  # so we can give the object a column name
  mtcars_col_frm <-  data.frame(mtcars[,i])
  colnames(mtcars_col_frm) <- shtname
  # write into that sheet the ith column of mtcars
  xlsx::addDataFrame(x = mtcars_col_frm, sheet = sht, row.names = FALSE)
}
# save all of the created sheets into a workbook
xlsx::saveWorkbook(wb, file="filename.xlsx")


text:
Q: How to style table as flex-wrap but without flexbox My structure of HTML and CSS looks like:

.item {
  background: white;
  padding: 5px;
  display: inline-block;
  text-align: center;
}
.item > div {
  background: yellow;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: table-cell;
  vertical-align: middle;
}
table{
  width: 100%;
}

0

1

2

3

4

5

6

7

8

9

10

I would like to apply to table flex-wrap: wrap but I can't use flexbox or grid cuz I am working on email template where 'modern styling methods' are not supported, so I need to use table. So I need to use flex-wrap on this table but without using flexbox. I need this to prevent some responsiveness.
Current support of flex-wrap in email : doc

A:

table{
 display:block}
table td{
display:inline-block;}
.item {
  background: white;
  padding: 5px;
  display: inline-block;
  text-align: center;
}
.item > div {
  background: yellow;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: table-cell;
  vertical-align: middle;
}
table{
  width: 100%;
}

0

1

2

3

4

5

6

7

8

9

10


text:
Q: Changes to multiple variables within a function in Python 3.x being reset to default values Edit since apparently I wasn't specific enough, despite receiving an answer quickly.
I'm a beginning coder, so please bear with me if this is a painfully obvious/stupid error.
I'm coming into an issue with a project wherein I have starting values that change as they are processed through several different function calls. At a certain point in the program, I print all variables in order to see the changes made. (SPECIFIC PROBLEM OR ERROR>>) This is where I noticed that the variables revert back to their original values, despite being returned. Within the function that changes these variables, I did some testing and can see the variables change, so I'm unsure why the return is not working.
(SPECIFIC ERROR EXAMPLE>>)Here's some example code following my program to show you what I mean:
a = 1
b = 1
c = 1
z = 3

def main():
    othercode()

def calculations(a, b, c, z):
    print("a:", a)
    print("b:", b)
    print("c:", c)
    print("z:", z)
    while z > 0:
        check = str(input("Enter a, b, or c: "))
        if check == "a":
            a += 1
            z -= 1
            print("a:", a)
            print("z:", z)
        elif check == "b":
            b += 1
            z -= 1
            print("b:", b)
            print("z:", z)
        elif check == "c":
            c += 1
            z -= 1
            print("c:", c)
            print("z:", z)
        else:
            print("Invalid input.")
    return a, b, c, z

def othercode()
    a, b, c, z = calculations(a, b, c, z)
    print(a, b, c, z)

if __name__ == "__main__":
    main()

Now, this seems like it should work to me. (DESIRED OUTPUT>>) The output should be an increase in the variables a, b, and c and a corresponding decrease in the resource pool (z variable) depending on the user's inputs. The results I get are the same as those originally defined in main, and my IDE (PyCharm Community) gives me the message (SPECIFIC ERROR MESSAGE>>)"Statement seems to have no effect..."

A: Just provide all params to your functions, also fixed some other mishaps:
def main():
    a,b,c,z = 1,1,1,3
    othercode(a,b,c,z) # you need to provide those, the local ones here
                       # are not in scope if you call into othercode()

def calculations(a, b, c, z):
    print("a:", a)
    print("b:", b)
    print("c:", c)
    print("z:", z)
    while z > 0:
        check = input("Enter a, b, or c: ")  # removed superflous str w/o ending )
        if check == "a":
            a += 1
            z -= 1
            print("a:", a)
            print("z:", z)
        elif check == "b":
            b += 1
            z -= 1
            print("b:", b)
            print("z:", z)
        elif check == "c":
            c += 1
            z -= 1
            print("c:", c)
            print("z:", z)
        else:
            print("Invalid input.")
    return a, b, c, z

def othercode(aa,bb,cc,zz):    # missing : in this line, also use given params
                               # to avoid scoping problems
    aaa, bbb, ccc, zzz = calculations(aa, bb, cc, zz)
    print(aaa, bbb, ccc, zzz)

if __name__ == "__main__":
    main()


text:
Q: Store objcets in singleton class Is it good idea store my data objects in static variables of singleton class? I have class AppEngine where are some data static e.g. boolean int and instances of my classes (Configuration etc.)
When these objects are destroyed?
If I want to use them I call it something like this:

MyEngine.getMyEngine().getConfiguration().method(arg);

A: no no no dude just put null in that object like this
singltonclassobject = null;

it will destroy. :)


text:
Q: More than one showFields in lookup column When we create lookup column OOTB, there is option "Add a column to show each of this additional fields", so that we can have more than one show fields in list for that lookup.
But how to do same thing if we are creating List by visual studio?
Please have a look at following screenshot for more ref.

A: To setup the additional field from the lookup, you need to add a second lookup field pointing at the same list, but include the FieldRef attribute on the second lookup field. The value of this attribute should be the same as the ID attribute of the first lookup field.
<Field ID="{5D184D01-082C-4831-8757-CA2C98F05221}" Name="Title" DisplayName="Title" Type="Lookup" Required="FALSE" Group="<GROUP>" ShowField="Title" List="Lists/EmpConfiguration"></Field>

Additional field can be added as follows:
<Field ID="{393F697A-7F99-488E-B67F-41DFD6D41857}" FieldRef="{5D184D01-082C-4831-8757-CA2C98F05221}" Name="EL" DisplayName="EL" Type="Lookup" Required="FALSE" ShowField="ID" List="Lists/EmpConfiguration"></Field>

Notice the ID of first field and FieldRef id of second field is same.


text:
Q: Trying to insert dashes between 2 odd numbers.Error: Illegal return statement function insertDash(str) {

    var arr = str.split("");

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

        if (arr[i] % 2 != 0 && arr[i + 1] % 2 != 0) {

            var x = arr.splice(i + 1, 0, '-');

        }

    }

    return arr;

}

console.log(insertDash("99999"));

A: You can use a String#replace with a regular expression with a lookahead:

function insertDash(string) {
    return string.replace(/([13579](?=[13579]))/g, "$1-");
}

console.log(insertDash("99999"));
console.log(insertDash("1122334455"));

The other option is to use Array#reduce to create the string:

function insertDash(string) {
    return string.split('').reduce(function(s, c, i, arr) {
      return s + c + (c % 2 && arr[i + 1] % 2 ? '-' : '');
    }, '');
}

console.log(insertDash("99999"));
console.log(insertDash("1122334455"));

A: You could iterate from the end of the array, because you probably insert a dash and the array gets a new length.
If you start at the end, you change not the length of the items which are eligible to test and for inserting a dash.

function insertDash(string) {
    var array = string.split(""),
        i = array.length;

    while (i--) {
        if (array[i] % 2 && array[i + 1] % 2) {
            array.splice(i + 1, 0, '-');
        }
    }
    return array.join('');
}

console.log(insertDash("99999"));
console.log(insertDash("1122334455"));


text:
Q: JavaScript: replace non breaking space and special space characters with ordinary space I was trying to debug a problem of searching inside a string and it came down to the following interesting piece of code.
Both "item " and "item " seem equal but they are not!

var result = ("item " === "item ");

document.write(result);
console.log(result);

After investigating this further by pasting it on a Python interpreter, I found out that the first "item " has a different kind of space as "item\xc2\xa0". Which I think is a non breaking space.
Now, A possible solution to match these strings will be to replace \xc2\xa0 with space, but is there a better approach to convert all special space characters with normal space?.

A: In ES2015/ES6 you can use the String.Prototype.normalize() method to decompose both characters to the same simple space character:

const normalize = str => str.normalize('NFKD');
console.log(normalize("item\u0020") === normalize("item\u00a0"));

A: The space in the first string is character code 160 (a non-breaking space), and the space in the second string is character code 32 (a normal space), so the strings aren't equal to each other.

console.log("item ".charCodeAt(4), "item ".charCodeAt(4));

is there a better approach to convert all special space characters with normal space?.

You can match space characters which aren't tabs or newlines and replace with a normal space:

const makeSpacesNormal = str => str.replace(/(?=\s)[^\r\n\t]/g, ' ');
console.log(makeSpacesNormal("item ") === makeSpacesNormal("item "));

Specifically, the \s will match a whole bunch of space-like characters:
[\t\n\v\f\r \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]

and by matching and replacing those (except newlines and tabs, if you want), you'll be left with ordinary spaces.

A: trim will remove all whitespace from the beginning and end of a string. If you want to compare two strings while ignoring leading and trailing whitespace, trim both of them.
"item ".trim() === "item ".trim()


text:
Q: sorting a list by key then value in python I have a list whose keys is the date and the value is the hour of that day a sample looks like this
dtlist = [{'26/12/2010','01'},{'27/3/2008','00'},{'7/7/2007','10'},{'7/7/2007','23'}]

The output that I should get is
dtlist= [{'7/7/2007','10'},{'7/7/2007','23'},{'27/3/2008','00'},{'26/12/2010','01'}]

I want the date to be sorted by year, month, day and when the date is the same sort by hour in increasing order. Many thanks.

A: You have a list of unordered set litterals. I'm assuming you actually want to use something else, like a list of lists, or a list of tuples.
Here's how you can do it with a list of lists, or a list of tuples:
a = [['26/12/2010','01'],['27/3/2008','00'],['7/7/2007','10'],['7/7/2007','23']]

def k(a):
    d = list(map(int, a[0].split("/")))
    return d[::-1] + [int(a[1])]

print(sorted(a, key=k))

outputs:
    [['7/7/2007', '10'], ['7/7/2007', '23'], ['27/3/2008', '00'], ['26/12/2010', '01']]
The key function returns the key for an item in the list, which is then used by the sorting function to sort the list.
In this example your input data corresponds to these keys:
items: [['7/7/2007', '10'], ['7/7/2007', '23'], ['27/3/2008', '00'], ['26/12/2010', '01']]
keys:  [[2007, 7, 7, 10],   [2007, 7, 7, 23],   [2008, 3, 27, 0],    [2010, 12, 26, 1]]

We thus sort by year, followed by month, followed by day, and lastly hour.


text:
Q: Story where deep future humans are colonising the galaxy and are about to destroy the home of a reptilian civilisation I'm fairly sure the story was called 'Dinosurs', and its main human character was a very tall humanoid called Drill.
He lived alone on a ship except for a thing made out of sex organs.
He arrives on a world to be terra-formed and starts introducing earth lifeforms, such as sharks to the oceans. However the planet is inhabited by a race of civilized reptiles at about the equivalent of 21st century Earth.
They petition Drill to stop the destruction of their world but he says sorry he can't and if they make more trouble soldiers will be dispatched to deal with them. I think they do and the last thing is soldiers arrive in 40 mile long ships to kill them all.
The end.
I think it was featured on the best science fiction audiotape from like 1995, but I cant find a thing about it anywhere. Does anyone know what it might be?

A: You were very close.  Dinosaurs by Walter Jon Williams.  From Asimov's, June 1987.


text:
Q: A theorem for n similar n-gons When I studied the conjecture 2, I found a generalization:
Conjecture: Let $A_{i1}A_{i2}...A_{in}$ for $i=1,2,..,n$ be a regular n-gons, such that $A_{i1} \rightarrow A_{i2} \rightarrow ....\rightarrow A_{in} $ all counter clockwise, (or all clockwise). Let $G_j$ be the centroids of n-polygon $A_{1j}A_{2j}...A_{nj}$ for $j=1,2,...,n$. Then show that: $G_1G_2...G_n$ is a regular n-gon. In the figure as attachted n=6.

A generalization: Let $A_{i1}A_{i2}...A_{in}$ for $i=1,2,..,n$ be $n$ similar n-gons, such that $A_{i1} \rightarrow A_{i2} \rightarrow ....\rightarrow A_{in} $ all counter clockwise, (or all clockwise). Let $G_j$ be the centroids of n-polygon $A_{1j}A_{2j}...A_{nj}$ for $j=1,2,...,n$. Then show that: $G_1G_2...G_n$ form a $(n+1)$ th similar n-polygon.

A: Put $\omega:=e^{2\pi i/n}$. Then there are complex numbers $z_k$ and $c_k$ with
$$A_{kj}=z_k+c_k\omega^j\quad(1\leq k\leq n, \ 1\leq j\leq n)\ ,$$
and your "averaged polygon"  has vertices
$$G_j:={1\over n}\sum_{k=1}^n A_{kj}={1\over n}\sum_{k=1}^n z_k+\left({1\over n}\sum_{k=1}^n c_k\right)\>\omega^j\ .$$
This shows that the "averaged polygon" is again regular.
The "generalization" can be handled similarly: Begin with
$$A_{kj}=z_k+c_k w_j\quad(1\leq k\leq n, \ 1\leq j\leq n)\ .$$
Here $z_k$ is the centroid of the $k^{\rm th}$ polygon, the $c_k$ are complex stretching factors, and the $w_j$ with $\sum_{j=1}^n w_j=0$ determine the common shape of the polygons.


text:
Q: Heating Nitinol while driving LED Edited in my LED module current requirements, fixed needed resistance and added a schematic to better illustrate what I'm trying to do. Thanks Tom and asmydolf.
Okay, it might seem like a dumb thing to do, but I'd like to light up a LED at the end of a conductive wire, which in turn I would like to heat up. The conductive wire is Nitinol, which is used to move the LED to a new position, hence the reason for driving them together. The LED is right now a module, rated 12V and 0.36W, so it should require 0.03A, and the Nitinol wire is 0.1mm Dia., and 30cm long. I made some calculations, and to heat to Nitinol wire in 5 seconds I need 0.35A, 36 Ohm, which will create 4.4W - meaning a reasonably priced resistor can be found for that. I thought of running both the Nitinol wire and the LED in parallel, as I hope my sketch will show. Alas, just running the LED module at the end means no heating, and when I place a potentiometer across the LED terminals to divide the current I either short out the LED while heating the Nitinol wire, short out the wire while driving the LED, or getting the potentiometer burning while trying to do both...

simulate this circuit – Schematic created using CircuitLab
Anyway, any and all help on the matter will be greatly appreciated, I'm trying to help my wife's project off the ground in between my exams, and I was never really good with electricity.
Thanks,
Uri

A: You say you need 4.4W, at 0.35A inside the wire, so that makes 12.6V (rounded).
But, if your wire is only 2.9Ohm, that would mean (P = V^2 / R):
V = sqrt(P * R) = sqrt( 4.4W * 2.9 Ohm ) =~ 3.57V
I = sqrt(P / R) = sqrt( 4.4W / 2.9 Ohm ) =~ 1.23A
I'll use my values for voltage and current, but leave you with the thoughts and formulae so you can redo it if you are 100% sure you were right about 0.35A (impying 12.6V for the wire, making about 24V for the total).
That means, if the LED module needs 12V, means the wire+LED should be powered with 12V + 3.57V =~ 15.6V, but 15V would probably do well enough.
You then need to adapt the LED end to handle the 1.23A, of course it normally wants only 20mA maximum, the module has an internal resistor that makes that happen for 12V, but if you power it through the wire with 15V, the wire will not add much resistance (2.9Ohm you say ?), which will cause the internal resistor to not limit enough any more, and the LED will in the best case be brighter with a slightly shorter life span (or die in the worst case, depends on how many chips and what resistor).
So you need to put an extra resistor in parallel to the LED that steals away 1.21A at 12V.
From R = V / I =~ 12V / 1.21A =~ 9.9 Ohm.
But that resistor needs to then be: P = I * V =~ 1.21A * 12V =~ 15W
Which means it will also dissipate a lot of heat, and not be very small at all.
If your wire really is 2.9 Ohm and needs 4.4W to get hot enough for your aims, you should seriously consider replacing the LED module with one that has no internal resistor, or is set for 3.5V or such. That would at least allow you to make the resistor:
R =~ 3.5V / 1.21A =~ 2.9 Ohm
P =~ 3.5V * 1.21A =~ 4.3W (still a lot!)
As you can see, in either case you are much better off adding a thin extra wire (possibly loosely wrapped around the Nitinol wire??) to power the LED separately.


text:
Q: Changed my IPv4 to ssh into OpenWRT on rpi2 - did dhclient on my host afterwards- Now I have two IPv4 on one NIC - and it works! How? as described in the title, sorry I wanted to have a specific title and I could not get it specific and short and the same time, I did the following:

*

*Flashed a SD Card with OpenWRT to test it on a Raspberry Pi.

*OpenWRT has dhcp client disabled and puts a static IP in that image that does not correspond to my network IPv4 pattern.

*So I changed my host IPv4 to 192.168.1.2 in order to connect to 192.168.1.1. That worked.

*After logout I did dhclient on my host.

Now I have access to all my network devices as before and still can connect to that OpenWRT machine I described above. I only have one NIC on my host system. So I wonder how this can work?
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether *somevalue* brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.2/24 brd 192.168.1.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet 10.88.88.80/24 brd 10.88.88.255 scope global dynamic eth0
       valid_lft 863229sec preferred_lft 863229sec
    inet6 XXX/64 scope global dynamic mngtmpaddr
       valid_lft forever preferred_lft forever
    inet6 XXX/64 scope global dynamic mngtmpaddr
       valid_lft 7013sec preferred_lft 1613sec
    inet6 XXX/64 scope link
       valid_lft forever preferred_lft forever

A: Simply: this is achieved by the ability of the OS to assign several IPv4 addresses to the same interface and by the use of routing tables and ARP - The Address Resolution Protocol.
When a node (A) wants to talk to another node (B) knowing initially only the IPv4 address of B, first it consults its routing tables to find the shortest path to the destination (there might be much more complicated cases, e.g. round-robin policy, but for the simplicity we assume shortest path policy here).
At this point A knows two more things: a) which source address to use and b) is a gateway device (G) involved into exchange.
Then A checks if there is an entry for the B's IP address in its ARP cache table (if gateway to be used then A checks for and uses G's address here and in all subsequent requests).
If the cached entry exists then A picks the MAC address to send the IP packet to from this entry.
If there is no cached information, then A broadcasts the Address Resolution Request over the LAN segment to find out if someone knows the mapping of B(G)'s IP address into MAC address:
06:14:26.622107 7a:df:9c:b5:9a:ef > ff:ff:ff:ff:ff:ff, ethertype ARP (0x0806), length 42: Request who-has 192.168.8.145 tell 192.168.8.160, length 28
06:14:26.665609 ac:ed:5c:76:01:38 > 7a:df:9c:b5:9a:ef, ethertype ARP (0x0806), length 60: Reply 192.168.8.145 is-at ac:ed:5c:76:01:38, length 46

here is the host 192.168.8.160 tries to resolve a MAC address of 192.168.8.145. The response is sent back by any node who has the requested information. Please note, that the request is sent with broadcast MAC address (FF:FF:FF:FF:FF:FF) as destination address while the response is sent using unicast MAC address of the requester. This is to prevent flooding IP stacks of all nodes connected to the segment with unnecessary information.
Now the node A receives the response and populates the ARP cache with an entry for B, so next time A needs to send an IP packet to B it does not need to query the network again.
This way a node maintains the ability to talk to nodes on different IPv4 subnets physically connected to the same LAN segment using the same interface.
Note, please, that your 192.168.1.1 node has no idea that your 192.168.1.2 has another, extra IP address assigned to its ethernet interface.


text:
Q: ExtJS : How to map Store fields to JSON properties? I have the following JSON data :
{
  "disclaimer": "Exchange rates provided for informational purposes only and do not constitute financial advice of any kind. Although every attempt is made to ensure quality, no guarantees are made of accuracy, validity, availability, or fitness for any purpose. All usage subject to acceptance of Terms: https://openexchangerates.org/terms/",
  "license": "Data sourced from various providers; resale prohibited; no warranties given of any kind. All usage subject to License Agreement: https://openexchangerates.org/license/",
  "timestamp": 1475110853,
  "base": "USD",
  "rates": {
    "AED": 3.672983,
    "AFN": 66.5538,
    "ALL": 122.0421,
    "AMD": 473.5925,
    "ANG": 1.7763,
    "AOA": 165.571834,
    "ARS": 15.3169,
    "AUD": 1.299338,
    "AWG": 1.792667,
    "YER": 250.130999,
    "ZAR": 13.61321,
    "ZMK": 5252.024745,
    "ZMW": 9.831204,
    "ZWL": 322.387247
  }
}

And I have defined my model as follows:
Ext.define('CurrencyConvert.model.CurrencyCode', {
    extend : 'Ext.data.Model',
    fields : [
        {
            name : 'code',
            value : 'string'
        },
        {
            name : 'rate',
            value : 'float'
        }
    ]
});

So that I can have the currency code(i.e. "USD") and the rate. But the problem is that the currency code itself is the property name of the actual rate; so how would I create my store so as to get both the code and the rate in my model ?
Ex:
For "AED": 3.672983, I want the code value to hold "AED" and rate field to hold 3.672983.

A: You can do like this:

    Ext.define('CurrencyConvert.model.CurrencyCode', {
        extend : 'Ext.data.Model',
        fields : [
            {
                name : 'code',
                value : 'string',
                convert:function(v,rec){
                   === Add Your Logic Here ===
                }
            },
            {
                name : 'rate',
                value : 'float'
                convert:function(v,rec){
                   === Add Your Logic Here ===
                }
            }
        ]
    });

A: Ext.define('CurrencyConvert.model.CurrencyCode', {
    extend : 'Ext.data.Model',
    fields : [
        {
            name : 'code',
            value : 'string'
        },
        {
            name : 'rate',
            value : 'float',
            convert : function(value, record) {
                return jsonData.rates[record.get('code')]
            }
        }
    ]
});


text:
Q: The operator + is undefined for the argument type(s) java.util.Scanner How to remove this error ? please anyone help
I'm getting an error "The operator + is undefined for the argument type(s) java.util.Scanner"
don't know why is it showing this?
package com.learn.java;
import java.util.Scanner;

public class GradeCalculator {

    public static void main(String[] args) {

        System.out.println("Enter marks of MATHS");
        Scanner math = new Scanner(System.in);
        System.out.println(math.nextFloat());

        System.out.println("Enter marks of ENGLISH");
        Scanner eng = new Scanner(System.in);
        System.out.println(eng.nextFloat());

        System.out.println("Enter marks of SOCIALSCIENCES");
        Scanner socialScience = new Scanner(System.in);
        System.out.println(socialScience.nextFloat());

        System.out.println("Enter marks of SCIENCE");
        Scanner science = new Scanner(System.in);
        System.out.println(science.nextFloat());

        float avgMarks = averageCalculator(math, eng, socialScience, science);
        System.out.println(avgMarks);
        calculatePerformanceGrades(avgMarks);

    }

    private static float averageCalculator(Scanner math, Scanner eng,
            Scanner socialScience, Scanner science) {
        float averageMarks;
        averageMarks=((math + eng + socialScience + science) / 4);//getting an error here(The operator + is undefined for the argument type(s) java.util.Scanner)
        return averageMarks;

    }

    private static void calculatePerformanceGrades(float avgMarks) {
        if (avgMarks < 40) {
            System.out.println("Poor");
        } else if (avgMarks >= 40 && avgMarks < 59) {
            System.out.println("Average");
        } else if (avgMarks >= 60 && avgMarks < 79) {
            System.out.println("Good");
        } else if (avgMarks >= 80 && avgMarks < 89) {
            System.out.println("Very Good ");
        } else if (avgMarks >= 90 && avgMarks <= 100) {
            System.out.println("Excellent");
        }
    }
}

Please help to solve the issue.

A: You can't use scanner to add data and find an average later. You could just perform arithmetic operations on numbers i.e. integer, floating point numbers etc. Instead define your method to accept input data type like float (i would take double here instead)
private static float averageCalculator(float math, float eng, float socialScience, float science) {
 ....
}

While the input that you take from standard input i.e. Keyboard, you need to capture the value and send that value to your method averageCalculator like:
Scanner scanner= new Scanner(System.in);//define it once
float math = scanner.nextFloat();//store in a variable
System.out.println(math);
...

A: You are using scanner to perform arithmetic operations which cannot be done.
Instead pass float parameters to the method and do manipulations.
public static void main(String[] args) {

            System.out.println("Enter marks of MATHS");
            Scanner math = new Scanner(System.in);
            float math1=(math.nextFloat());

            System.out.println("Enter marks of ENGLISH");
            Scanner eng = new Scanner(System.in);
            float eng1 = eng.nextFloat();

            System.out.println("Enter marks of SOCIALSCIENCES");
            Scanner socialScience = new Scanner(System.in);
            float socialScience1= socialScience.nextFloat();

            System.out.println("Enter marks of SCIENCE");
            Scanner science = new Scanner(System.in);
            float science1=  science.nextFloat();

            float avgMarks = averageCalculator(math1, eng1, socialScience1, science1);
            System.out.println(avgMarks);
            calculatePerformanceGrades(avgMarks);

        }

        private static float averageCalculator(float math, float eng,
                float socialScience, float science) {
            float averageMarks;
            averageMarks=((math + eng + socialScience + science) / 4);
            return averageMarks;

        }

        private static void calculatePerformanceGrades(float avgMarks) {
            if (avgMarks < 40) {
                System.out.println("Poor");
            } else if (avgMarks >= 40 && avgMarks < 59) {
                System.out.println("Average");
            } else if (avgMarks >= 60 && avgMarks < 79) {
                System.out.println("Good");
            } else if (avgMarks >= 80 && avgMarks < 89) {
                System.out.println("Very Good ");
            } else if (avgMarks >= 90 && avgMarks <= 100) {
                System.out.println("Excellent");
            }
        }


text:
Q: Cannot find a mixed-strategy Nash equilibrium in a matrix I have the follow matrix, but whenever I try to calculate the probabilities, they are all.. equal? I can't deduce the formulas any more and I am incredibly confused since I don't think this is how it is done. Can someone point me out what I am doing wrong?

player 2:
3p+1(1-p) = 3p+1(1-p)
3p+1-1p = 3p+1-1p
player 1:
1q+3(1-q) = 1q+3(1-q)
1q+3-3q=1q+3-3q

A: This game has only a pure strategy Nash equilibrium of $(T, R)$. There is no reason to mix strategies because changing strategies can not improve either players reward. Note that this would technically be considered a trivial mixed strategy where for example player one plays $T$ with probability 1 and plays $B$ with probability 0.


text:
Q: Devise session controller failing after ruby upgrade on a /sign_in?locale=enpage managed by devise gem for authentication, the following error is generated:
undefined method `unshift' for nil:NilClass

from the log:
SyntaxError - syntax error, unexpected '{', expecting keyword_end
...ion only: [:create, :destroy] { request.env["devise.skip_tim...
...                              ^
/Users/deploy/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/devise-4.2.0/app/controllers/devise/sessions_controller.rb:5: syntax error, unexpected '}', expecting keyword_end
..."devise.skip_timeout"] = true }
...                              ^:
devise (4.2.0) app/controllers/devise/sessions_controller.rb:5:in `'

NoMethodError (undefined method `unshift' for nil:NilClass):

Rendered /Users/deploy/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/actionpack-4.2.10/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.1ms)

Error occurs with 2.5.3 not 2.4.5. The relevant line of the session controller  appears to be line 2, not 5 as per error message:
skip_before_filter :authenticate_user!, :only => [:create, :new]
#    skip_authorization_check only: [:create, :failure, :show_current_user, :options, :new]
respond_to :json

While this appears to be a syntactic issue  the error message alludes to devise code, not the application code.  Devise does not have a specific version established in the gemfile and bundle update has properly run its course.
What is a proper path to resolve this?


text:
Q: How do I change URL behavior for an Android browser Suppose there is a link to a tweet on some web page. When I click it, I want to view in my Twitter client app instead of inside the browser. How can I achieve that? Can I develop extensions to my Android browser (the stock one, Chrome, Dolphin, Firefox, etc)? Or there's another way to do that?
Another example is when I click on a LinkedIn profile link in my email, and it opens up a page saying "Get the App" and "Go the profile". How can I make the browser be aware that I already have the app, and it should really redirect me to the app and show the profile there? This probably is not about the browser but about the website and the individual apps. Let me know.
Update #1: I'm not clicking the link in some app developed by myself. It will be some app that I don't have control of.

A: If you want to open a URL in your app you need to take a look at Intent Filters. These will allow you to respond to a URL when the user clicks a link. In the case of Twitter the following would work,
<intent-filter>
    <action android:name="android.intent.ACTION_VIEW"/>
    <data android:host="twitter.com"/>
</intent-filter>

This way then the user attempts to open any twitter.com URL they will be presented with the app chooser.


text:
Q: How to suspend a thread without control over the loop in run method I try to make a class to play FLAC files. For this I use jFlac. So, for playing a song, I need to do:
Player p = new Player();
p.decode("PATH_TO_FLAC");

And I put that in the run() method of my class. If I start the thread, that's works. But I wonder how to make a pause. I have no control over the loop which is made in p.decode();, so I can't use wait and notify. But Thread.suspend() is deprecated. I don't know what to do.
My class:
public class FLACPlayer implements Runnable {
/**
 * Path of the song
 */
private String file;

private org.kc7bfi.jflac.apps.Player player;

/**
 * The thread launching the player
 */
private Thread playerThread;

/**
 * Constructor: initialize the player
 *
 * @param str
 *            The path of the file to play
 */
public FLACPlayer(String str) {
    file = str;

    player = new org.kc7bfi.jflac.apps.Player();
    this.playerThread = new Thread(this, "AudioPlayerThread");
}

public void play() {
    playerThread.start();
}

@Override
public void run() {
    try {
        player.decode(file);
    } catch (IOException | LineUnavailableException e) {
    }
}

Thanks!

A: In general, threads should be stopped by setting some variable (using appropriate synchronization) that's periodically checked by the thread. The thread is then in charge of stopping itself. The same goes for suspension -- they can check a variable and then sleep for a time.
Suspending a thread where the code is not under your control is dangerous, because you don't know what it's doing. Maybe it grabbed a bunch of network ports (just for a moment, it thought) and now you've suspended it and those ports are mysteriously unavailable. Maybe it's doing some real-time stuff, and when you resume it will be in a totally broken state.
That said, you should read and understand why Thread.stop and friends are deprecated. Basically, it's not because they are themselves broken, but because they frequently lead to broken code. However, if you understand the risks and the code you're working with, there's nothing inherently wrong with calling them.

A: You can't pause a Java thread, and you don't want to, anyway.
The code you are using is just a simple example application, which does not contain any method to pause playing. You should check the source for the Player class; the code contained there is more complicated, but gives you more control over the playback process, doubtless including also the ability to pause.

A: you can solve the issue by interrupting a thread. when you interrupt a thread it shall throw a interrupted exception, catch the exception and make a wait lock on a object there. when you want to resume, just call notify on the object.
Object lock=new Object();

@Override
public void run() {
    try {
        player.decode(file);
    } catch (InterruptedException e) {

      synchronized(lock)
      {
        lock.wait();
      }

    }

A: I think you have figure out your self how to implement this - But as Flavio suggested you can do the  following
This method in PCMProcessors should be overridden -
  public void processPCM(ByteData pcm) {
    synchronized (pcmProcessors) {

        int suspensionValue=0;

        Iterator it = pcmProcessors.iterator();
        while (it.hasNext()) {
          //DEFINE THE FLAG FOR SUSPENSION HERE - Logic should be block set ???

           PCMProcessor processor = (PCMProcessor)it.next();
            processor.processPCM(pcm);
        }
    }
  }

    DEFINE A Variable : volatile int flag=Threshold.Value

    Poll this from the main thread which kicks DECODE method

    Sleep and Resume for whatever time you want


text:
Q: Appending data to num query I'm using the following query to display pages whose URL's are stored in two different tables. (Actually, I'll soon have four or five joined tables.)
$sql = "SELECT SUM(num) as num FROM (
 SELECT COUNT(URL) AS num FROM gw_geog WHERE URL = :MyURL
 UNION ALL
 SELECT COUNT(URL) AS num FROM gw_world_urls WHERE URL = :MyURL
 ) AS X";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':MyURL',$MyURL,PDO::PARAM_STR);
$stmt->execute();
$Total = $stmt->fetch();

Of course, this query only returns 0, 1, 2, etc. I just wondered if it's possible to extract additional information from such a query.
For example, is it possible to modify it so that every page derived from table gw_geog has the value $MyKind = 'This', while every page derived from table gw_world_urls has the value $MyKind = 'That'?
Or suppose table gw_world has a field named Rank with various values, like 1, 2, 3. Is it possible to say that a URL derived from that table (e.g. arizona) has a rank of 2, where the row values are arizona | 2?

A: Im not sure I understand what you want. I think you want to count how many rows you have in x tables where URL field = something. Then you want to know if a specific row of these tables (e.g. the one from gw_world where url = arizona) have a specific value for rank.
Do you really need this in only one query? Because you will get many repeated "sum" fields.
You could make this query to count the results and another one to get all rows with their respective ranks.


text:
Q: Can a skin alter the hitboxes on a hero? Can different skins affect the hitboxes on heroes? For example, with Zenyatta, the Ifrit skin adds a headpiece. Is this now an area that can take damage?
Can skins increase the effective headshot hitbox?

A: No, all skins have the same hitbox. I've seen this from playing against Zenyatta using legendary skins.


text:
Q: How to add new tree item/folder in fuelux tree I'm using fuelux tree plugins, I need to add new item on the fly(not by reloading all tree data or refreshing a page), can any one give simple example how to do it?

A: At the moment, there is no direct way to do this since all data for the tree comes from its dataSource.  This would be a good suggestion to post at https://fuelux.uservoice.com/


text:
Q: Order of repetition per row and column in Python I have been trying to figure the order of repetition per-row and just couldn't do it. Ok. Lets consider a ndarray of size (2, 11, 10)
a = np.array([
    [
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 0, 0, 0, 1, 1, 1, 0, 0],
        [0, 1, 0, 0, 0, 1, 0, 0, 1, 0],
        [1, 1, 0, 0, 1, 1, 1, 1, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
        [1, 0, 0, 1, 0, 1, 1, 1, 0, 0],
        [1, 1, 0, 1, 1, 0, 1, 1, 0, 0],
        [0, 1, 1, 1, 0, 0, 1, 1, 0, 1],
        [1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 1, 0, 1, 0, 0, 1, 1],
        [0, 1, 1, 1, 0, 0, 1, 1, 0, 1]
    ],
    [
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 1, 0, 0, 1, 0, 0, 0, 1, 1],
        [0, 1, 0, 1, 0, 0, 0, 1, 0, 0],
        [1, 1, 0, 1, 0, 1, 1, 1, 0, 0],
        [1, 1, 0, 1, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 0, 0, 0, 1, 1, 0, 0],
        [1, 0, 0, 0, 1, 1, 0, 0, 1, 1],
        [1, 1, 1, 0, 0, 1, 1, 1, 0, 1],
        [1, 0, 0, 1, 1, 0, 1, 0, 1, 0],
        [1, 0, 0, 0, 0, 0, 1, 0, 0, 0],
        [1, 1, 1, 0, 0, 1, 1, 1, 0, 1]
    ]
])

What I wanted to is to get the order of every 1's per row based on a column. Whenever the first 1 is found in a row the order starts would start at 0; then goes to the second row if 1 is found here then the order is 1, but if the 1 is already present at the column index in the previous row, then it is ignored. For example
Lets consider these lists:
   0  1  2  3  4  5  6  7  8  9   -> column index
0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], -> no 1's no order here
1 [1, 1, 0, 0, 0, 1, 1, 1, 0, 0], -> order starts at 0
2 [0, 1, 0, 0, 0, 1, 0, 0, 1, 0], -> order starts at 1

At row index 0 there are no 1 so nothing happens, at row index 1 there are ones in column index [0,1,5,6,7] this will be equal to 0; the output should be
column   order
0         0
1         0
2         -
3         -
4         -
5         0
6         0
7         0
8         -
9         -

At row index 2 there are 1 at column index [1,5,8] whos order is 1; in there 1 and 5 are ignored because it already has an order 0 to it, but for the unknown order it should be 1; the final output should be
column   order
0         0
1         0
2         -
3         -
4         -
5         0
6         0
7         0
8         1
9         -

I have tried using Numpy's np.where method to the index values; something like this
index = np.asarray(np.where(a == 1)).T

I have no idea what to do next. Can anyone please help me?

A: Apparently, the desired result--based on comments on the question and an earlier version of this answer--is to find the "dense ranking" of the row index of the first 1 in each column.  (See the docstring of scipy.stats.rankdata for the meaning of "dense ranking".)   The result can be found using a combination of the .argmax() method and scipy.stats.rankdata.
Here's a function that computes the order for a two-dimensional array.  The question doesn't define what should happen when a column is all zeros; order assigns that column the value -1.
from scipy.stats import rankdata

def order(x):
    result = x.argmax(axis=0)
    result[(x == 0).all(axis=0)] = -1
    rank = rankdata(result, method='dense') - 1 - np.any(result < 0)
    return rank

For example, here is the array y:
In [71]: y
Out[71]:
array([[0, 1, 0, 0, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0],
       [1, 1, 1, 0, 1, 1, 0, 0],
       [1, 0, 1, 1, 1, 1, 0, 0],
       [1, 0, 0, 0, 1, 1, 1, 0]])

In [72]: order(y)
Out[72]: array([ 1,  0,  1,  2,  0,  0,  3, -1])

Here's the array a from the question:
In [73]: a
Out[73]:
array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 0, 0, 0, 1, 1, 1, 0, 0],
        [0, 1, 0, 0, 0, 1, 0, 0, 1, 0],
        [1, 1, 0, 0, 1, 1, 1, 1, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
        [1, 0, 0, 1, 0, 1, 1, 1, 0, 0],
        [1, 1, 0, 1, 1, 0, 1, 1, 0, 0],
        [0, 1, 1, 1, 0, 0, 1, 1, 0, 1],
        [1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 1, 0, 1, 0, 0, 1, 1],
        [0, 1, 1, 1, 0, 0, 1, 1, 0, 1]],

       [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 1, 0, 0, 1, 0, 0, 0, 1, 1],
        [0, 1, 0, 1, 0, 0, 0, 1, 0, 0],
        [1, 1, 0, 1, 0, 1, 1, 1, 0, 0],
        [1, 1, 0, 1, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 0, 0, 0, 1, 1, 0, 0],
        [1, 0, 0, 0, 1, 1, 0, 0, 1, 1],
        [1, 1, 1, 0, 0, 1, 1, 1, 0, 1],
        [1, 0, 0, 1, 1, 0, 1, 0, 1, 0],
        [1, 0, 0, 0, 0, 0, 1, 0, 0, 0],
        [1, 1, 1, 0, 0, 1, 1, 1, 0, 1]]])

The function order() expects a two-dimensional array, so we must use a loop to get the order for each subarray in a:
In [74]: np.array([order(m) for m in a])
Out[74]:
array([[0, 0, 3, 3, 2, 0, 0, 0, 1, 4],
       [2, 0, 3, 1, 0, 2, 2, 1, 0, 0]])


text:
Q: Binary Classification on Panel Data I have a Panel data set as below except with a lot more variables. Can I perform a classification to understand the chances that a student will leave the college ? I want to be able to classify the student with a probability that he/she will leave the college.
The dependent variable is a binary variable Yes / No.
Yes - Student has left the college without completion
No - Student is still enrolled
Graduated - This is another category which could be considered as student still with the college.
Some variables change over time, some don't. For example age of the student, economic status (student can move between localities), GPA.
Also some students commence course in 2016, some in 2017. So a student may have 3, 2 or 1 row, if I consider 3 years of data.
I was told to drop the Student ID column and treat the rows as independent of each other and run classification models like Random Forest. Would that be correct ?
Socio Economic Indicator is based on the locality a student lives at the time of data collection. If he or she moved to a different locality the following year, the Socio Economic Status may change.
If I have 1 row per student I could run Random Forest and oter classification algorithms. If I have panel data I understand Fixed Effects and Random Effects are he model used. Now, this suggestion of dropping student ID's and running classification models, doesn't seem right to me.


text:
Q: Storage Access Framework as a "Private" (local-only) Folder/File Picker? My ultimate goal is to allow the user to select a folder to save a file to - the file is a video file that will be created at some point after the user has chosen the destination.
I am simply using the storage access framework picker to allow them to select a location for it to be saved in.
First of all, is there a way to allow a user to select only a folder (and not a file/filename)?
The best I can do right now is use the ACTION_CREATE_DOCUMENT Intent in order to get a save location, however I do not really want to specify the filename in the SAF picker (this will be done back in the app)...
Secondly, after reading the Storage Access Framework documentation, and cobbling together some bits from a few code samples, I've got a working DocumentsProvider which almost does what I want - which is to allow the user to browse their external storage (SD Card) directories for a suitable place to save a video file - by adding my own root which points to Environment.getExternalStorageDirectory() to the queryRoots() method.
However, what I really want is for that to be my only root (at the minute I've also got Drive, Downloads etc.).
Is it possible to remove/hide other roots so it essentially becomes an application-specific file picker?
Or even show local storage only (perhaps the Root.FLAG_LOCAL_ONLY flag can help)?
Thanks!

A: API 21 supports Intent.ACTION_OPEN_DOCUMENT_TREE. This allows you to select the location once and then you can use the provided URI to manipulate its content.
private static final int LOCATION_CHOOSER_REQ_CODE = 4;

public void chooseLocation() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    startActivityForResult(intent, LOCATION_CHOOSER_REQ_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == LOCATION_CHOOSER_REQ_CODE && resultCode == Activity.RESULT_OK) {
        if (data != null) {
            Uri uri = data.getData();  // Use this URI to access files
        }
}


text:
Q: Numpy and Python compatibility Issues Currently using Kaggle to analyze datasets. I wrote this:
from learntools.core import binder
binder.bind(globals())

It throwed a peculiar error.
raise ImportError(
ImportError: Unable to import required dependencies:
numpy:

I'm using VS Code and a Conda environment to run it.
Python Ver: 3.9 (via Conda)
Numpy Ver: 1.21.5
I executed the same lines using python.exe located in the Anaconda folder, and it worked. But using that as an interpreter for VS produced the mentioned error.
Question: Are these two incompatible? If so, how can I fix it?


text:
Q: How to Extract Text from Body HTML I have an HTML element that displays text documents like so:
<embed src="Link" type="text/html" width="100%" height="427px" />

"Link" being the link to the text document in external storage.
The text in the document is displayed in the body of the page. I need to be able to extract the displayed text and send it out of the HTML element to the outer page be edited; however if I use:
document.getElementById("Body").innerHTML

It just displays the link to the document and not the text itself. Is there a way of copying the displayed text in the body, with code, to be edited?
Example of what is output:
<embed src="Link" type="text/html" width="100%" height="427px">

What should be output:
Text that is contained in the text file.


text:
Q: Lock specific columns on change event of a cell with header filter and sort enabled in excel There are 6 columns in the sheet, out of which first four are editable and last two columns should be locked.

On changing any cell value of Col1 to Col4, date/time should be updated in Col5 (created on) and Col6 (last updated).
I did the following:

    Private Sub Worksheet_Change(ByVal Target As Range)

    Dim myTableRange As Range

    Dim myDateTimeRange As Range

    Dim myUpdatedRange As Range

    'Your data table range
    Set myTableRange = Range("A2:D10")

    'Unprotect sheet
    ActiveSheet.Unprotect Password:="Test@pass"

    'Check if the changed cell is in the data table or not.
    If Intersect(Target, myTableRange) Is Nothing Then Exit Sub

    'Column for the date/time
    Set myDateTimeRange = Range("E" & Target.Row)

    'Column for last updated date/time
    Set myUpdatedRange = Range("F" & Target.Row)

    'Determine if the input date/time should change
    If myDateTimeRange.Value = "" Then

    myDateTimeRange.Value = Now

    End If

    'Update the updated date/time value
    myUpdatedRange.Value = Now

    'Protect sheet
    ActiveSheet.Protect Password:="Test@pass"

    End Sub

I am able to update Col5 and Col6 based on cell edited under Col1 to Col4, but sort and filter ability is lost of all Columns header.
How do i bring back the header sort and filter functionality after cell lock?

A: Whenever you protect a sheet you won't be able to sort the table any longer - although you chose the "AutoFilter"-option - this is kind of a bug. But Filtering should work ...


text:
Q: What exactly does a .net core api return to the browser? So I have this endpoint:
[HttpGet]
public async Task<ActionResult> Get()
{
   var ext = new ApiExtensions();
   List<Record> records = await ext.GetRecords();
   return Ok(records);
}

This is the Record object:
public class Record
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? DateCreated { get; set; }
    public string LastModifiedBy { get; set; }
    public DateTime? LastModifiedDate { get; set; }
}

Inspecting the results in Fiddler or Postman I get what I expect to see.
But both of these tools (Fiddler and Postman) give me the ability to "see" the data (body) returned by the api in different formats: text, raw, json, xml, etc. So, what exactly is the api returning to the client? Is it just the "raw" data as displayed in the raw tab? Or does it return the same data in different formats and it is up to the client to use the right one?
(I'm using .net core 3.1.)
Thanks.

A: ASP.NET Core MVC/API has support for formatting response data. Response data can be formatted using specific formats or in response to client requested format. The built-in helper method Ok returns JSON-formatted data:
    [HttpGet]
    public async Task<ActionResult> GetMovie()
    {
        return Ok(await _context.Movie.ToListAsync());
    }

You can using the F12 browser developer tools or Postman to check the response header, content-type: application/json; charset=utf-8 is displayed.

More detail information about response data format, see Format response data in ASP.NET Core Web API.

But both of these tools (Fiddler and Postman) give me the ability to
"see" the data (body) returned by the api in different formats: text,
raw, json, xml, etc

About the Fiddler and PostMan response body format, I think it is the tool's function, it is better to change the response body format.


text:
Q: Let $Q$ be a special orthogonal matrix. Show that $Q(u\times v)=Q(u)\times Q(v)$ for any vectors $u, v\in\mathbb R^3$.
Let $Q$ be a $3\times3$ special orthogonal matrix. Show that $Q(u\times v)=Q(u)\times Q(v)$ for any vectors $u, v\in\mathbb R^3$.

I have no idea how to start. I'm not sure if $Q(u)\cdot Q(V)=Q(u\cdot v)$ would helps. Please give me some help. Thanks.

A: The cross-product $u\times v$ is the unique vector such that
$$
\det(u,v,w)=(u\times v)\cdot w\qquad \forall w
$$
where $\det(u,v,w)$ is the determinant of the $3\times 3$ matrix whose columns are $u,v,w$ in this order, that  is the determinant of the linear map that sends the canonical basis to $(u,v,w)$. That's a common definition of the cross-product. See below if needed.
Recall that $Q$ special orthogonal means $Q^T=Q^{-1}$ and $\det Q=1$.

We need to prove that $Q^T(Qu\times Qv)=u\times v$. So let us compute
  $$
Q^T(Qu\times Qv)\cdot w=(Qu\times Qv)\cdot Qw=\det(Qu,Qv,Qw)=\det Q\det(u,v,w)=\det(u,v,w).
$$
  By the uniqueness defining $u\times v$, this proves $Q^T(Qu\times Qv)=u\times v$, i.e. $Qu\times Qv=Q(u\times v)$.

Note: the same argument shows more generally that, as mentioned by lhf and wikipedia,
$$
M^T(Mu\times Mv)=(\det M) u\times v\quad\Rightarrow \quad (Mu\times Mv)=(\det M) M^{-T}(u\times v)
$$
for every invertible $3\times 3$ matrix $M$, where $M^{-T}=(M^{-1})^T=(M^T)^{-1}$. The formula on the left is true for every matrix $M$ and is just $0=0$ in the singular case, since we have $Mu\times Mv=0$ for every $u,v$ in this case.

The fact that the identity $\det(u,v,w)=(u\times v)\cdot w$ is satisfied by every $u,v,w$ can be checked directly, by computations, from the determinant definition of $u\times v$. Another way to see it is to note that the map $(u,v,w)\longmapsto (u\times v)\cdot w$ is multilinear, anti-symmetric (or alternating), and sends the canonical basis to $1$, whatever definition of the cross-product you might have. So it must be the determinant. Uniqueness of $u\times v$ satisfying the identity follows from $(\mathbb{R}^{3})^\perp=\{0\}$, as $w_1\cdot w=w_2\cdot w$ for every $w$ implies $(w_1-w_2)\cdot w=0$ for every $w$, in particular for $w=w_1-w_2$, whence $\|w_1-w_2\|^2=0$.

A: Maybe it will be easiest to show this explicitly for the basis vectors $ \{ (1,0,0) \cdots \} $ , and then the general case follows from linearity of all things involved. It will be useful to note that if $ \vec{Q_1}, \vec{Q_2}, \vec{Q_3} $ are the column vectors of $ Q $, then the fact that $ \det(Q) = 1 = \vec{Q1} \cdot (\vec{Q_2} \times \vec{Q_3}) $ gives the "right hand rule" that $\vec{Q_1} \times \vec{Q_2} = \vec{Q_3} $.
Please note, I have been very sloppy and did not check the signs and orders of things. You should check that all formulae are indeed right.


text:
Q: Running js function from button and displaying I have made a function called "compare" and want to run it from a button with the id "start"
<input type="button" id="start" onClick="compare(userChoice, computerChoice)" value="Start">

but when it's pressed the function does not load, also I tried to display it in this
document.getElementById("score").innerHTML = compare(userChoice, computerChoice);

but the problem with it is that it starts as the page loads

<script>

        var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
 computerChoice = "rock";
} else if(computerChoice <= 0.67) {
 computerChoice = "paper";
} else {
 computerChoice = "scissors";
}

var compare = function(choice1, choice2){
  if(choice1 === choice2){
   return "The result is a tie!"
  }
  else if(choice1 === "rock"){
   if(choice2 === "scissors"){
    return "rock wins";
   }
   else{
    return "paper wins"
   }
  }

  else if(choice1 === "paper"){
   if(choice2 === "rock"){
    return "paper wins";
   }
   else{
    return "scissors wins"
   }
  }

   else if(choice1 === "scissors"){
   if(choice2 === "paper"){
    return "scissors wins";
   }
   else{
    return "rock wins"
   }
  }

};
document.getElementById("player").innerHTML = userChoice;
document.getElementById("computer").innerHTML = computerChoice;
document.getElementById("score").innerHTML = compare(userChoice, computerChoice) ;

</script>

Thank you for reading

A: your function compare returns a string, so, calling it from onclick will result in nothing happening, you haven't specified what you want to do with the return of the function
rather than all your "returns" in that function, you could replace them with
document.getElementById("score").innerHTML =

a better way would be something like
var compare = function() {
    var userChoice = prompt("Do you choose rock, paper or scissors?");
    var computerChoice = Math.random();
    if (computerChoice < 0.34) {
        computerChoice = "rock";
    } else if(computerChoice <= 0.67) {
        computerChoice = "paper";
    } else {
        computerChoice = "scissors";
    }
    var check = function () {
        if (userChoice === computerChoice) {
            return "The result is a tie!"
        } else if (userChoice === "rock") {
            if (computerChoice === "scissors") {
                return "rock wins";
            } else {
                return "paper wins"
            }
        } else if (userChoice === "paper") {
            if (computerChoice === "rock") {
                return "paper wins";
            } else {
                return "scissors wins"
            }
        } else if (userChoice === "scissors") {
            if (computerChoice === "paper") {
                return "scissors wins";
            } else {
                return "rock wins"
            }
        }
    }
    document.getElementById("score").innerHTML = check();
};

or even
var compare = function() {
    var userChoice = prompt("Do you choose rock, paper or scissors?");
    var computerChoice = Math.random();
    if (computerChoice < 0.34) {
        computerChoice = "rock";
    } else if(computerChoice <= 0.67) {
        computerChoice = "paper";
    } else {
        computerChoice = "scissors";
    }
    document.getElementById("score").innerHTML = function () {
        if (userChoice === computerChoice) {
            return "The result is a tie!"
        } else if (userChoice === "rock") {
            if (computerChoice === "scissors") {
                return "rock wins";
            } else {
                return "paper wins"
            }
        } else if (userChoice === "paper") {
            if (computerChoice === "rock") {
                return "paper wins";
            } else {
                return "scissors wins"
            }
        } else if (userChoice === "scissors") {
            if (computerChoice === "paper") {
                return "scissors wins";
            } else {
                return "rock wins"
            }
        }
    }(); // IIEF
};

(code edited based on comment question)
in both cases you can change the button to
<input type="button" id="start" onClick="compare()" value="Start"/>


text:
Q: How to generate a Twitter Bootstrap modal but keep it hidden I want to create a Twitter Bootstrap modal, but keep it hidden until I'm ready to show it.
Here is the smallest amount of code to demonstrate. It successfully creates the modal, but it applies display: block to it inline, overriding my style.
    modalHtml = '
'
        + '
'
        + '
Hello World

'

    modal = jQuery(modalHtml);

    modal.modal('show');

https://jsfiddle.net/Lx23xqbq/2/
I could add this
modal.modal('hide');

But this allows the modal to be visible for a split second.
How can I create a Twitter Bootstrap modal without displaying it to the user?

A: Modals are hidden via the CSS class .modal by default.
Remove modal.modal( 'show' );.
You have modal.modal( 'show' ); in your JS which causes the modal to be visible for a split second before you call modal.modal( 'hide' ).

Personally I would place the modal markup into the page before hand.

var $button = $('button');
var $modal = $('#myModal');

$modal.on('show.bs.modal', function(e) {

  // Optional. We update the modal with content stored in the data-content
  // attribute of the <button>.
  // You could also grab another hidden element to inject or perform
  // AJAX here.
  var content = $(e.relatedTarget).data('content');

  $modal
    .find('.modal-content')
    .text(content);

});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<button type="button" data-toggle="modal" data-target="#myModal" data-content="Hi Guy!">Show Modal</button>

Hello World

Injecting into the page wouldn't be much different.

var html =
  '
' +
    '
' +
      '
Hello World
' +
    '
' +
  '
';

// Append modal markup to page.
$('body').append(html);

var $button = $('button');
var $modal = $('#myModal');

$modal.on('show.bs.modal', function(e) {

  // Optional. We update the modal with content stored in the data-content
  // attribute of the <button>.
  // You could also grab another hidden element to inject or perform
  // AJAX here.
  var content = $(e.relatedTarget).data('content');

  $modal
    .find('.modal-content')
    .text(content);

});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<button type="button" data-toggle="modal" data-target="#myModal" data-content="Hi Guy!">Show Modal</button>

A:
How can I create a Twitter Bootstrap modal without displaying it to
  the user?

Technically you are already creating the modal with your first 2 lines of code. It just isn't displayed until the 3rd line (modal.modal('show');).
What I think you might be trying to accomplish is separating the code that creates the modal from the code that shows/hides it. The problem (I'm assuming) is that elsewhere in your code you no longer have a reference to the variable modal (that you created in modal = jQuery(modalHtml);), because it is out of scope.
Add this to your HTML page:

Update your Javascript as described below:
modalHtml = '
'
    + '
'
    + '
Hello World

'

// inject the modal markup into the hidden element on the page
jQuery('#hidden-modal').html(modalHtml);

// whenever ready, retrieve the hidden modal html and display it
jQuery(jQuery('#hidden-modal').html()).modal('show');

https://jsfiddle.net/Lx23xqbq/3/

A: If I understand your question this have to work:

$(document).ready(function () {

    draw();

});

function draw() {
  var html = ""
  html += '<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>';
  html += '
';
  html += '
';
  html += '
';
  html += '
';
  html += '
';
  html += '<button type="button" class="close" data-dismiss="modal">×</button>';
  html += '
Modal Header
';
  html += '
';
  html += '
';
  html += '
Some text in the modal.
';
  html += '
';
  html += '
';
  html += '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
  html += '
';
  html += '
';
  html += '
';
  html += '
';

  $('#modal').html(html);
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

When page is loaded the function draw() draws the modal and keep it hidden until you click the button, hyperlink, label or whatever you want.


text:
Q: find text in file and then when found take the word on same line and insert into code i want to insert the first word from file.txt when it matches string in my documents, i have like 500 documents like this so it would be nice if it works
file.txt looks like this:
test1 t1
test2 t2
test3 t3

this is my code
code="t1"

sed -i -e 's/^/Name="$code" /'

this will result in
code="t1"

sed -i -e 's/^/Name="t1" /'

this what i want for final output in all my documents:
document1.txt
code="t1"

sed -i -e 's/^/Name="test1" /'

document2.txt
code="t2"

sed -i -e 's/^/Name="test2" /'

A: I don't clearly understand your requirement. If you cant to extract the first word depending on the second word and then do some string manipulation, following might help.
file.txt content:
test1 t1
test2 t2
test3 t3

Extract first word, given the second word:
second="t1"                                       # change this for a different match
first=$(sed -n "s/\(.*\) $second/\1/p" file.txt)  # now $first is "test1"
echo "first word is ${first} and blah..."         # write it to a file or do anything you need here


text:
Q: Why my rpm installation hang while played remotely I have an AIX 6.1 server where I want to uninstall a rpm.
This uninstallation can be done directly on the server :
[user@server]$ sudo /usr/bin/rpm -e --allmatches _MyRPM-1.0.0

This uninstallation is working.
I have a script lauching this unstallation :
Uninstall.sh
#!/usr/bin/bash
set -x

sudo /usr/bin/rpm -e --allmatches _MyRPM-1.0.0

I can play this script on the server without any problem :
[user@server]$ cd /where/is/the/script;./Uninstall.sh
+ sudo /usr/bin/rpm -e --allmatches _MyRPM-1.0.0
_MyRPM-1.0.0 has been uninstalled successfully

But when I'm playing this script remotely the rpm hang :
[user@client]$ ssh user@server "cd /where/is/the/script;./Uninstall.sh"
+ sudo /usr/bin/rpm -e --allmatches _MyRPM-1.0.0

And this command hang, I need to kill it in order to end the ssh.
PS : I have exactly the same comportment for installation or uninstallation.
EDIT :
The problem seems coming from the sudo. The hang problem appears also when I'm doing anithing with a sudo.
For example with a new script :
test.sh
#!/usr/bin/bash
set -x

sudo env

A: Sudo normally requires a user authenticate as themselves, and if I recall it can act different via remote execution due to the way the terminal is handled.
I don't have a system to test this on at the moment, but but you could try ssh's -t or -T switches:
 -T      Disable pseudo-tty allocation.

 -t      Force pseudo-tty allocation.  This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services.
         Multiple -t options force tty allocation, even if ssh has no local tty.

I suspect you could get this to work by adding the script you're remotely executing into /etc/sudoers:
{user} ALL=NOPASSWD:/where/is/the/script/Uninstall.sh

Then try:
"ssh -t user@server /where/is/the/script/Uninstall.sh"

EDIT:
Found some details to help explain why sudo is behaving differently when executed remotely:
http://www.sudo.ws/sudoers.man.html

The sudoers security policy requires that
  most users authenticate themselves before they can use sudo. A
  password is not required if the invoking user is root, if the target
  user is the same as the invoking user, or if the policy has disabled
  authentication for the user or command.

Perhaps it's hanging because it's trying to authenticate, whereas locally it wouldn't need to do so.


text:
Q: Splitting Excel cell string while keeping font color formatting I have posted this question before but it was voted as too vague. So here I am trying again.
I have a cell with letters with different colors. Each letter is evenly spaced with one another (See below). I need to split them into separate cells with their color formatting intact using VBA.
The actual font colors are expressed in [] brackets
I need to split:
  |A                              |
1 |Alan[Red] Betty[Blue] Cass[Red]|

Into:
  |A           |
1 |Alan[Red]   |
2 |Betty[Blue] |
3 |Cass[Red]   |

I was only able to extract values in the original string but not the individual letter's formatting.
I've tried Text to Columns as well but all the split cells are not formatted. Even manual copy pasting does not work when only selecting partial string in the cell.
How can I accomplish splitting the string while keeping the color via VBA?
The code I used is part of a larger chunk of other things but the simplified logic is this:
Sub test()
Dim strLength As Long
Dim breakPos As Long
Dim spaceCount As Long

strLength = Len(Cells(1, 1))
spaceCount = strLength - Len(Replace(Cells(1, 1), " ", ""))

For i = 1 To spaceCount
    strLength = Len(Cells(i, 1))
    breakPos = InStr(1, Cells(i, 1), " ")
    Cells(i + 1, 1) = Right(Cells(i, 1), strLength - breakPos)
    Cells(i, 1) = Left(Cells(i, 1), breakPos - 1)
Next i

End Sub

A: This seems to result in what you describe.

*

*Split the cell into words

*Write the words to the new location

*Check the font of the original word and set that color to the new location

In your "production" code, you'll want to more strongly declare the workbook and worksheet, and you will probably be doing this on more than a single cell, so you'll probably need to add some loops and statements to adjust for different ranges than just A1 and A3 as you show in your question.
Option Explicit
Sub splitWithColor()
    Dim vStr As Variant, v
    Dim rSrc As Range, rRes As Range
    Dim I As Long, J As Long

'Note we are working with "active sheet"
'you should have stronger definitions in final product
Set rSrc = Range("A1")
Set rRes = Range("A3")

vStr = Split(rSrc.Value2)

Application.ScreenUpdating = False

Set rRes = rRes.Resize(UBound(vStr) + 1)
rRes.Value = WorksheetFunction.Transpose(vStr)
I = 0
J = 1
For Each v In vStr
    rRes.Offset(I)(1).Font.Color = rSrc.Characters(J, 1).Font.Color
    I = I + 1
    J = J + Len(v) + 1
Next v

End Sub

A: Try this code, please. Al words in the analyzed string must have the same font color for all their characters, they must be separated by spaces (" "). The result will be returned below the processed cell. In this example, below of active cell. If necessary, it can replace the selected cell, of course, but you cannot repeat the test for the same cell...
Sub splitByWordsKeepingFontColor()
  Dim c As Range, i As Long, arrRes As Variant, arrCol() As Variant
    Set c = ActiveCell: If c.Text = "" Then MsgBox "Emply cell selection...": Exit Sub
    arrRes = Split(c.Text, " ")
    If UBound(arrRes) = 0 Then MsgBox "No strings separated by space ("" "") exist in """ & _
                                                               c.Text & """.": Exit Sub
    ReDim arrCol(UBound(arrRes))
      For i = 0 To UBound(arrRes)
        arrCol(i) = c.Characters(InStr(c.Text, arrRes(i)), _
                                                    Len(arrRes(i))).Font.ColorIndex
      Next i
      c.Offset(1, 0).Resize(UBound(arrRes) + 1, 1) = _
                                    Application.WorksheetFunction.Transpose(arrRes)
      For i = 0 To UBound(arrCol)
        c.Offset(i + 1, 0).Font.ColorIndex = arrCol(i)
      Next i
End Sub


text:
Q: In PHP when using fgets() to read from file how to exclude "brake row" I'm writing simple function witch will read data from myfile.txt with fgets().
Content of file is something like:
1

2

3

4

Function to get first value (1):
$f = fopen ("myfile.txt", "r");
$mystring = fgets ($f);

Now, when I use $mystring to write in file like:
$f1 = fopen ("myfile2.txt", "w");
fwrite($f1, 'text' . $mystrin . 'more text');

text 'more text' goes to new row.
I want to have it in in same row with other text.

A: When reading a file using fgets() it will include the newline at the end. You only need to remove it.
$mystring = trim ($mystring);

This will remove any leading and trailing whitespaces.

A: $mystring = rtrim ($mystring, PHP_EOL);

Will remove any trailing newlines.


text:
Q: Could not run Hadoop cause it couldn't find java I am trying to start Hadoop on my CentOS 7 by command start-dfs.sh it shows me this ERROR:
JAVA_HOME /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.262.b10-1.el7.x86_64/jre/bin/java does not exist.
As the JDK is already installed I don't understand why Hadoop cannot find it.
Console Image


text:
Q: Need to export the python output of the below code to json (key : value) format file I am printing the column name, data type and the max length of the columns from an Excel file.
Below is the code and the output, need to export the output to the json file.
Excel file (assignment.xlsx):

      Type
      Amount received
      Currency
      Flag
      Date

      Educationsl
      1422.00
      USD
      2018-11-30

Output
Column Name : Type
Data type : String
Size  : 11

Column Name : Amountreceived
Data type : Float
Size  : 6

Column Name : Currency
Data type : String
Size  : 3

Column Name : Flag
Data type : String
Size  : 1

Column Name : Date
Data type : Float
Date format  : ddmmyyyy

Code
import string
import re
import datetime
import xlrd
loc = r"C:\Users\Documents\PythonStuff\assignment.xlsx"
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

for i in range(sheet.ncols):
    print ("Column Name : " + re.sub('[^A-Za-z0-9]+', '', sheet.cell_value(0, i).replace(' ','_')))
##Data Type
    if str(sheet.cell_type(1,i)) == '1':
        print  ("Data type : String ")
    elif isinstance(sheet.cell_value(1,i), float) == True:
        print  ("Data type : Float ")
    elif str(sheet.cell_type(1,i)) =='3':
        print  ("Data type : Date ")
## Date Format
    if str(sheet.cell_type(1,i)) =='3':
        print ("Date format  : " + "ddmmyyyy" +"\n ")
    else:
        print ("Size  : " + str(len (str(sheet.cell_value(1,i))))+"\n ")

Desired output
{"Excel": [{"Type": "Educational", "Amount received": "1422.00", "Currency": "USD", "Flag": "N", "Date": "2018-11-30"} ]}

A: I assume that you want to use the values of the 1st row as the dict keys and every row is an item in a the list. Add this to you code:
keys = [i.value for i in sheet.row(0)]
sheet_dict = {'Excel': list()}

for row in range(1, sheet.nrows):
    row_dict = {}
    for col in range(sheet.ncols):
        row_dict[keys[col]] = sheet.cell_value(rowx=row, colx=col)
    sheet_dict['Excel'].append(row_dict)

print(sheet_dict)

Or if you want a pretty output:
import json
print(json.dumps(sheet_dict, sort_keys=True, indent=4))


text:
Q: Calling uilabel animation with string variables swift I am trying to build a UILabel animation. I want to add a variable string to the function, so that i can call it together with the variable.
I try to use the code below but it gives me error message.
@IBOutlet weak var Text1: UILabel!

    let myText = Array("Hello World !!!".characters)
    var myCounter = 0
    var timer:NSTimer?
    func fireTimer(){
        timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "typeLetter", userInfo: nil, repeats: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
fireTimer()
        // Do any additional setup after loading the view.
    }

    func typeLetter(myText  :String){
        if myCounter < myText.count {
            Text1.text = Text1.text! + String(myText[myCounter])
            let randomInterval = Double((arc4random_uniform(8)+1))/20
            timer?.invalidate()
            timer = NSTimer.scheduledTimerWithTimeInterval(randomInterval, target: self, selector: "typeLetter", userInfo: nil, repeats: false)
        } else {
            timer?.invalidate()
        }
        myCounter++
    }

The error message is shown below

May I know what's the problem and how to solve this problem? Thanks

A: The problem there is that you need to choose a different name for your method parameter. Inside the method you cannot access your array count because your text parameter has the same name.

A: Your code has various problems.
As @luk2302 pointed out, your function typeLetter takes a parameter of type string, but string does not have a count property. You need to use string.characters to convert it to an array of unichars. Arrays do have a count property.
As @LeoDabus pointed out, you have 2 different variables myText. One is (I think) and instance variable of your view controller class (type [Character]) and the other is a parameter to your typeLetter function (type String). The typeLetter function's parameter myText is going to hide the instance variable myText so you can't use it.
A bigger problem is that you've declared your typeLetter function as taking a parameter of type String, but you're calling it from a timer. The only parameter that a timer passes to a function is the timer itself. You can't pass arbitrary parameters to a timer function.
You could fix all of these problems if you rewrote your typeLetter function to take a timer as a parameter.
func typeLetter(timer: NSTimer)
{
    if myCounter < myText.count {
        Text1.text = Text1.text! + String(myText[myCounter])
        let randomInterval = Double((arc4random_uniform(8)+1))/20
        timer?.invalidate()
        timer = NSTimer.scheduledTimerWithTimeInterval(randomInterval,
          target: self,
          selector: "typeLetter",
          userInfo: nil,
          repeats: false)
    }
    else
    {
        timer?.invalidate()
    }
    myCounter++
}

When you do that, the instance variable myText is no longer hidden by the parameter of the same name, and the instance variable myText is the correct type, [unichar].

A: To get the characters count, you need to use
myText.characters.count

To solve the subscript error, you can try
myText[myText.startIndex.advancedBy(myCounter)]


text:
Q: Adding check constraint for type double precision in postgres I have coordinates with the type double precision in a column. I want to check the length (it has to be 7) before the decimal point (before the decimal places). The numbers can have decimals up to 4.
My first idea:
CHECK (char_length(point_gauss::double precision::char)=...

A: For floating point keep in mind these are binary floating point types and so decimal precision is a bit of a problematic concept.  Your first instinct should be something like:
 CHECK(point_gauss BETWEEN -9999.999 AND 9999.999)

However, if you need specific base 10 precision the best way is to change from double to numeric and use this instead:
 point_gauss NUMERIC(7,3),....


text:
Q: Check for file duplication and remove Basically what I'm looking to do is remove duplicated files and directories which exist among 2 particular locations. What I would like to do is create a script which will check the contents of directories "A" and "B" and in any cases where a directory that exists in "B" is also present in "A", remove from "B".
EXAMPLE:
/some/path/a
dir1
    file1.ext
    file2.ext
    file3.ext
dir2
    file1.ext
    file2.ext
    file3.ext

/some/path/b
dir1
    file1.ext
    file2.ext
    file3.ext
dir3
    file1.ext
    file2.ext
    file3.ext

In this example, the desired outcome would be to recognize that "dir1" exists in both places and then remove "dir1" and its contents from /some/path/b leaving everything else alone. I have played around in the terminal trying to achieve these results and looked online for answers but haven't found anything that fits this particular use case. Any help would be much appreciated.

A: Using bash and comm from GNU coreutils:
a=some/path/a
b=some/path/b

mapfile -d '' dirs_to_del <                           \
  <(comm -z12                                         \
    <(shopt -s nullglob; cd "$a" && printf '%s\0' */) \
    <(shopt -s nullglob; cd "$b" && printf '%s\0' */))
cd "$b" && rm -rf -- "${dirs_to_del[@]}"

Drop the echo if output looks ok.

A: You're looking for something like this:
A=/some/path/a
B=/some/path/b

shopt -s nullglob

for dir in "$B"/*/; do
  if test -d "$A${dir#"$B"}"; then
    echo rm -r -- "$dir"
  fi
done

Remove echo if you're happy with the output.

A: I use something like this
diff -r -s a b | grep -v "Only in" | awk '{print $4}' | xargs rm

Given the folder structure like this
$ tree
.
├── a
│   ├── dir1
│   │   ├── file1.txt
│   │   ├── file2.txt
│   │   └── file3.txt
│   └── dir2
│       ├── file1.txt
│       ├── file2.txt
│       └── file3.txt
└── b
    ├── dir1
    │   ├── file1.txt
    │   └── file2.txt
    └── dir3
        ├── file1.txt
        ├── file2.txt
        └── file3.txt

diff -r -s a b should show
Files a/dir1/file1.txt and b/dir1/file1.txt are identical
Files a/dir1/file2.txt and b/dir1/file2.txt are identical
Only in a/dir1: file3.txt
Only in a: dir2
Only in b: dir3

The -s is explained in diff as
       -s, --report-identical-files
              report when two files are the same


text:
Q: Rmarkdown slidy increase size of equation I am using a slidy presentation with Rmarkdown. The output is html (not pdf). I have a math equation like:
$$\eta_i = \widetilde{r_i} - \widehat{r_i}$$

I would like to increase the size of this equation only within the slide, not the whole slide.
Is this possible?

A: I did
$$\large \eta_i = \widetilde{r_i} - \widehat{r_i}$$
or
$$\huge \eta_i = \widetilde{r_i} - \widehat{r_i}$$
and it worked


text:
Q: Embedding Python in C# via resources I have been working on a problem for a while now which I cannot seem to resolve so I need some help! The problem is that I am writing a program in C# but I require a function from a Python file I created. This  in itself is no problem:
...Usual Stuff

using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace Program
{
    public partial class Form1 : Form
    {
        Microsoft.Scripting.Hosting.ScriptEngine py;
        Microsoft.Scripting.Hosting.ScriptScope s;
        public Form1()
        {
            InitializeComponent();

            py = Python.CreateEngine(); // allow us to run ironpython programs
            s = py.CreateScope(); // you need this to get the variables

        }

        private void doPython()
        {
            //Step 1:
            //Creating a new script runtime
            var ironPythonRuntime = Python.CreateRuntime();

            //Step 2:
            //Load the Iron Python file/script into the memory
            //Should be resolve at runtime
             dynamic loadIPython = ironPythonRuntime.;

             //Step 3:
             //Invoke the method and print the result
             double n = loadIPython.add(100, 200);
             numericUpDown1.Value = (decimal)n;
         }
    }
}

However, this requires for the file 'first.py' to be wherever the program is once compiled. So if I wanted to share my program I would have to send both the executable and the python files which is very inconvenient. One way I thought to resolve this is by adding the 'first.py' file to the resources and running from there... but I don't know how to do this or even if it is possible.
Naturally the above code will not work for this as .UseFile method takes string arguments not byte[]. Does anyone know how I may progress?

A: Lets start with the simplest thing that could possibly work, you've got some code that looks a little like the following:
// ...
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
var ironPythonRuntime = Python.CreateRuntime();
var x = py.CreateScriptSourceFromFile("SomeCode.py");
x.Execute(s);
var myFoo = s.GetVariable("myFoo");
var n = (double)myFoo.add(100, 200);
// ...

and we'd like to replace the line var x = py.CreateScriptSourceFromFile(... with something else;  If we could get the embedded resource as a string, we could use ScriptingEngine.CreateScriptSourceFromString().
Cribbing this fine answer, we can get something that looks a bit like this:
string pySrc;

var resourceName = "ConsoleApplication1.SomeCode.py";
using (var stream = System.Reflection.Assembly.GetExecutingAssembly()
                          .GetManifestResourceStream(resourceName))
using (var reader = new System.IO.StreamReader(stream))
{
    pySrc = reader.ReadToEnd();
}
var x = py.CreateScriptSourceFromString(pySrc);


text:
Q: Windows authentication fail with "401 Unauthorized" I have a MVC client accessing a Web API protected by IDS4. They all run on my local machine and hosted by IIS. The app works fine when using local identity for authentication. But when I try to use Windows authentication, I keep getting "401 Unauthorized" error from the dev tool and the login box keeps coming back to the browser.

Here is the Windows Authentication IIS setting

and enabled providers

It's almost like that the user ID or password was wrong, but that's nearly impossible because that's the domain user ID and password I use for logging into the system all the time. Besides, according to my reading, Windows Authentication is supposed to be "automatic", which means I will be authenticated silently without a login box in the first place.
Update
I enabled the IIS request tracing and here is the result from the log:

As you can see from the trace log item #29, the authentication (with the user ID I typed in, "DOM\Jack.Backer") was successful. However, some authorization item (#48) failed after that. And here is the detail of the failed item:

What's interesting is that the ErrorCode says that the operation (whatever it is) completed successfully, but still I received a warning with a HttpStatus=401 and a HttpReason=Unauthorized. Apparently, this is what failed my Windows Authentication. But what is this authorization about and how do I fix it?

A: In case anyone interested - I finally figured this one out. It is because the code that I downloaded from IndentityServer4's quickstart site in late 2020 doesn't have some of the important pieces needed for Windows authentication. Here is what I had to add to the Challenge function of the ExternalController class

and here is the ProcessWindowsLoginAsync function
private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl)
{
    var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);
    if (result?.Principal is WindowsPrincipal wp)
    {
        var props = new AuthenticationProperties()
        {
            RedirectUri = Url.Action(nameof(Callback)),
            Items =
            {
                { "returnUrl", returnUrl },
                { "scheme", AccountOptions.WindowsAuthenticationSchemeName },
            }
        };

        var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName);
        id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name));
        id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));

        if (AccountOptions.IncludeWindowsGroups)
        {
            var wi = wp.Identity as WindowsIdentity;
            var groups = wi.Groups.Translate(typeof(NTAccount));
            var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
            id.AddClaims(roles);
        }

        await HttpContext.SignInAsync(IdentityConstants.ExternalScheme, new ClaimsPrincipal(id), props);

        return Redirect(props.RedirectUri);
    }
    else
    {
        return Challenge(AccountOptions.WindowsAuthenticationSchemeName);
    }
}

Now my windows authentication works with no issues.