问:
Java: properly checked class instantiation using reflection
I'm trying to use one of the simplest forms of reflection to create an instance of class:

```<code>package some.common.prefix;

public interface My {
    void configure(...);
    void process(...);
}

public class MyExample implements My {
    ... // proper implementation
}

String myClassName = "MyExample"; // read from an external file in reality

Class<? extends My> myClass =
    (Class<? extends My>) Class.forName("some.common.prefix." + myClassName);
My my = myClass.newInstance();
</code>```

Typecasting unknown Class object we've got from Class.forName yields a warning:

```Type safety: Unchecked cast from Class<capture#1-of ?> to Class<? extends My>```

I've tried using instanceof check approach:

```<code>Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if (myClass instanceof Class<? extends RST>) {
    Class<? extends My> myClass = (Class<? extends My>) loadedClass;
    My my = myClass.newInstance();
} else {
    throw ... // some awful exception
}
</code>```

but this yields a compilation error:
Cannot perform instanceof check against parameterized type Class<? extends My>. Use the form Class<?> instead since further generic type information will be erased at runtime. So I guess I can't use instanceof approach.

How do I get rid of it and how am I supposed to do it properly? Is it possible to use reflection without these warnings at all (i.e. without ignoring or supressing them)?

答:
This is how you do it:</p>

```<code>/**
 * Create a new instance of the given class.
 *
 * @param <T>
 *            target type
 * @param type
 *            the target type
 * @param className
 *            the class to create an instance of
 * @return the new instance
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public static <T> T newInstance(Class<? extends T> type, String className) throws
        ClassNotFoundException,
        InstantiationException,
        IllegalAccessException {
    Class<?> clazz = Class.forName(className);
    Class<? extends T> targetClass = clazz.asSubclass(type);
    T result = targetClass.newInstance();
    return result;
}

My my = newInstance(My.class, "some.common.prefix.MyClass");
</code>```

Body:
I'm trying to use one of the simplest forms of reflection to create an instance of class:

package some.common.prefix;

public interface My {
    void configure(...);
    void process(...);
}

public class MyExample implements My {
    ... // proper implementation
}

String myClassName = "MyExample"; // read from an external file in reality

Class<? extends My> myClass =
    (Class<? extends My>) Class.forName("some.common.prefix." + myClassName);
My my = myClass.newInstance();

Typecasting unknown Class object we've got from Class.forName yields a warning:

Type safety: Unchecked cast from Class<capture#1-of ?> to Class<? extends My>

I've tried using instanceof check approach:

Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if (myClass instanceof Class<? extends RST>) {
    Class<? extends My> myClass = (Class<? extends My>) loadedClass;
    My my = myClass.newInstance();
} else {
    throw ... // some awful exception
}

but this yields a compilation error:
Cannot perform instanceof check against parameterized type Class<? extends My>. Use the form Class<?> instead since further generic type information will be erased at runtime. So I guess I can't use instanceof approach.

How do I get rid of it and how am I supposed to do it properly? Is it possible to use reflection without these warnings at all (i.e. without ignoring or supressing them)?

Body:
This is how you do it:

/**
 * Create a new instance of the given class.
 *
 * @param <T>
 *            target type
 * @param type
 *            the target type
 * @param className
 *            the class to create an instance of
 * @return the new instance
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public static <T> T newInstance(Class<? extends T> type, String className) throws
        ClassNotFoundException,
        InstantiationException,
        IllegalAccessException {
    Class<?> clazz = Class.forName(className);
    Class<? extends T> targetClass = clazz.asSubclass(type);
    T result = targetClass.newInstance();
    return result;
}

My my = newInstance(My.class, "some.common.prefix.MyClass");


来源: stackexchange

问:
Replace values in one vector based on values greater than x in separate vector of dataframe
I have a dataframe where values above certain level in one vector should be changed in next vector.

I have tried if function, which gives back 'NA'.

```<code>if (mydata$duration >15) {
mydata$code==3
}
</code>```

Here's some code of what the end function should look like labelled 'recode'

```<code>duration<-c(1,14,5,17,9,10,14,16,2,8,3,18)
code<-c(1,2,1,2,1,2,1,2,1,2,1,2)
mydata<-data.frame(code,duration)
recode<-c(1,2,1,3,1,2,1,3,1,2,1,3)
mydata<-data.frame(recode,duration)
</code>```

答:
Either the 'ifelse' or the 'with (replace)' function worked well.</p>

```<code>mydata$code<-ifelse(mydata$duration>15,3,mydata$code)

mydata$code<-with(mydata,replace(code,duration>15,3))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe where values above certain level in one vector should be changed in next vector.

I have tried if function, which gives back 'NA'.

if (mydata$duration >15) {
mydata$code==3
}

Here's some code of what the end function should look like labelled 'recode'

duration<-c(1,14,5,17,9,10,14,16,2,8,3,18)
code<-c(1,2,1,2,1,2,1,2,1,2,1,2)
mydata<-data.frame(code,duration)
recode<-c(1,2,1,3,1,2,1,3,1,2,1,3)
mydata<-data.frame(recode,duration)

Body:
Either the 'ifelse' or the 'with (replace)' function worked well.

mydata$code<-ifelse(mydata$duration>15,3,mydata$code)

mydata$code<-with(mydata,replace(code,duration>15,3))


问:
How to destroy VC after adding to UIWindow?
For certain types of tests, I need the view controller to be inside a UIWindow. The UIWindow itself is never shown. I'm having trouble destroying the view controller.

Say we have

```<code>class MyViewController: UIViewController {
    deinit {
        print("MyVC bye-bye")
    }
}

class MyWindow: UIWindow {
    deinit {
        print("MyWindow bye-bye")
    }
}
</code>```

Now in a test suite, I can make both objects and they'll be deallocated.

```<code>class MyTests: XCTestCase {
    func test() {
        let vc = MyViewController()
        let window = MyWindow()
    }
}
</code>```

In the console output, I see

```<code>MyWindow bye-bye
MyVC bye-bye
</code>```

But if I add the following line to the test, neither object is destroyed.

```<code>        window.addSubview(vc.view)
</code>```

The window itself may be cleaned up later by the autorelease pool. But my main concern is that the view controller isn't destroyed.

I tried doing

```<code>        vc.view.removeFromSuperview()
</code>```

but that's not enough.

答:
Pumping the run loop gives the autorelease pool a kick, so that no objects linger after the test concludes. If the objects are purely local to the test, place the objects in the autorelease pool and do the pump:

```<code>func test() {
    autoreleasepool {
        let vc = MyViewController()
        let window = MyWindow()
        window.addSubview(vc.view)
    }
    RunLoop.current.run(until: Date())
}
</code>```

But in most test suites, the view controller is part of the test fixture. In that case, pump the loop after releasing the fixture.

```<code>override func tearDown() {
    vc = nil
    RunLoop.current.run(until: Date())
    super.tearDown()
}
</code>```

Body:
For certain types of tests, I need the view controller to be inside a UIWindow. The UIWindow itself is never shown. I'm having trouble destroying the view controller.

Say we have

class MyViewController: UIViewController {
    deinit {
        print("MyVC bye-bye")
    }
}

class MyWindow: UIWindow {
    deinit {
        print("MyWindow bye-bye")
    }
}

Now in a test suite, I can make both objects and they'll be deallocated.

class MyTests: XCTestCase {
    func test() {
        let vc = MyViewController()
        let window = MyWindow()
    }
}

In the console output, I see

MyWindow bye-bye
MyVC bye-bye

But if I add the following line to the test, neither object is destroyed.

        window.addSubview(vc.view)

The window itself may be cleaned up later by the autorelease pool. But my main concern is that the view controller isn't destroyed.

I tried doing

        vc.view.removeFromSuperview()

but that's not enough.

Body:
Pumping the run loop gives the autorelease pool a kick, so that no objects linger after the test concludes. If the objects are purely local to the test, place the objects in the autorelease pool and do the pump:

func test() {
    autoreleasepool {
        let vc = MyViewController()
        let window = MyWindow()
        window.addSubview(vc.view)
    }
    RunLoop.current.run(until: Date())
}

But in most test suites, the view controller is part of the test fixture. In that case, pump the loop after releasing the fixture.

override func tearDown() {
    vc = nil
    RunLoop.current.run(until: Date())
    super.tearDown()
}


问:
Define relation at model without migration which adds FK constraint?
When we define relationships between two tables at Rails, we usually do like

Run command for generate migration file like rails g migration AddUserToTask user:belongs_to

And add line at model to define type of relationships like has_many :users

Then, how about just do step2, which is just add line for define relationships at model?

Does it work?

If so, why we usually do step1?

=====

And, what happen in the case like below?

Just creating column which is necessary for association(like user_id). And this column doesn't have FK constraint at sql level.

And add line at model to define type of relationships like has_many :users with column name which is made at step 1

That means, there is the column needed for association, but it doesn't have FK constraint.

答:
The first step creates the relationship on the database, so it's adding the column user_id in the tasks table.

After this, when you save a task, e.g.

```<code>> task = Task.first
> task.user = User.first
> task.save
</code>```

It's saving the user's id in the user_id field in the tasks table.

Without this column, the association has_many will not work, because there's no link between a User and a Task in the database.

Also, in your example migration, the correct association should be to add has_many :tasks to the User model, and belongs_to :user in the Task model.

Body:
The first step creates the relationship on the database, so it's adding the column user_id in the tasks table.

After this, when you save a task, e.g.

> task = Task.first
> task.user = User.first
> task.save

It's saving the user's id in the user_id field in the tasks table.

Without this column, the association has_many will not work, because there's no link between a User and a Task in the database.

Also, in your example migration, the correct association should be to add has_many :tasks to the User model, and belongs_to :user in the Task model.


问:
Is there a difference between two classes both inherited from NSObject but one marked with @objc in Swift?
I wonder whether @objc would add some extra functionality for those classes inherited from NSObject in Swift.

This is Swift 5.0 with Xcode 10.2.1.

```<code>@objc class X: NSObject {
    var x = 0
}

class Y: NSObject {
    var y = 0
}
</code>```

Is there a semantic difference between these two classes in Swift's perspective?

答:
The only difference here is that class X can be called from Objective-C and class Y cannot. The fact that they both inherit from NSObject is a completely separate thing.

It's the exact same as having to classes that inherit from UIViewController, if one has the @objc prefix it can be called from Objective-C code and the other can't, doesn't have anything to do with the fact that they are UIViewController subclasses.

Body:
I wonder whether @objc would add some extra functionality for those classes inherited from NSObject in Swift.

This is Swift 5.0 with Xcode 10.2.1.

@objc class X: NSObject {
    var x = 0
}

class Y: NSObject {
    var y = 0
}

Is there a semantic difference between these two classes in Swift's perspective?


问:
How to know how often an external link is clicked?
This page: http://funds.ft.com/CityofLondon/investmentmanagement/HCEWUR contains a number of links under the section "Annual Reports & Factsheets". The content these links point at is hosted at fundslibrary.co.uk, a 3rd party supplier.

Is there any way for us to track how often these links are clicked? We don't have access to the 3rd party web server logs.

One way I'm thinking is to POST an instruction to increment a count with jQuery every time the link is clicked, but that would mean us having to maintain the count.

Is there any functionality in Google Analytics that could give us this info?

答: You could use Google Analytics Event Tracking http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html</p>

ContentLicense: CC BY-SA 3.0


问:
Find absolute difference between 2 columns with dates of different formats as number of days
I need to find the absolute difference in days between 2 columns which have dates in python.
This is pretty easy in excel but I want in python.

I have a xlsx file which I have read to a python dataframe(using pd.read_excel) with sample data reading as below:
The columns have the date details in the plain text format of ddmmyyyy/dmmyyyy.

A                   B

1102012

26071993        27122007

28062010        3122015

16012010        21022016

02082015        14092010

Now I need to create a new column C which contains the absolute number of days difference between A and B. A can be less than or greater than B.

If B is empty then it should consider current date for days calculation. But A will not have empty/NULL values.

So output will be the difference of number of days:

C

2432

5267

1984

2227

1783

The approach I followed was:

Convert A and B to 8 digits as we have only 7 digits in some values of A and B - using df['A'].apply(lambda x: '{0:0>8}'.format(x))

Convert A to datetime field using pd.to_datetime

Create another temporary column say CC by copying B values and with all not NULL date values(that is replacing NULL/empty with current date)

Then find the absolute difference between A and CC(number of days)

I am stuck in third step and not able to proceed. Is there any simpler way to do this?

Body:
First fomratting options is a good idea. Avoids confusion as to which is day or month.

# Recreate dataframe
df = pd.DataFrame([["1102012", pd.np.NaN],["26071993","27122007"],
                   ["28062010","3122015"],["16012010","21022016"],
                   ["02082015","14092010"]], columns=["A","B"])
print(df)
>>>
          A         B
0   1102012       NaN
1  26071993  27122007
2  28062010   3122015
3  16012010  21022016
4  02082015  14092010

print(df.dtypes)
>>>
A    object
B    object
dtype: object

So the dataframe we are working from is above. The data types are all object (string). Would be good if you can confirm this step as everything else stems from here.

# convert some datetimes
# Assumption is that column A is not sparse - there are no NaNs
# Column B can be NaN so make it today if so
m = df["B"].isnull()
df.loc[m, "B"] = pd.datetime.now().strftime("%d%m%Y")
print(df)
>>>
          A         B
0   1102012  03062019
1  26071993  27122007
2  28062010   3122015
3  16012010  21022016
4  02082015  14092010

# now we zero pad some numbers
df['A'] = df['A'].apply(lambda x: '{0:0>8}'.format(x))
df['B'] = df['B'].apply(lambda x: '{0:0>8}'.format(x))
print(df)
>>>
          A         B
0  01102012  03062019
1  26071993  27122007
2  28062010  03122015
3  16012010  21022016
4  02082015  14092010

Then use to_datetime:

df["A"] = pd.to_datetime(df["A"], format="%d%m%Y")
df["B"] = pd.to_datetime(df["B"], format="%d%m%Y")
print(df)
>>>
           A          B
0 2012-10-01 2019-06-03
1 1993-07-26 2007-12-27
2 2010-06-28 2015-12-03
3 2010-01-16 2016-02-21
4 2015-08-02 2010-09-14

print(df.dtypes)
>>>
A    datetime64[ns]
B    datetime64[ns]
dtype: object

Then the diff

df["Diff"] = (df["A"] - df["B"]).abs()
print(df)
>>>
           A          B      Diff
0 2012-10-01 2019-06-03 2436 days
1 1993-07-26 2007-12-27 5267 days
2 2010-06-28 2015-12-03 1984 days
3 2010-01-16 2016-02-21 2227 days
4 2015-08-02 2010-09-14 1783 days

# or
df["Diff"] = (df["A"] - df["B"]).abs().dt.days
print(df)
>>>
           A          B  Diff
0 2012-10-01 2019-06-03  2436
1 1993-07-26 2007-12-27  5267
2 2010-06-28 2015-12-03  1984
3 2010-01-16 2016-02-21  2227
4 2015-08-02 2010-09-14  1783


问:
How to implement the Google Analytics event monitoring on a website if the standard Analytics tracking code seems not to be enough?
The website www.3dz.it is using with WordPress.

There are four languages and each one on a different domain (Italian .it, France .fr, etc.). It is in this way using WPML with the multi-domain option, since April 2018.

Up to April 2018, the events monitoring was going. For three months with the four domains, we were without data; in July we add the new analytics code so each language has an own Analytics property.
But we are still without the monitoring of the events.

Google analytics tracking code is since July 2018 set how is actually online.

<?php if(ICL_LANGUAGE_CODE=='en'){?>

<?php } elseif(ICL_LANGUAGE_CODE=='it'){?>

<?php } elseif(ICL_LANGUAGE_CODE=='es'){?>

<?php } elseif(ICL_LANGUAGE_CODE=='fr'){?>

<?php } ?>```

Someone can tell me please how to implement the code to obtain the monitoring of the events again?

答: The problem was the different library of Analytics. I solved it calling google assistance. I changed the event script in the website and I modified the conversion in Analytics (event categories and actions)</p>

Body:
The website www.3dz.it is using with WordPress.

There are four languages and each one on a different domain (Italian .it, France .fr, etc.). It is in this way using WPML with the multi-domain option, since April 2018.

Up to April 2018, the events monitoring was going. For three months with the four domains, we were without data; in July we add the new analytics code so each language has an own Analytics property.
But we are still without the monitoring of the events.

Google analytics tracking code is since July 2018 set how is actually online.

<?php if(ICL_LANGUAGE_CODE=='en'){?>

<?php } elseif(ICL_LANGUAGE_CODE=='it'){?>

<?php } elseif(ICL_LANGUAGE_CODE=='es'){?>

<?php } elseif(ICL_LANGUAGE_CODE=='fr'){?>

<?php } ?>

Someone can tell me please how to implement the code to obtain the monitoring of the events again?


问:
How to prevent PaginationComponent in Angular 2 event to work?
I'm using pagination component that comes from ngx-bootstrap/pagination. Like this:

```<code><pagination *ngIf="returnedArray"
    [totalItems]="contentArray.length"
    (pageChanged)="pageChanged($event)"
    [itemsPerPage]="1"
    [boundaryLinks]="false"></pagination>
</code>```

I want the pager to not navigate to the next page until some conditions are met, but can't find how to achieve that.

I tried several things:

Remove the (pageChanged)="pageChanged($event)" from the pagination component. But navigation is still firing.

Tried to make something like event.preventDefault() but it doesn't exist here

答:
The only way I found to solve this was by hiding paginator component, and then, with a button, simulate the pagination click when conditions are met, like this:

```<code>(<HTMLInputElement>document.querySelector('#next .pagination-next .page-link')).click();
</code>```

Tricky... ugly... but worked :)

Body:
I'm using pagination component that comes from ngx-bootstrap/pagination. Like this:

<pagination *ngIf="returnedArray"
    [totalItems]="contentArray.length"
    (pageChanged)="pageChanged($event)"
    [itemsPerPage]="1"
    [boundaryLinks]="false"></pagination>

I want the pager to not navigate to the next page until some conditions are met, but can't find how to achieve that.

I tried several things:

Remove the (pageChanged)="pageChanged($event)" from the pagination component. But navigation is still firing.

Tried to make something like event.preventDefault() but it doesn't exist here

Body:
The only way I found to solve this was by hiding paginator component, and then, with a button, simulate the pagination click when conditions are met, like this:

(<HTMLInputElement>document.querySelector('#next .pagination-next .page-link')).click();

Tricky... ugly... but worked :)


问:
c++ vectors and pointers
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of them).

The problem when i try to iterate over my vector of string pointers is i cant extract the actual value from them

```<code>string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

vector<string*>::iterator iterator = names.begin();
while (iterator != names.end())
{
    std::cout << (*iterator) << ":" << std::endl;
    // std::cout << *(*iterator); // fails

    iterator++;
}
</code>```

See the commented line, i have no problem in receiving the string pointer. But when i try to get the string pointers value i get an error (i couldnt find what excatly the error is but the program just fails).

I also tried storing (iterator) in a new string variable and but it didnt help?

答:
Try

```<code>if (*iterator)
{
  std::cout << *(*iterator) << ":" << std::endl;
}
</code>```

Mark Ransom explains why some of the pointers are now

Title: c++ vectors and pointers

Body:
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of them).

The problem when i try to iterate over my vector of string pointers is i cant extract the actual value from them

string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

vector<string*>::iterator iterator = names.begin();
while (iterator != names.end())
{
    std::cout << (*iterator) << ":" << std::endl;
    // std::cout << *(*iterator); // fails

    iterator++;
}

See the commented line, i have no problem in receiving the string pointer. But when i try to get the string pointers value i get an error (i couldnt find what excatly the error is but the program just fails).

I also tried storing (iterator) in a new string variable and but it didnt help?

Body:
Try

if (*iterator)
{
  std::cout << *(*iterator) << ":" << std::endl;
}

Mark Ransom explains why some of the pointers are now


问:
How to open a file in both read and append mode at the same time in one variable in python?
'r' will read a file, 'w' will write text in the file from the start, and 'a' will append. How can I open the file to read and append at the same time?

I tried these, but got errors:

```<code>open("filename", "r,a")

open("filename", "w")
open("filename", "r")
open("filename", "a")
</code>```

error:

```<code>invalid mode: 'r,a'
</code>```

答:
You can't do that with a textfile. Either you want to read it or you want to write to it. The a or the r specifies a seek to a particular location in the file. Specifying both is asking open to point to two different locations in the file at the same time.

Textfiles in general can't be updated in place. You can use a to add new stuff to the end but that is about it. To do what I think you want, you need to open the existing file in read mode, and open another, new file in write mode, and copy the data from the one to the other.

After that you have two files so you have to take care of deleting the old one. If that is troublesome, take a look at the module in-place.

The other alternative is to read the input file into memory, close and reopen it for writing, then write out a new version of the file. Then you don't have to delete the old copy. But if something goes wrong in the middle you will have no old input file, because you deleted it, and no new output file either, because you didn't successfully write it.

The reason for this is that textfiles are not designed for random access.

Body:
'r' will read a file, 'w' will write text in the file from the start, and 'a' will append. How can I open the file to read and append at the same time?

I tried these, but got errors:

open("filename", "r,a")

open("filename", "w")
open("filename", "r")
open("filename", "a")

error:

invalid mode: 'r,a'


问:
Cassandra modelling reflecting relationship values
In a Relational database I have a table products (pid,...) and another with property (propid,name) and another that relates the previous ones (relationid,pid,propid,value).
This means that I can relate new properties to products.
I'm trying to get a solution in Cassandra that could reflect what I got for now.
Is adding columns to an existing table in cassandra a good practice?

Thanks for your help

答:
Welcome to the Cassandra world.

This is the most challenging part when evolving from relational databases to Cassandra: the change of paradigms, as in Cassandra denormalizing is actually encouraged. Also, the structure of the tables should depend on the query that you need to execute, which will give you a lot of duplicated data.

There are several resources regarding these changes in data modeling, you can also find an in-depth explanation in https://datastaxacademy.com/ , in the course "DS220: DataStax Enterprise 6 Practical Application Data Modeling with Apache Cassandra™"


问:
Nested axios requests from different web services
I have a problem (using NodeJS + Express) trying to retrieve in 'users' information from 3 different requests (2 domains) and I can't get what I want. I'd like a function getAllUsers() to return something like this:

```<code>[
    {
        "username": "joe_example",
        "plays": 178,
        "friends": 7,
        "uri": "/users/joe_example"
    },
    ...snip additional users...
]
</code>```

Here's my main function:

```<code>async function getAllUsers() {
    let users = await axios.get('http://localhost:8000/friends')
        .then(response => {
            response.data["friends"].map(user => {
                user = getUser(user.username)
            })
        })
        .catch(error => console.log(error))
    return users
}

async function getUser(name) {
    let user = await axios.all(
        [
            axios.get('http://localhost:8000/friends/' + name),
            axios.get('http://localhost:8001/plays/' + name)
        ]).then(axios.spread((res1, res2) => {
            user["username"] = name
            user["friends"] = res1.data["friends"].length
            user["plays"] = res2.data["plays"].length
            user["uri"] = "/users/" + name
        })).catch(error => { console.log(error) })
    return user
}
</code>```

Yes, it may sounds crazy...Friends service has user names and you have to call /friends/<username> in order to retrieve the amount of friends each user has, same with /plays/<username>

Any ideas or suggestions ? I've tried all I know :(

答:
Assuming your getUser works and data["friends"] is an array as you expect:

```<code>async function getAllUsers() {
  let users;
  try {
    const { data } = await axios.get('http://localhost:8000/friends')
    const friends = data["friends"].map(user => getUser(user.username))
    users = await Promise.all(friends)
  } catch(error) {
    console.log(error)
  }
  return users
}
</code>```

Body:
I have a problem (using NodeJS + Express) trying to retrieve in 'users' information from 3 different requests (2 domains) and I can't get what I want. I'd like a function getAllUsers() to return something like this:

[
    {
        "username": "joe_example",
        "plays": 178,
        "friends": 7,
        "uri": "/users/joe_example"
    },
    ...snip additional users...
]

Here's my main function:

async function getAllUsers() {
    let users = await axios.get('http://localhost:8000/friends')
        .then(response => {
            response.data["friends"].map(user => {
                user = getUser(user.username)
            })
        })
        .catch(error => console.log(error))
    return users
}

async function getUser(name) {
    let user = await axios.all(
        [
            axios.get('http://localhost:8000/friends/' + name),
            axios.get('http://localhost:8001/plays/' + name)
        ]).then(axios.spread((res1, res2) => {
            user["username"] = name
            user["friends"] = res1.data["friends"].length
            user["plays"] = res2.data["plays"].length
            user["uri"] = "/users/" + name
        })).catch(error => { console.log(error) })
    return user
}

Yes, it may sounds crazy...Friends service has user names and you have to call /friends/<username> in order to retrieve the amount of friends each user has, same with /plays/<username>

Any ideas or suggestions ? I've tried all I know :(

Body:
Assuming your getUser works and data["friends"] is an array as you expect:

async function getAllUsers() {
  let users;
  try {
    const { data } = await axios.get('http://localhost:8000/friends')
    const friends = data["friends"].map(user => getUser(user.username))
    users = await Promise.all(friends)
  } catch(error) {
    console.log(error)
  }
  return users
}


问:
how to do true deep copy for NSArray and NSDictionary with have nested arrays/dictionary?
Question: Is there a way to use existing objective-c methods to do a full deep copy of a NSDictionary or NSArray, that themselves have nested dictionaries or arrays within them?

That is I have read the problem may be when it hits a nested dictionary or array it only copies the pointer to the nested item, and not copy the item truely.

Background: So as an example for me I'm trying to load/save the following config with NSUserDefaults and when loading need to convert the immutable copies one gets from NSUserDefault to mutable prior to making changes.

Items (NSDictionary)

Item (NSDictionary)

aString: NSString

aString2: NSString

aDate: NSDate

aDate2: NSDate

aBool: BOOL

aTI1: NSTimeInterval

aTI2: NSTimeInterval

Keywords (NSArray)

keyword: NSString

keyword: NSString

答:
If someone want the mutable copy then please use below code:

NSMutableDictionary *newDictionary = (NSMutableDictionary *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)dict, kCFPropertyListMutableContainers));

ContentLicense: CC BY-SA 2.5


问:
Unexpected call to method or property access in IE 7
For work, I need to get our site working in IE7.  Because, as we all know, the corporate world can't upgrade.

I am using IE8's IE7 emulation mode to test the site, and using IE8's wonderful debugger has been a nightmare.

My most recent problem is the following error:

```<code>Unexpected call to method or property access.  jquery.js, line 113 character 460
</code>```

I've put console.log commands on every line of my function, and figured out the line that's causing the error.

```<code>var $loading = $('<span/>').addClass('span-icon icon-ajax-loader').html('Loading...');
</code>```

This line works fine in Firefox and Chrome.  Oh, and it works fine when entering it into IE8's JavaScript console.

Why would this line give Unexpected call to method or property access?  I think the call to the method or property was totally expected.

UPDATE: As per @Pointy's suggestion I broke that line into 3 lines.

```<code>var $loading = $('<span/>');
$loading.addClass('span-icon icon-ajax-loader');
$loading.html('Loading...');
</code>```

Now I'm getting the error on this call $loading.html('Loading...');.  Again, if I paste this code into IE8's developer tools and run it, it works fine.

答:
Where are you injecting the content? Have you looked at this question and answer?
Javascript IE error: unexpected call to method or property access</p>

Body:
For work, I need to get our site working in IE7.  Because, as we all know, the corporate world can't upgrade.

I am using IE8's IE7 emulation mode to test the site, and using IE8's wonderful debugger has been a nightmare.

My most recent problem is the following error:

Unexpected call to method or property access.  jquery.js, line 113 character 460

I've put console.log commands on every line of my function, and figured out the line that's causing the error.

var $loading = $('').addClass('span-icon icon-ajax-loader').html('Loading...');

This line works fine in Firefox and Chrome.  Oh, and it works fine when entering it into IE8's JavaScript console.

Why would this line give Unexpected call to method or property access?  I think the call to the method or property was totally expected.

UPDATE: As per @Pointy's suggestion I broke that line into 3 lines.

var $loading = $('');
$loading.addClass('span-icon icon-ajax-loader');
$loading.html('Loading...');

Now I'm getting the error on this call $loading.html('Loading...');.  Again, if I paste this code into IE8's developer tools and run it, it works fine.


问:
Scala - Add elements based on logic
I am new to Scala.
I have a function that accepts a string and based on different logics, I need to create a Seq of String with all permutations.
Example - input string is 00US_India0234. The result will be Seq of:

```<code>US // Condition - if string contains "US"
India // Condition - if string contains "India"
234 // Condition - if string contains number and trim
US_India // One more condition to keep countries intact and so on
</code>```

Code tried so far which I didn't work

```<code>val retSeq: Seq[String] = Seq.empty
if myStr contains "US" retSeq +: "US"
</code>```

I have the conditions in place but adding to Seq is not possible and I do not want to create a var.

答:
Here is another version, using RegEx:

```<code>import scala.util.matching.Regex

val input = "00US_India0234"

val reg = "([A-Z]{2})_?([A-Za-z]+)([0-9]+)".r

val a = for (m <- reg.findAllMatchIn(input)) yield m.subgroups

println(a.toVector.flatten)

// Out: Vector(US, India, 0234)
</code>```

You can test it in scalafiddle

Title: Scala - Add elements based on logic

Body:
I am new to Scala.
I have a function that accepts a string and based on different logics, I need to create a Seq of String with all permutations.
Example - input string is 00US_India0234. The result will be Seq of:

US // Condition - if string contains "US"
India // Condition - if string contains "India"
234 // Condition - if string contains number and trim
US_India // One more condition to keep countries intact and so on

Code tried so far which I didn't work

val retSeq: Seq[String] = Seq.empty
if myStr contains "US" retSeq +: "US"

I have the conditions in place but adding to Seq is not possible and I do not want to create a var.

Body:
Here is another version, using RegEx:

import scala.util.matching.Regex

val input = "00US_India0234"

val reg = "([A-Z]{2})_?([A-Za-z]+)([0-9]+)".r

val a = for (m <- reg.findAllMatchIn(input)) yield m.subgroups

println(a.toVector.flatten)

// Out: Vector(US, India, 0234)

You can test it in scalafiddle


问:
Constant global user type values in Go
I want to arrange to compute a value that will not change after initialization.

I'd use const, but Go restricts consts to built-in types, IIUC.

So I figured I'd use var, and compute their initial values in init()

```<code>var (
    // ScreenBounds is the visible screen
    ScreenBounds types.Rectangle

    // BoardBounds is the total board space
    BoardBounds  types.Rectangle
)

func init() {
    ScreenBounds := types.RectFromPointSize(
        types.Pt(-ScreenWidth/2, 0),
        types.Pt(ScreenWidth, ScreenHeight))

    BoardBounds := ScreenBounds
    BoardBounds.Max.Y += TankSpeed * TotalFrames
}
</code>```

Which is pretty good - but is there a way to "lock" the values once computed, other than to change the vars to unexported names, and then uses function-accessors to return their values?

答:
As an option you can move these "constants"

```<code>func init() {
    screenBounds := types.RectFromPointSize(
        types.Pt(-ScreenWidth/2, 0),
        types.Pt(ScreenWidth, ScreenHeight))

    BoardBounds := ScreenBounds
    BoardBounds.Max.Y += TankSpeed * TotalFrames
}
</code>```

into a separate package and define them as unexportable and also define an exportable function like this:

```<code>func GetScreenBounds() types.SomeType {
 return screenBounds
}
</code>```

It's some overhead but it will provide you ability to use that constants securely.

Title: Constant global user type values in Go

Body:
I want to arrange to compute a value that will not change after initialization.

I'd use const, but Go restricts consts to built-in types, IIUC.

So I figured I'd use var, and compute their initial values in init()

var (
    // ScreenBounds is the visible screen
    ScreenBounds types.Rectangle

    // BoardBounds is the total board space
    BoardBounds  types.Rectangle
)

func init() {
    ScreenBounds := types.RectFromPointSize(
        types.Pt(-ScreenWidth/2, 0),
        types.Pt(ScreenWidth, ScreenHeight))

    BoardBounds := ScreenBounds
    BoardBounds.Max.Y += TankSpeed * TotalFrames
}

Which is pretty good - but is there a way to "lock" the values once computed, other than to change the vars to unexported names, and then uses function-accessors to return their values?

Body:
As an option you can move these "constants"

func init() {
    screenBounds := types.RectFromPointSize(
        types.Pt(-ScreenWidth/2, 0),
        types.Pt(ScreenWidth, ScreenHeight))

    BoardBounds := ScreenBounds
    BoardBounds.Max.Y += TankSpeed * TotalFrames
}

into a separate package and define them as unexportable and also define an exportable function like this:

func GetScreenBounds() types.SomeType {
 return screenBounds
}

It's some overhead but it will provide you ability to use that constants securely.


问:
How to remove duplicate words from a text file using java
I have a input file like

names.txt

```<code>   Maria Derek Erica
   Livia Jack Anita
   Kendall Maria Livia Derek
   Jamie Jack
   Thomson Erica

</code>```

I want to output like. Removing duplicates words from the name

output.txt

```<code>   Maria Derek Erica
   Livia Jack Anita
   Kendall
   Jamie
   Thomson

</code>```

I already tried to read file separated by whitespace and then add them into ArrayList then I lost what to do next to generate output.

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class duplicate {
   public static void main(String[] args) throws IOException {
      ArrayList<String> list = new ArrayList<String>();
      File file = new File("weather.txt");
      Scanner input = new Scanner(file);
      String prev = input.next();
      int count = 0;
      while (input.hasNext()) {
         String next  = input.next();
         System.out.println(next);
         set.add(next);
         count = count + 1;
         if(prev.equals(next))
         {
            System.out.println("Match found: -" + prev);
         }
         prev = next;
      }

      System.out.println(list);
      System.out.println("Word count: " + count);
   }
}
```

答:
If order doesn't matter, just use Set. Set will filter out duplicate element automatically. Then just print out that set. You will be fine.

Set<String> list = new HashSet<String>();
```

Body:
I have a input file like

names.txt

   Maria Derek Erica
   Livia Jack Anita
   Kendall Maria Livia Derek
   Jamie Jack
   Thomson Erica

I want to output like. Removing duplicates words from the name

output.txt

   Maria Derek Erica
   Livia Jack Anita
   Kendall
   Jamie
   Thomson

I already tried to read file separated by whitespace and then add them into ArrayList then I lost what to do next to generate output.

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class duplicate {
   public static void main(String[] args) throws IOException {
      ArrayList<String> list = new ArrayList<String>();
      File file = new File("weather.txt");
      Scanner input = new Scanner(file);
      String prev = input.next();
      int count = 0;
      while (input.hasNext()) {
         String next  = input.next();
         System.out.println(next);
         set.add(next);
         count = count + 1;
         if(prev.equals(next))
         {
            System.out.println("Match found: -" + prev);
         }
         prev = next;
      }

      System.out.println(list);
      System.out.println("Word count: " + count);
   }
}


问:
Create a TextBlock for every item in a List<Object>
Currently I'm trying to create a TextBlock for every object in a provided list. The object is of type person with various fields, but I'm wanting to display their full name as the content for the TextBlock. I'm doing this like so:

XAML

```<code><ItemsControl ItemsSource="{Binding GetPeople}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <StackPanel>
                    <TextBlock Text="{Binding Path=FullName}" />
                </StackPanel>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

</code>```

This gets the correct values for every object in the list, however, when I add a new object to the list, it does not show up until I reload the control.

答: You need to use ObservableCollection<T>, BindingList<T>, or another collection that can raised events.

Body:
Currently I'm trying to create a TextBlock for every object in a provided list. The object is of type person with various fields, but I'm wanting to display their full name as the content for the TextBlock. I'm doing this like so:

XAML

<ItemsControl ItemsSource="{Binding GetPeople}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <StackPanel>
                    <TextBlock Text="{Binding Path=FullName}" />
                </StackPanel>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

This gets the correct values for every object in the list, however, when I add a new object to the list, it does not show up until I reload the control.


问:
jQuery Transparent Countdown
I have seen many countdown's in JS and jQuery so I wanted it to be transparent i.e to match with the Page BG color ? If anyone knows such a countdown please reply and I need it to be in sorta Big FOnts and Vertical ...</p>

答:
You can use this plugin.

Modify the css for the background-color and font size.

The class .hasCountdown for background-color and .countdown_amount for the size of the countdown number.

Title: jQuery Transparent Countdown


问:
Rails active-record array gives 0 on count but record exists in db?
can anyone help me to solve this mystery?

checkout on image you will understand it

Ruby version - 2.6.0
Rails - 5.2.2

```<code>(byebug) volume_prices
#<ActiveRecord::AssociationRelation [#<Spree::VoumePrice id: 5, variant_id: 4, name: nil, range: "(1..5)", amount: 0.109e3, position: 2, created_at: "2019-05-30 12:49:56", updated_at: "2019-05-30 12:49:56", discount_type: "price", role_id: nil, volume_price_model_id: nil, user_id: nil, supplier_id: 3, pricing_tier_id: 5>]>
(byebug) volume_prices.count
0
(byebug) volume_prices.length
1
(byebug) Spree::VolumePrice.find(5)
#<Spree::VolumePrice id: 5, variant_id: 4, name: nil, range: "(1..5)", amount: 0.1e2, position: 1, created_at: "2019-05-30 12:54:00", updated_at: "2019-05-30 12:54:00", discount_type: "price", role_id: nil, volume_price_model_id: nil, user_id: nil, supplier_id: 4, pricing_tier_id: 5>
</code>```

答:
volume_prices is NOT an array, it is an AcitveRecord::Relation, so that may have something to do with it. I would recommend using #size instead of #length or #count. #size will always give you the number you're looking for, regardless of if it's an array or a Relation.

If it's a relation, it will run the SQL command for counting instead of querying for all records and THEN counting in Ruby.

```<code>[1] pry(main)> User.all.size
   (0.5ms)  SELECT COUNT(*) FROM `users`
=> 10
[2] pry(main)> User.all.to_a.size
  User Load (0.6ms)  SELECT `users`.* FROM `users`
=> 10
[3] pry(main)> User.all.length
  User Load (0.4ms)  SELECT `users`.* FROM `users`
=> 10
</code>```

Body:
can anyone help me to solve this mystery?

checkout on image you will understand it

Ruby version - 2.6.0
Rails - 5.2.2

(byebug) volume_prices
#<ActiveRecord::AssociationRelation [#<Spree::VoumePrice id: 5, variant_id: 4, name: nil, range: "(1..5)", amount: 0.109e3, position: 2, created_at: "2019-05-30 12:49:56", updated_at: "2019-05-30 12:49:56", discount_type: "price", role_id: nil, volume_price_model_id: nil, user_id: nil, supplier_id: 3, pricing_tier_id: 5>]>
(byebug) volume_prices.count
0
(byebug) volume_prices.length
1
(byebug) Spree::VolumePrice.find(5)
#<Spree::VolumePrice id: 5, variant_id: 4, name: nil, range: "(1..5)", amount: 0.1e2, position: 1, created_at: "2019-05-30 12:54:00", updated_at: "2019-05-30 12:54:00", discount_type: "price", role_id: nil, volume_price_model_id: nil, user_id: nil, supplier_id: 4, pricing_tier_id: 5>

Body:
volume_prices is NOT an array, it is an AcitveRecord::Relation, so that may have something to do with it. I would recommend using #size instead of #length or #count. #size will always give you the number you're looking for, regardless of if it's an array or a Relation.

If it's a relation, it will run the SQL command for counting instead of querying for all records and THEN counting in Ruby.

[1] pry(main)> User.all.size
   (0.5ms)  SELECT COUNT(*) FROM `users`
=> 10
[2] pry(main)> User.all.to_a.size
  User Load (0.6ms)  SELECT `users`.* FROM `users`
=> 10
[3] pry(main)> User.all.length
  User Load (0.4ms)  SELECT `users`.* FROM `users`
=> 10


问:
Heroku deployment error H10; Error: Cannot find module '/app/console`
I'm trying to deploy my first React application on Heroku. The Build portion appears successful, but launching the app delivers a white screen with "Application error."

I've followed heroku logs --tail, but cannot identify the errors that it is giving me.

Heroku logs --tail:

```<code>2019-05-30T13:15:28.528598+00:00 heroku[router]: at=error code=H10
desc="App crashed" method=GET path="/" host=serene-peak-
12902.herokuapp.com request_id=e2d2bd7d-9b96-42fb-a4ce-89cc7bccfad6
fwd="67.166.97.166" dyno= connect= service= status=503 bytes=
protocol=https
2019-05-30T13:15:29.101530+00:00 heroku[router]: at=error code=H10
desc="App crashed" method=GET path="/favicon.ico" host=serene-peak-
12902.herokuapp.com request_id=44fa674d-ef39-4132-9c6f-430038be66ec
fwd="67.166.97.166" dyno= connect= service= status=503 bytes=
protocol=https
</code>```

Heroku run node console:

```<code>internal/modules/cjs/loader.js:550
throw err;
^

Error: Cannot find module '/app/console'
at Function.Module._resolveFilename
(internal/modules/cjs/loader.js:548:15)
at Function.Module._load (internal/modules/cjs/loader.js:475:25)
at Function.Module.runMain (internal/modules/cjs/loader.js:695:10)
at startup (internal/bootstrap/node.js:201:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)
</code>```

答:
(Assuming you're using stack MERN) Heroku can't find the root path. You have to get your Express app to serve your React app,  so you need to config your server.js file in order to do that.

Follow this tutorial

Body:
I'm trying to deploy my first React application on Heroku. The Build portion appears successful, but launching the app delivers a white screen with "Application error."

I've followed heroku logs --tail, but cannot identify the errors that it is giving me.

Heroku logs --tail:

2019-05-30T13:15:28.528598+00:00 heroku[router]: at=error code=H10
desc="App crashed" method=GET path="/" host=serene-peak-
12902.herokuapp.com request_id=e2d2bd7d-9b96-42fb-a4ce-89cc7bccfad6
fwd="67.166.97.166" dyno= connect= service= status=503 bytes=
protocol=https
2019-05-30T13:15:29.101530+00:00 heroku[router]: at=error code=H10
desc="App crashed" method=GET path="/favicon.ico" host=serene-peak-
12902.herokuapp.com request_id=44fa674d-ef39-4132-9c6f-430038be66ec
fwd="67.166.97.166" dyno= connect= service= status=503 bytes=
protocol=https

Heroku run node console:

internal/modules/cjs/loader.js:550
throw err;
^

Error: Cannot find module '/app/console'
at Function.Module._resolveFilename
(internal/modules/cjs/loader.js:548:15)
at Function.Module._load (internal/modules/cjs/loader.js:475:25)
at Function.Module.runMain (internal/modules/cjs/loader.js:695:10)
at startup (internal/bootstrap/node.js:201:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)


问:
Application insight configuration for spring boot is not working

I am using spring boot version 2.0.0.

  and I am using applicationInsight-web and core jar 2.1.0.

  I have put instrumantation key in applicaionInsight.xml also.

答:
Here are the configurations for me to make Spring-cloud + Azure Application Insight.

pom.xml

```<code>        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>applicationinsights-spring-boot-starter</artifactId>
            <version>1.2.0-BETA</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>applicationinsights-logging-logback</artifactId>
            <version>2.4.0-BETA</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
        </dependency>
        <dependency>
            <groupId>io.opentracing.brave</groupId>
            <artifactId>brave-opentracing</artifactId>
        </dependency>
</code>```

and dependenciesManagement

```<code><dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.microsoft.azure</groupId>
                <artifactId>spring-cloud-azure-dependencies</artifactId>
                <version>1.1.0.RC5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</code>```

logback-spring.xml

```<code><appender name="aiAppender"
           class="com.microsoft.applicationinsights.logback.ApplicationInsightsAppender">
        <instrumentationKey>YOUR_INSTRUMENTATION_KEY</instrumentationKey>
</appender>
</code>```

application.yml

```<code>azure:
  application-insights:
    instrumentation-key: YOUR_INSTRUMENTATION_KEY
</code>```

Good luck!

Body:
Here are the configurations for me to make Spring-cloud + Azure Application Insight.

pom.xml

        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>applicationinsights-spring-boot-starter</artifactId>
            <version>1.2.0-BETA</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>applicationinsights-logging-logback</artifactId>
            <version>2.4.0-BETA</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
        </dependency>
        <dependency>
            <groupId>io.opentracing.brave</groupId>
            <artifactId>brave-opentracing</artifactId>
        </dependency>

and dependenciesManagement

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.microsoft.azure</groupId>
                <artifactId>spring-cloud-azure-dependencies</artifactId>
                <version>1.1.0.RC5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

logback-spring.xml

<appender name="aiAppender"
           class="com.microsoft.applicationinsights.logback.ApplicationInsightsAppender">
        <instrumentationKey>YOUR_INSTRUMENTATION_KEY</instrumentationKey>
</appender>

application.yml

azure:
  application-insights:
    instrumentation-key: YOUR_INSTRUMENTATION_KEY

Good luck!


问:
Read file and write file
Can't seem to get my data to be read as an integer and print out the data. plus there is a close stream (IOError) for count = aFile.gets in def read (afile) function.
This program includes Array, files and loops. The purpose of this program is to take a number 10 and write the number to a file then on each line increment from zero to 10 that is passed.</p>

```<code># takes a number and writes that number to a file then on each line
# increments from zero to the number passed
def write(aFile, number)
  # You might need to fix this next line:
  aFile.puts("number")
  index = 0
  while (index < number)
   aFile.puts(number.to_s)
   index += 1
  end
end

# Read the data from the file and print out each line
def read(aFile)

  # Defensive programming:
  count = aFile.gets
  if (is_numeric(count))
    count = count.to_i
  else
    count = 0
    puts "Error: first line of file is not a number"
  end

  index = 0
  while (count < index)
    line = aFile.gets
    puts "Line read: " + line
  end
end

# Write data to a file then read it in and print it out
def main
  aFile = File.new("mydata.txt", "w") # open for writing
  if aFile  # if nil this test will be false
    write(aFile, 10)
  else
    puts "Unable to open file to write!"
  end

  if aFile
    read(aFile)
  end
  aFile.close
end

# returns true if a string contains only digits
def is_numeric?(obj)
  if /[^0-9]/.match(obj) == nil
    true
  end
  false
end

main

</code>```

答:
Here is a skinned code working, you'd easily add the features I removed.

```<code>def write(a_file, number)
  (1..number).each { |n| a_file.puts(n) }
end

def read(a_file)
  a_file.each  { |line| puts line }
end

def main
  a_file = File.new("mydata.txt", "w")
  if a_file
    write(a_file, 10)
  else
    puts "Unable to open file to write!"
  end
  a_file.close

  a_file = File.open("mydata.txt", "r")
  if a_file
    read(a_file)
  end
  a_file.close
end

main
</code>```

The main bugs I've found:

After writing, close the file and open again fro writing

See here for reading: What are all the common ways to read a file in Ruby?

aFile.puts(number.to_s) you should puts index, which is the incrementing variable

(is_numeric(count)) missing ?

Side note: use Ruby notation for variables: a_file is good, aFile is not.

Title: Read file and write file

Body:
Can't seem to get my data to be read as an integer and print out the data. plus there is a close stream (IOError) for count = aFile.gets in def read (afile) function.
This program includes Array, files and loops. The purpose of this program is to take a number 10 and write the number to a file then on each line increment from zero to 10 that is passed.

# takes a number and writes that number to a file then on each line
# increments from zero to the number passed
def write(aFile, number)
  # You might need to fix this next line:
  aFile.puts("number")
  index = 0
  while (index < number)
   aFile.puts(number.to_s)
   index += 1
  end
end

# Read the data from the file and print out each line
def read(aFile)

  # Defensive programming:
  count = aFile.gets
  if (is_numeric(count))
    count = count.to_i
  else
    count = 0
    puts "Error: first line of file is not a number"
  end

  index = 0
  while (count < index)
    line = aFile.gets
    puts "Line read: " + line
  end
end

# Write data to a file then read it in and print it out
def main
  aFile = File.new("mydata.txt", "w") # open for writing
  if aFile  # if nil this test will be false
    write(aFile, 10)
  else
    puts "Unable to open file to write!"
  end

  if aFile
    read(aFile)
  end
  aFile.close
end

# returns true if a string contains only digits
def is_numeric?(obj)
  if /[^0-9]/.match(obj) == nil
    true
  end
  false
end

main

Body:
Here is a skinned code working, you'd easily add the features I removed.

def write(a_file, number)
  (1..number).each { |n| a_file.puts(n) }
end

def read(a_file)
  a_file.each  { |line| puts line }
end

def main
  a_file = File.new("mydata.txt", "w")
  if a_file
    write(a_file, 10)
  else
    puts "Unable to open file to write!"
  end
  a_file.close

  a_file = File.open("mydata.txt", "r")
  if a_file
    read(a_file)
  end
  a_file.close
end

main

The main bugs I've found:

After writing, close the file and open again fro writing

See here for reading: What are all the common ways to read a file in Ruby?

aFile.puts(number.to_s) you should puts index, which is the incrementing variable

(is_numeric(count)) missing ?

Side note: use Ruby notation for variables: a_file is good, aFile is not.


问:
JSF: Hide input when typing in the text box
I want to hide the first 6 characters of SSN when user types in the text box. Something like *--1234
Is there any built in tag I can achieve this. Thanks in advance.

答:
The "built in" components of the standard JSF implementation only represents the standard HTML elements. Your functional requirement is not covered by any of those HTML elements, so the standard JSF implementation won't have it as well. The closest one is the HTML <input type="password"> which is provided by JSF <h:inputSecret> component, but this will mask all characters instead of only a specified subset.

Also no 3rd party JSF component libraries comes to mind which is able to do this. You have basically 2 options, an easy one and a harder one.

Split the SSN over two input fields. One <h:inputSecret> and one <h:inputText>. Add if necessary some onkeyup JavaScript helper code which auto-tabs to the next field when 6 characters are entered. In the server side just glue the two parts together.

Use a <h:inputHidden> for the value and a normal <input type="text"> with some onkeydown JavaScript helper code which fills the hidden input and returns the masked character to the visible input for the first 6 characters.


问:
npm-shrinkwrap.json: Could not install from "node_modules/react-navigation/react-native-tab-view@github:react-navigation/react-native-tab-view
I tried to run an npm install this morning on a React Native 0.53.3 project with   "react-navigation": "1.5.11", and I got this error:

```<code>npm ERR! code ENOLOCAL
npm ERR! Could not install from "node_modules/react-navigation/react-native-tab-view@github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb" as it does not contain a package.json file.
</code>```

I thought it would resolve by adding this to my package.json file:

```<code>"react-native-tab-view": "^1.3.2",
</code>```

but I continue to get that same error. I opened a couple of issues with react-navigation team and it got closed as they concluded it is a problem with npm.

How can I resolve this?

It looks like it is referencing this inside of npm-shrinkwrap.json:

```<code>"react-native-tab-view": {
      "version": "github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb",
      "from": "react-native-tab-view@github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb",
      "requires": {
        "prop-types": "^15.6.0"
      }
    },
</code>```

答:
This seems to be an issue with npm-shrinkwrap.json where the error kept referencing the following inside of it:

```<code>"react-native-tab-view": {
      "version": "github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb",
      "from": "react-native-tab-view@github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb",
      "requires": {
        "prop-types": "^15.6.0"
      }
    },
</code>```

Removing just this did not help, I had to completely remove npm-shrinkwrap.json and do an npm install with just the conventional package-lock.json.

Body:
I tried to run an npm install this morning on a React Native 0.53.3 project with   "react-navigation": "1.5.11", and I got this error:

npm ERR! code ENOLOCAL
npm ERR! Could not install from "node_modules/react-navigation/react-native-tab-view@github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb" as it does not contain a package.json file.

I thought it would resolve by adding this to my package.json file:

"react-native-tab-view": "^1.3.2",

but I continue to get that same error. I opened a couple of issues with react-navigation team and it got closed as they concluded it is a problem with npm.

How can I resolve this?

It looks like it is referencing this inside of npm-shrinkwrap.json:

"react-native-tab-view": {
      "version": "github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb",
      "from": "react-native-tab-view@github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb",
      "requires": {
        "prop-types": "^15.6.0"
      }
    },

Body:
This seems to be an issue with npm-shrinkwrap.json where the error kept referencing the following inside of it:

"react-native-tab-view": {
      "version": "github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb",
      "from": "react-native-tab-view@github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb",
      "requires": {
        "prop-types": "^15.6.0"
      }
    },

Removing just this did not help, I had to completely remove npm-shrinkwrap.json and do an npm install with just the conventional package-lock.json.


问:
Is using one Amazon Document DB replica provide fastest fail over time?
Because there is no election involved in the fail over, so when the primary is down, it will auto switch to the only one slave automatically?</p>

答:
The answer to your question is within the docs. https://docs.aws.amazon.com/documentdb/latest/developerguide/replication.html

Specifically :

If a failure occurs in the primary instance (AZ1), a failover is triggered, and one of the existing replicas is promoted to primary. When the old primary recovers, it becomes a replica in the same Availability Zone in which it was provisioned (AZ1). When you provision a three-instance cluster, Amazon DocumentDB continues to preserve that three-instance cluster. Amazon DocumentDB automatically handles detection, failover, and recovery of instance failures without any manual intervention.

and

You can specify Amazon DocumentDB replicas as failover targets. That is, if the primary instance fails, the specified Amazon DocumentDB replica or replica from a tier is promoted to the primary instance. There is a brief interruption during which read and write requests made to the primary instance fail with an exception. If your Amazon DocumentDB cluster doesn't include any Amazon DocumentDB replicas, when the primary instance fails, it is re-created. Promoting an Amazon DocumentDB replica is much faster than re-creating the primary instance.

Read more about fault tolerance here.
https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-fault-tolerance.html


问:
How to run command with administrator privileges
I want to implement a simple mac app which will run some commands with administrator privileges.
What I've done is the code below

```<code>func execute(command: String) -> String {
        var arguments:[String] = []
        arguments.append("-c")
        arguments.append(command)

        let task = Process()
        task.launchPath = "/bin/sh"
        task.arguments = arguments

        let pipe = Pipe()
        task.standardOutput = pipe
        task.standardError = pipe
        task.launch()
        task.waitUntilExit()
        let data = pipe.fileHandleForReading.readDataToEndOfFile()

        return String(data: data, encoding: .utf8)!
    }
</code>```

This is working for commands without sudo, when I'm putting sudo in the beginning of command I get this error /bin/sh: /usr/bin/sudo: Operation not permitted

I just want somehow to give the user's password or ask it native?
Any ideas?

答:
I found the solution, keep the code as it is and the command should be in this format:

```<code>"osascript -e 'do shell script \"my command\" with administrator privileges'"
</code>```

I tried to use it before but I had to put quotes and single quotes as above!

With that the native alert of apple is presenting.

Body:
I want to implement a simple mac app which will run some commands with administrator privileges.
What I've done is the code below

func execute(command: String) -> String {
        var arguments:[String] = []
        arguments.append("-c")
        arguments.append(command)

        let task = Process()
        task.launchPath = "/bin/sh"
        task.arguments = arguments

        let pipe = Pipe()
        task.standardOutput = pipe
        task.standardError = pipe
        task.launch()
        task.waitUntilExit()
        let data = pipe.fileHandleForReading.readDataToEndOfFile()

        return String(data: data, encoding: .utf8)!
    }

This is working for commands without sudo, when I'm putting sudo in the beginning of command I get this error /bin/sh: /usr/bin/sudo: Operation not permitted

I just want somehow to give the user's password or ask it native?
Any ideas?

Body:
I found the solution, keep the code as it is and the command should be in this format:

"osascript -e 'do shell script \"my command\" with administrator privileges'"

I tried to use it before but I had to put quotes and single quotes as above!

With that the native alert of apple is presenting.


问:
Web-scraping a simulator
I'm trying to scrape all the data inside this loan simulator:

https://m-pt-funnel.younited-credit.com/initialproposal

For example, I need to get all the TAEG values depending on the loan amount and time ("meses")

I was searching for a json file in this website so that I can use get/post functions to extract the info but I was unable to find the json.

Further than the TAEG information, I would also like to get the monthly payment (the numbers in orange), the number of months to pay (number of "meses" at the right) and the "MONTANTE TOTAL DEVIDO" at the bottom of the page.

答:
If there is no API, you could use Selenium with Chrome driver and copy the fields by referencing the Xpath, you could select fields and click calculate then use the "wait" function to then grab the results and store in a table or log. you will need to download chrome driver though/.

example on first value:

```<code>import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://m-pt-funnel.younited-credit.com/initialproposal')
time.sleep(5)
rtn_element = driver.find_elements_by_xpath("//*[@id='"'wrappApp'"']/div/div/yuc-initial-proposal-step/div/div/div/div[1]/div[3]/div/div/yuc-commercial-offer/div/div[1]/div/div[2]/span[2]/label")
rtn = [x.text for x in rtn_element]
# print out all info on RTN
print('RTN:')
print(rtn, '\n')
</code>```

Title: Web-scraping a simulator

Body:
If there is no API, you could use Selenium with Chrome driver and copy the fields by referencing the Xpath, you could select fields and click calculate then use the "wait" function to then grab the results and store in a table or log. you will need to download chrome driver though/.

example on first value:

import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://m-pt-funnel.younited-credit.com/initialproposal')
time.sleep(5)
rtn_element = driver.find_elements_by_xpath("//*[@id='"'wrappApp'"']/div/div/yuc-initial-proposal-step/div/div/div/div[1]/div[3]/div/div/yuc-commercial-offer/div/div[1]/div/div[2]/span[2]/label")
rtn = [x.text for x in rtn_element]
# print out all info on RTN
print('RTN:')
print(rtn, '\n')


问:
Strange difference between Integer variable and Array variable
```<code>a = 1
def bla x
 x = x + 1
end

bla a # =>2 when I use bla to add 1, it return 2

a # => 1 but it get back to the original value

a = [1]
</code>```

but Array

```<code>def bla x
 x << 1
end

bla a # => [1,1]

a # =>[1,1] stay in the new value
</code>```

Could Anybody tell me why it is?

答:
This version of your integer bla:

```<code>def bla x
  x += 1
end
a = 1
bla a
</code>```

is closer to your array one. But, even this one won't change a because Fixnum instances are immutable; if Fixnum instances weren't immutable you'd have people changing the value of 1 and that would just create a big mess.

This version of your array bla:

```<code>def bla x
  x + [1]
end
a = [1]
bla a
</code>```

is closer to your integer one. This array-bla will leave a unmodified.

Your array-bla changes a because x << 1 is the same as x.push(1) and the push method modifies the array. The x that your array-bla see is a reference that points to the same object that a does.

Body:
a = 1
def bla x
 x = x + 1
end

bla a # =>2 when I use bla to add 1, it return 2

a # => 1 but it get back to the original value

a = [1]

but Array

def bla x
 x << 1
end

bla a # => [1,1]

a # =>[1,1] stay in the new value

Could Anybody tell me why it is?

Body:
This version of your integer bla:

def bla x
  x += 1
end
a = 1
bla a

is closer to your array one. But, even this one won't change a because Fixnum instances are immutable; if Fixnum instances weren't immutable you'd have people changing the value of 1 and that would just create a big mess.

This version of your array bla:

def bla x
  x + [1]
end
a = [1]
bla a

is closer to your integer one. This array-bla will leave a unmodified.

Your array-bla changes a because x << 1 is the same as x.push(1) and the push method modifies the array. The x that your array-bla see is a reference that points to the same object that a does.


问:
How can I load all items on a web page when using an HTML parser?
I'm trying to get a list of all the items available for purchase on a certain web page. However, the web page only loads 12 items at a time until the user scrolls down and then 12 more are loaded. Is there a way, in C# or Python, using any open source libraries, to be able to "see" all of the items available without physically going to the page and scrolling down?

Using Chrome's developer tools, I can only "see" the 12 items in the HTML window until I physically scroll down on the web page and it loads more.

NOTE: I'm relatively new at C#/Python web scraping, so I appreciate any in depth answers!

EDIT: If I were to use something like Selenium, would it be possible to load everything programatically? If so, how?

答:
The Web browser itself can obviously load more items, and a web browser is just a program, so yes, it's possible to write a program to do it.

But you'd essentially be writing a mini web browser, which is a lot of work.

Does the website itself offer a way to load more items at once?  i.e. some websites offer a link or a dropdown menu in the corner of the page that allows you to increase the maximum number of items shown.


问:
Regex pattern needs to match only the first occurrence and not be "greedy"
I'm stumped on one pattern that keeps returning all matches beyond the first (it's "greedy")
my pattern: ISS/(?\w\S*)
Where the text has two matches:

ISS/2018-03-02

ISS/2005-03-09

I only want the C# regex to return the first match "2018-03-02"

```<code>    private static readonly Regex tagIssueDateRegex = new Regex(
        @"ISS\/(?<issue>\w+\S*)",
        RegexOptions.Singleline);
</code>```

答:
Note that in your pattern \w+\S* is a very broad match for the date like part.

You can use your pattern and use Match to get the first occurrence.

```<code>string pattern = @"ISS\/(?<issue>\w\S*)";
string input = @"ISS/2018-03-02
ISS/2005-03-09";
RegexOptions options = RegexOptions.Multiline;
var res = Regex.Match(input, pattern);
Console.WriteLine(res.Value);
</code>```

Result:

```<code>ISS/2018-03-02
</code>```

C# Demo

If you want a more specific match for a date like format you could use:

```<code>\bISS/(?<issue>\d{4}-\d{2}-\d{2})\b
</code>```

See a regex demo

Body:
I'm stumped on one pattern that keeps returning all matches beyond the first (it's "greedy")
my pattern: ISS/(?\w\S*)
Where the text has two matches:

ISS/2018-03-02

ISS/2005-03-09

I only want the C# regex to return the first match "2018-03-02"

    private static readonly Regex tagIssueDateRegex = new Regex(
        @"ISS\/(?<issue>\w+\S*)",
        RegexOptions.Singleline);

Body:
Note that in your pattern \w+\S* is a very broad match for the date like part.

You can use your pattern and use Match to get the first occurrence.

string pattern = @"ISS\/(?<issue>\w\S*)";
string input = @"ISS/2018-03-02
ISS/2005-03-09";
RegexOptions options = RegexOptions.Multiline;
var res = Regex.Match(input, pattern);
Console.WriteLine(res.Value);

Result:

ISS/2018-03-02

C# Demo

If you want a more specific match for a date like format you could use:

\bISS/(?<issue>\d{4}-\d{2}-\d{2})\b

See a regex demo


问:
How to deal with relative path in Junits between Maven and Intellij
I have a maven project with a module

```<code>/myProject
pom.xml
    /myModule
    pom.xml
       /foo
       bar.txt
</code>```

Consider a Junit in myModule which needs to open bar.txt, with maven the basedir is the module directory.

So to open the file bar.txt  :

```<code>  new File("foo/bar.txt")
</code>```

This works well when you execute mvn test BUT when you launch the same junit in intellij, it fails because Intellij sets the basedir in the project directory, not the module directory.

Intellij tries to open myProject/foo/bar.txt instead of myProject/myModule/foo/bar.txt

Is there a way to deal with that ?

答:
If you want to keep your code, you can try to change the working directory in the run/debug configuration (first entry in the combo box giving access to what you want to run)
Set this to your module root.
But prefer the other suggested approach:

```<code>ClassLoader.getSystemResourceAsStream(youPath)
</code>```

Or my preferred:

```<code>getClass.getResource(youPath)
</code>```

or

```<code>getClass.getResourceAsStream(youPath)
</code>```

A leading '/' in path indicates the working dir of your project, while no '/' indicates a relative dir to current class.

I use this last solution for my tests: I put my test data resources at the same package level as the test source, or in a subdir to avoid too messy package.

This way I can do a simple call without complicated path and without having to deal with working directory:

```<code>project-root
  - module A
    - src
      - test
        - rootfile.txt
        - my-complicated-package-naming-root
          - mypackage
            - Test.java
            - testResource.xml
</code>```

I can get the files this way:

```<code>final URL rootfile= Test.class.getResource("/rootfile.txt");
final URL testResource= Test.class.getResource("testResource.xml");
</code>```

Body:
I have a maven project with a module

/myProject
pom.xml
    /myModule
    pom.xml
       /foo
       bar.txt

Consider a Junit in myModule which needs to open bar.txt, with maven the basedir is the module directory.

So to open the file bar.txt  :

  new File("foo/bar.txt")

This works well when you execute mvn test BUT when you launch the same junit in intellij, it fails because Intellij sets the basedir in the project directory, not the module directory.

Intellij tries to open myProject/foo/bar.txt instead of myProject/myModule/foo/bar.txt

Is there a way to deal with that ?

Body:
If you want to keep your code, you can try to change the working directory in the run/debug configuration (first entry in the combo box giving access to what you want to run)
Set this to your module root.
But prefer the other suggested approach:

ClassLoader.getSystemResourceAsStream(youPath)

Or my preferred:

getClass.getResource(youPath)

or

getClass.getResourceAsStream(youPath)

A leading '/' in path indicates the working dir of your project, while no '/' indicates a relative dir to current class.

I use this last solution for my tests: I put my test data resources at the same package level as the test source, or in a subdir to avoid too messy package.

This way I can do a simple call without complicated path and without having to deal with working directory:

project-root
  - module A
    - src
      - test
        - rootfile.txt
        - my-complicated-package-naming-root
          - mypackage
            - Test.java
            - testResource.xml

I can get the files this way:

final URL rootfile= Test.class.getResource("/rootfile.txt");
final URL testResource= Test.class.getResource("testResource.xml");


问:
How can I identify duplicated elements in rows
I have a data frame which looks like this but with altogether 31 variables(columns) and 11000 observations (the missing values are empty):

```<code>T1 = c("a1", "c1", "e1", "d1", "a3", "f1", "f2")
T2 = c("b1", "d1", "a1", "b2", "a3", "f1", "f3")
T3 = c(NA, NA, "e1", "d1", NA, "a4", "f3")
T4 = c( NA, NA, NA, "b2", NA, "b3", "f5")
T5 = c( NA, NA, NA, NA, NA, "a4", "f6")
T6 = c( NA, NA, NA, NA, NA,  NA, "f7")
T7 = c(NA, NA, NA, NA, NA, NA, "c1")
T8 = c(NA, NA, NA, NA, NA, NA, "c1")
T9 = c(NA, NA, NA, NA, NA, NA, "f2")
T10= c(NA, NA, NA, NA, NA, NA, "f3")
</code>```

I would like to identify if there is any duplicated element of the "T" type variables by rows, so my df would look like this:

```<code> T1 = c("a1", "c1", "e1", "d1", "a3", "f1", "f2")
 T2 = c("b1", "d1", "a1", "b2", "a3", "f1", "f3")
 T3 = c(NA, NA, "e1", "d1", NA, "a4", "f3")
 T4 = c( NA, NA, NA, b2, NA, "b3", "f5")
 T5 = c( NA, NA, NA, NA, NA, "a4", "f6")
 T6 = c( NA, NA, NA, NA, NA,  NA, "f7")
 T7 = c(NA, NA, NA, NA, NA, NA, "c1")
 T8 = c(NA, NA, NA, NA, NA, NA, "c1")
 T9 = c(NA, NA, NA, NA, NA, NA, "f2")
 T10= c(NA, NA, NA, NA, NA, NA, "f3")
 D = c(F, F, T, T, T, T, T)
</code>```

I attempted to write a function but clearly I miss something because it does not work:
first I created a new variable with empty values

```<code>df$D <- ""
</code>```

then the function:

```<code>dupl <- function(x){
     for(i in 1:nrow(x))
              if (duplicated(x[i], incomparables = NA)){
            df$D <- "TRUE"
  }else{
    df$D <- "FALSE"
  }
}

df$D <- dupl(df)
</code>```

I also tried this code but it does not give me the rows (when D takes a value of true) which contains the duplicated elements:

```<code>df$D <- apply(df[-1], 1, function(i) any(duplicated(i, incomparables = NA)))
</code>```

答:
I'm a fan of dplyr and tidyverse which is why I would go this route:

```<code>df <- data.frame(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)

df %>%
mutate(index = row_number()) %>%
gather(key, value, -index, na.rm = T) %>%
group_by(index) %>%
summarise(D = any(duplicated(value))) %>%
cbind(df)
</code>```

Body:
I have a data frame which looks like this but with altogether 31 variables(columns) and 11000 observations (the missing values are empty):

T1 = c("a1", "c1", "e1", "d1", "a3", "f1", "f2")
T2 = c("b1", "d1", "a1", "b2", "a3", "f1", "f3")
T3 = c(NA, NA, "e1", "d1", NA, "a4", "f3")
T4 = c( NA, NA, NA, "b2", NA, "b3", "f5")
T5 = c( NA, NA, NA, NA, NA, "a4", "f6")
T6 = c( NA, NA, NA, NA, NA,  NA, "f7")
T7 = c(NA, NA, NA, NA, NA, NA, "c1")
T8 = c(NA, NA, NA, NA, NA, NA, "c1")
T9 = c(NA, NA, NA, NA, NA, NA, "f2")
T10= c(NA, NA, NA, NA, NA, NA, "f3")

I would like to identify if there is any duplicated element of the "T" type variables by rows, so my df would look like this:

 T1 = c("a1", "c1", "e1", "d1", "a3", "f1", "f2")
 T2 = c("b1", "d1", "a1", "b2", "a3", "f1", "f3")
 T3 = c(NA, NA, "e1", "d1", NA, "a4", "f3")
 T4 = c( NA, NA, NA, b2, NA, "b3", "f5")
 T5 = c( NA, NA, NA, NA, NA, "a4", "f6")
 T6 = c( NA, NA, NA, NA, NA,  NA, "f7")
 T7 = c(NA, NA, NA, NA, NA, NA, "c1")
 T8 = c(NA, NA, NA, NA, NA, NA, "c1")
 T9 = c(NA, NA, NA, NA, NA, NA, "f2")
 T10= c(NA, NA, NA, NA, NA, NA, "f3")
 D = c(F, F, T, T, T, T, T)

I attempted to write a function but clearly I miss something because it does not work:
first I created a new variable with empty values

df$D <- ""

then the function:

dupl <- function(x){
     for(i in 1:nrow(x))
              if (duplicated(x[i], incomparables = NA)){
            df$D <- "TRUE"
  }else{
    df$D <- "FALSE"
  }
}

df$D <- dupl(df)

I also tried this code but it does not give me the rows (when D takes a value of true) which contains the duplicated elements:

df$D <- apply(df[-1], 1, function(i) any(duplicated(i, incomparables = NA)))

Body:
I'm a fan of dplyr and tidyverse which is why I would go this route:

df <- data.frame(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)

df %>%
mutate(index = row_number()) %>%
gather(key, value, -index, na.rm = T) %>%
group_by(index) %>%
summarise(D = any(duplicated(value))) %>%
cbind(df)


问:
What is GET/ error in node.js application?
I am trying to run my node.js application with npm start

The output I am getting is:

```<code>$ npm start

> alaka@1.0.0 start C:\Users\Alaka\Downloads\A4\API assignment 4
> nodemon app.js

[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node app.js`
</code>```

When I try to connect via localhost, I get error Cannot GET /

I tried running nodemon nodemon ./app.js and nodemon start 9000
  but the error is still the same.

Here's my app.js

```<code>const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

var uploadRouter = require('./Upload/upload');
const app = express();
app.use(express.json());

app.use('/uploads',express.static('./public/uploads'));
app.use(express.urlencoded({ extended: false }));

require('./DB/dbmongoose');
const User = require('./model/user');
const Product= require('./model/product');

app.use(bodyParser.urlencoded({ extended: false }));
app.use('/upload', uploadRouter);
module.exports = app;
app.post('/Register', (req, res) => {

    var user = new User(req.body);
    console.log(req.body);
    user.save();
});

app.get('/Login', function (req, res) {
    User.find().then(function (user) {
        res.send(user);
    }).catch(function (e) {
        res.send(e)
    });

});

app.post('/addproduct', (req, res) => {

    var product = new Product(req.body);
    console.log(req.body);
    product.save().then(function(product){
            res.send(product);
    }).catch(function (e){
        res.send(e);
    });
    });

app.get('/allproduct',(req, res, next) => {
    console.log('ok');
    Product.find({})
        .then((product) => {
            res.json(product);
        }, (err) => next(err))
        .catch((err) => next(err));
});

app.listen(9000);
</code>```

答:
Have you try to use this?</p>

```<code>app.get('/', function (req, res) {
  throw new Error('BROKEN') // Express will catch this on its own.
})
</code>```

Body:
I am trying to run my node.js application with npm start

The output I am getting is:

$ npm start

> alaka@1.0.0 start C:\Users\Alaka\Downloads\A4\API assignment 4
> nodemon app.js

[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node app.js`

When I try to connect via localhost, I get error Cannot GET /

I tried running nodemon nodemon ./app.js and nodemon start 9000
  but the error is still the same.

Here's my app.js

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

var uploadRouter = require('./Upload/upload');
const app = express();
app.use(express.json());

app.use('/uploads',express.static('./public/uploads'));
app.use(express.urlencoded({ extended: false }));

require('./DB/dbmongoose');
const User = require('./model/user');
const Product= require('./model/product');

app.use(bodyParser.urlencoded({ extended: false }));
app.use('/upload', uploadRouter);
module.exports = app;
app.post('/Register', (req, res) => {

    var user = new User(req.body);
    console.log(req.body);
    user.save();
});

app.get('/Login', function (req, res) {
    User.find().then(function (user) {
        res.send(user);
    }).catch(function (e) {
        res.send(e)
    });

});

app.post('/addproduct', (req, res) => {

    var product = new Product(req.body);
    console.log(req.body);
    product.save().then(function(product){
            res.send(product);
    }).catch(function (e){
        res.send(e);
    });
    });

app.get('/allproduct',(req, res, next) => {
    console.log('ok');
    Product.find({})
        .then((product) => {
            res.json(product);
        }, (err) => next(err))
        .catch((err) => next(err));
});

app.listen(9000);

Body:
Have you try to use this?

app.get('/', function (req, res) {
  throw new Error('BROKEN') // Express will catch this on its own.
})


问:
Dynamic Programming - Jumping jacks
Can some one help in solving the below problem using DP technique.

No need of code. Idea should be enough.

Marvel is coming up with a new superhero named Jumping Jack. The co-creator of this superhero is a mathematician, and he adds a mathematical touch to the character's powers.

So, one of Jumping Jack's most prominent powers is jumping distances. But, this superpower comes with certain restrictions.

Jumping Jack can only jump —

To the number that is one kilometre lesser than the current distance. For example, if he is 12 km away from the destination, he won't be able to jump directly to it since he can only jump to a location 11 km away.

To a distance that is half the current distance. For example, if Jumping Jack is 12 km away from the destination, again, he won't be able to jump directly to it since he can only jump to a location 6 km away.

To a distance that is ⅓rd the current distance. For example, if Jumping Jack is 12 km away from the destination, once more, he won't be able to jump directly to it since he can only jump to a location 4 km away.

So, you need to help the superhero develop an algorithm to reach the destination in the minimum number of steps. The destination is defined as the place where the distance becomes 1. Jumping Jack should cover the last 1 km running! Also, he can only jump to a destination that is an integer distance away from the main destination. For example, if he is at 10 km, by jumping 1/3rd the distance, he cannot reach 10/3rd the distance. He has to either jump to 5 or 9.

So, you have to find the minimum number of jumps required to reach a destination. For instance, if the destination is 10 km away, there are two ways to reach it:
10 -> 5 -> 4 -> 2 -> 1 (four jumps)
10 -> 9 -> 3 -> 1 (three jumps)
The minimum of these is three, so the superhero takes a minimum of three jumps to reach the point.

答:
Consider f[1]=0 as the number of jumps required when JumpingJack is 1km away is none.
Using this base value solve F[2]...f[n] in below manner

```<code>        for(int i=2; i<=n; i++) {
            if(i%2==0 && i%3==0) {
                f[i] = Math.min(Math.min(f[i-1]+1, f[i/2]+1), f[i/3] + 1);
            }
            if(i%2==0) {
                f[i] = Math.min(f[i-1]+1, f[i/2]+1);
            }else if(i%3==0) {
                f[i] = Math.min(f[i-1]+1, f[i/3] + 1);
            }else{
                f[i] = f[i-1]+1;
            }
        }
        return f[n];
</code>```

You don't need to recursively solve the subproblem more than once!

Title: Dynamic Programming - Jumping jacks

Body:
Consider f[1]=0 as the number of jumps required when JumpingJack is 1km away is none.
Using this base value solve F[2]...f[n] in below manner

        for(int i=2; i<=n; i++) {
            if(i%2==0 && i%3==0) {
                f[i] = Math.min(Math.min(f[i-1]+1, f[i/2]+1), f[i/3] + 1);
            }
            if(i%2==0) {
                f[i] = Math.min(f[i-1]+1, f[i/2]+1);
            }else if(i%3==0) {
                f[i] = Math.min(f[i-1]+1, f[i/3] + 1);
            }else{
                f[i] = f[i-1]+1;
            }
        }
        return f[n];

You don't need to recursively solve the subproblem more than once!


问:
How to run c++ Files using g++ and Cmake?
I am using Header Only Libraries. The libraries are included through Cmake. I am using the g++ Compiler.
Now what I am looking for is to compile the c++ source files via windows cmd. In this moment i am using clion to compile.

Does anyone know how to compile the source files?
If i am compiling the files without cmake , I am getting errors because the program cannot find the libraries.

答:
You do not run a source file, you run an executable produced by a compiler from  source file(s)

If you are under a Linux for instance enter the path(s) where the libraries are through the environment variable LD_LIBRARY_PATH

[edit after your remark]

I mean compile

To indicate to g++ where the library are to link use the option -L followed by the path of a directory where the libraries are. If your libraries are on different directories use several time the option, one per directory


问:
Why request body is null in file upload with postman in Node.js
I am trying to upload file from postman to the Node.js server. I am using multer and body-parse to parse the body of the request.

Use case:

when I use POST request with raw-JSON as Body in Postman, everything
works fine and I can see the req.body exactly as provided in the Postman and also I can assign new key-value pair to the req.body so that these new variables can be use in further middlewares in the route.

But when I try to upload a file from the postman with form-data as Body in Postman, then still I can get the value from req.body as provided. But after the multer middle layer, the newly assigned values to the req.body (from the middleware) shows corrupted like req.body becomes [Object: null prototype]. I can confirm that Multer is working fine but Multer is corrupting the req.body data (which is created in the route middleware itself)

Please help to identify the meaning of req.body=[Object: null prototype]

答:
I ran into a similar issue. If you console.log(req.body) in the function. you will notice that the body is equal to [Object: null prototype] because Multer is handling the request as the form is multipart. So, if you console.log(req) object, you can find the values that can be retrieved and you can just do req.{Name_of_field} to get values.

If you need clarification please let me know, I might be able to share the code.


问:
React.js: Why i cant see HTML content on the browser?
I started to learn React, i am writing my code on VS Studio. Can someone tell me why i cant see the HTML code on the browser?

!(https://imgur.com/KaIupnw)

答: You are editing an index.js in the root directory of your project, but with create-react-app the index.js you should be editing is in your src folder. Edit the correct index.js file and your changes should show on the browser.</p>


问:
How to use text from text box in Sub statement
I have a file.copy statement where part of the "path" needs to be whatever is in a text box instead of being hard coded

```<code>File.Copy("\\NetworkComputer1\mall\Productionx64\productdesigner.cfg", "c:\mall\NetworkComputer1_productdesingner.cfg", True)
</code>```

In the above, I need NetworkComputer1 to be the value of a specific text box on a form.

Can anyone help me with this?

答:
The 2 paths (origin and destination) are just strings.  I personally like to use variables instead of putting the full path in the file.copy because its easy for me to read.</p>

```<code>Dim FileOrigin as String
Dim FileDestination as String

'adjust the next line based on how the computer name is displayed on the textbox and
'also the name of the textbox itself replacing Textbox1 for the ID of the Textbox.

FileOrigin = "\\" & Textbox1.Text & "\mall\Productionx64\productdesigner.cfg"
FileDestination = "c:\mall\NetworkComputer1_productdesingner.cfg"

File.Copy(FileOrigin, FileDestination, True)
</code>```

Body:
I have a file.copy statement where part of the "path" needs to be whatever is in a text box instead of being hard coded

File.Copy("\\NetworkComputer1\mall\Productionx64\productdesigner.cfg", "c:\mall\NetworkComputer1_productdesingner.cfg", True)

In the above, I need NetworkComputer1 to be the value of a specific text box on a form.

Can anyone help me with this?

Body:
The 2 paths (origin and destination) are just strings.  I personally like to use variables instead of putting the full path in the file.copy because its easy for me to read.

Dim FileOrigin as String
Dim FileDestination as String

'adjust the next line based on how the computer name is displayed on the textbox and
'also the name of the textbox itself replacing Textbox1 for the ID of the Textbox.

FileOrigin = "\\" & Textbox1.Text & "\mall\Productionx64\productdesigner.cfg"
FileDestination = "c:\mall\NetworkComputer1_productdesingner.cfg"

File.Copy(FileOrigin, FileDestination, True)


问:
How do I add a dropdown menu in navbar?
I'd like to know how to add a dropdown menu in my navbar where the "social media" class is.  Here's my code:

  </button>

      Home (current)
      Social Media
      Pricing
      Disabled

</nav
```

答:
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown
  </button>

  Home (current)

  Social Media

  Pricing

  Disabled

```

You have to do several things - wrap your item in 2 div tags. One is with class dropdown. This one contains the button which you click to display the actual dropdown. The other div is with class dropdown menu. This div contains your items. With newer bootstrap you can use buttons instead of link items.

Title: How do I add a dropdown menu in navbar?

Body:
<div class="navbar-nav">
<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown
  </button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu2">
  <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>

  <a class="nav-item nav-link" href="#">Social Media</a>

  <a class="nav-item nav-link" href="#">Pricing</a>

  <a class="nav-item nav-link disabled" href="#">Disabled</a>
  </div>
</div>
</div>

You have to do several things - wrap your item in 2 div tags. One is with class dropdown. This one contains the button which you click to display the actual dropdown. The other div is with class dropdown menu. This div contains your items. With newer bootstrap you can use buttons instead of link items.


问:
Regular expression for a non-zero hex value
I am looking for a regular expression to determine when any of the values in a 32-bit hex value is non-zero.

The data patterns look like 0x00000000 and I want to know when any of the digits is non-zero.  For example, if 0x00001000 or 0x10000000 or 0xB000000 would be capture by the regular expression, but not a 0x00000000 pattern.  Right now I perform a walking pattern match of

```<code>0x[^0]
0x0[^0]
0x00[^0]
...
0x0000000[^0]
</code>```

This will work, but I much rather have one pattern if possible. Thanks.

Mark

Edit:  I didn't mention as the RegEx was not needed in a program, otherwise I would have used a different approach, but I was using the RegEx to search for values in a log file using UltraEdit.  I could have developed a program or some other means to search, but I was just being lazy, just being honest.  Ben S solution worked both in UltraEdit and Rad Software Regular Expression Designer.  rampion solution didn't work in either tool, not sure why.

答:
Fixed size hex numbers can be looked up using negative lookahead as:

```<code>/(0x(?!0{8})[0-9a-fA-F]{8})/
</code>```

A group is looked up beginning with 0x

then negative look ahead 0{8} (fails if found)

otherwise match [0-9a-fA-F]{8}

Works with PCRE, JavaScript, Python. Don't know which editors support negative lookahead.

Body:
I am looking for a regular expression to determine when any of the values in a 32-bit hex value is non-zero.

The data patterns look like 0x00000000 and I want to know when any of the digits is non-zero.  For example, if 0x00001000 or 0x10000000 or 0xB000000 would be capture by the regular expression, but not a 0x00000000 pattern.  Right now I perform a walking pattern match of

0x[^0]
0x0[^0]
0x00[^0]
...
0x0000000[^0]

This will work, but I much rather have one pattern if possible. Thanks.

Mark

Edit:  I didn't mention as the RegEx was not needed in a program, otherwise I would have used a different approach, but I was using the RegEx to search for values in a log file using UltraEdit.  I could have developed a program or some other means to search, but I was just being lazy, just being honest.  Ben S solution worked both in UltraEdit and Rad Software Regular Expression Designer.  rampion solution didn't work in either tool, not sure why.

Body:
Fixed size hex numbers can be looked up using negative lookahead as:

/(0x(?!0{8})[0-9a-fA-F]{8})/

A group is looked up beginning with 0x

then negative look ahead 0{8} (fails if found)

otherwise match [0-9a-fA-F]{8}

Works with PCRE, JavaScript, Python. Don't know which editors support negative lookahead.