问:
Android ListView with custom adapter crashing on SM-T280 tablet
I have two Samsung tablets (Samsung SM-T580 Android 7.0 and SM-T280 Android 5.1).
I have a list view with a custom adapter. It works fine on the SM-T580 but it crashes on the first iteration of method:

```<code>public override View GetView(int position, View convertView, ViewGroup parent)
</code>```

on the SM-T280 tablet. I do not understand how it works perfect on the SM-T580 and crashes on the SM-T280. The error message when it crashes is:

The application is in break mode.

Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code.)

I have the compiler set to:

```<code>Compile using Android version: (Target Framework)
Android 5.1 (Lollipop)
</code>```

I am using Visual Studio 2017 with Xamarin.

The following is my code.

The layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TableLayout
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="2"
        android:id="@+id/tableLayout1">
        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_weight="1">
            <TextView
                android:id="@+id/CompanyNameLabel"
                android:text=""
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:layout_column="1"
                android:layout_gravity="left"
                android:textStyle="bold"
                android:textSize="16sp"
                android:padding="8dip" />
            <TextView
                android:id="@+id/CompanySalesLabel"
                android:text=""
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:layout_column="2"
                android:layout_gravity="right"
                android:padding="8dip" />
        </TableRow>
    </TableLayout>
    <TextView
        android:id="@+id/CompanyAddressLabel"
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="20dip" />
    <TextView
        android:id="@+id/CompanyCityStateZipLabel"
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="20dip" />
</LinearLayout>
</code>```

The view holder code:

```<code>public class MyMainCompanyRowHolder : Java.Lang.Object
{
    public TextView CompanyName { get; set; }
    public TextView CompanyAddress { get; set; }
    public TextView CompanySales { get; set; }
    public TextView CompanyCityStateZipLabel { get; set; }
    public static T Cast<T>(Java.Lang.Object obj) where T : MyMainCompanyRowHolder
    {
        var propInfo = obj.GetType().GetProperty("Instance");
        return propInfo == null ? null : propInfo.GetValue(obj, null) as T;
    }
}
</code>```

The custom adapter:

```<code>public class ListAdapter : BaseAdapter<Company>
{
    List<Company> company;
    Activity context;

    public ListAdapter(Activity currentContext, List<Company> companyList) : base()
    {
        this.company = companyList;
        this.context = currentContext;

    }

    public override Company this[int position]
    {
        get { return company.ToArray()[position]; }
    }

    public override int Count
    {
        get { return company.Count; }
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        Models.ViewHolder.MyMainCompanyRowHolder myViewHolder = null;

        View view = convertView;

        if (view != null)
            myViewHolder = Models.ViewHolder.MyMainCompanyRowHolder.Cast<Models.ViewHolder.MyMainCompanyRowHolder>(view.Tag);

        if (myViewHolder == null)
        {
            myViewHolder = new Models.ViewHolder.MyMainCompanyRowHolder();
            //view = context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null);
            view = context.LayoutInflater.Inflate(Resource.Layout.MainCompanyListRow, null);

            myViewHolder.CompanyName = view.FindViewById<TextView>(Resource.Id.CompanyNameLabel);
            myViewHolder.CompanyAddress = view.FindViewById<TextView>(Resource.Id.CompanyAddressLabel);
            myViewHolder.CompanySales = view.FindViewById<TextView>(Resource.Id.CompanySalesLabel);
            myViewHolder.CompanyCityStateZipLabel = view.FindViewById<TextView>(Resource.Id.CompanyCityStateZipLabel);

            view.Tag = myViewHolder;

        }
        myViewHolder.CompanyName.Text = company.ToArray()[position].CompanyName;
        myViewHolder.CompanyAddress.Text = company.ToArray()[position].Address;
        myViewHolder.CompanySales.Text = company.ToArray()[position].ActualSales.ToString("C0");
        myViewHolder.CompanyCityStateZipLabel.Text = company.ToArray()[position].City + ", " + company.ToArray()[position].State + " " + company.ToArray()[position].Zip;
        return view;
    }
}
</code>```

The call in the Activity module:

```<code>myCompany = myDBF.getCompany("");
var listView = FindViewById<ListView>(Resource.Id.OrderMethodListView);
listView.Adapter = new Models.Adapters.ListAdapter(this, myCompany);
</code>```

答:
Thanks! I figured it out. Android 5.1 does not like:

```<code>android:layout_weight="1"
android:layout_column="1"
android:layout_gravity="left"
</code>```

Once I removed those lines from my Layout Code, the app works correctly.

Body:
I have two Samsung tablets (Samsung SM-T580 Android 7.0 and SM-T280 Android 5.1).
I have a list view with a custom adapter. It works fine on the SM-T580 but it crashes on the first iteration of method:

public override View GetView(int position, View convertView, ViewGroup parent)

on the SM-T280 tablet. I do not understand how it works perfect on the SM-T580 and crashes on the SM-T280. The error message when it crashes is:

The application is in break mode.

Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code.)

I have the compiler set to:

Compile using Android version: (Target Framework)
Android 5.1 (Lollipop)

I am using Visual Studio 2017 with Xamarin.

The following is my code.

The layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TableLayout
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="2"
        android:id="@+id/tableLayout1">
        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_weight="1">
            <TextView
                android:id="@+id/CompanyNameLabel"
                android:text=""
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:layout_column="1"
                android:layout_gravity="left"
                android:textStyle="bold"
                android:textSize="16sp"
                android:padding="8dip" />
            <TextView
                android:id="@+id/CompanySalesLabel"
                android:text=""
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:layout_column="2"
                android:layout_gravity="right"
                android:padding="8dip" />
        </TableRow>
    </TableLayout>
    <TextView
        android:id="@+id/CompanyAddressLabel"
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="20dip" />
    <TextView
        android:id="@+id/CompanyCityStateZipLabel"
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="20dip" />
</LinearLayout>

The view holder code:

public class MyMainCompanyRowHolder : Java.Lang.Object
{
    public TextView CompanyName { get; set; }
    public TextView CompanyAddress { get; set; }
    public TextView CompanySales { get; set; }
    public TextView CompanyCityStateZipLabel { get; set; }
    public static T Cast<T>(Java.Lang.Object obj) where T : MyMainCompanyRowHolder
    {
        var propInfo = obj.GetType().GetProperty("Instance");
        return propInfo == null ? null : propInfo.GetValue(obj, null) as T;
    }
}

The custom adapter:

public class ListAdapter : BaseAdapter<Company>
{
    List<Company> company;
    Activity context;

    public ListAdapter(Activity currentContext, List<Company> companyList) : base()
    {
        this.company = companyList;
        this.context = currentContext;

    }

    public override Company this[int position]
    {
        get { return company.ToArray()[position]; }
    }

    public override int Count
    {
        get { return company.Count; }
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        Models.ViewHolder.MyMainCompanyRowHolder myViewHolder = null;

        View view = convertView;

        if (view != null)
            myViewHolder = Models.ViewHolder.MyMainCompanyRowHolder.Cast<Models.ViewHolder.MyMainCompanyRowHolder>(view.Tag);

        if (myViewHolder == null)
        {
            myViewHolder = new Models.ViewHolder.MyMainCompanyRowHolder();
            //view = context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null);
            view = context.LayoutInflater.Inflate(Resource.Layout.MainCompanyListRow, null);

            myViewHolder.CompanyName = view.FindViewById<TextView>(Resource.Id.CompanyNameLabel);
            myViewHolder.CompanyAddress = view.FindViewById<TextView>(Resource.Id.CompanyAddressLabel);
            myViewHolder.CompanySales = view.FindViewById<TextView>(Resource.Id.CompanySalesLabel);
            myViewHolder.CompanyCityStateZipLabel = view.FindViewById<TextView>(Resource.Id.CompanyCityStateZipLabel);

            view.Tag = myViewHolder;

        }
        myViewHolder.CompanyName.Text = company.ToArray()[position].CompanyName;
        myViewHolder.CompanyAddress.Text = company.ToArray()[position].Address;
        myViewHolder.CompanySales.Text = company.ToArray()[position].ActualSales.ToString("C0");
        myViewHolder.CompanyCityStateZipLabel.Text = company.ToArray()[position].City + ", " + company.ToArray()[position].State + " " + company.ToArray()[position].Zip;
        return view;
    }
}

The call in the Activity module:

myCompany = myDBF.getCompany("");
var listView = FindViewById<ListView>(Resource.Id.OrderMethodListView);
listView.Adapter = new Models.Adapters.ListAdapter(this, myCompany);

Body:
Thanks! I figured it out. Android 5.1 does not like:

android:layout_weight="1"
android:layout_column="1"
android:layout_gravity="left"

Once I removed those lines from my Layout Code, the app works correctly.


来源: stackexchange

问:
Is SonarLint 3.2.0 compatible with sonarqube 6.2?
I am trying to connect to a remote sonarqube 6.2 server from Sonarlint 3.2 plugin in eclipse neon. I am able to connect to my local server http://localhost:9000.

But When I am trying to hit the remote sonar server I am getting below error:

Fail to request https://xxxxxxxxxxxxxx:xxxx/xxx/api/system/status

Please advise.

答:
I ran into this problem myself using SonarLint 3.1 and SonarQube 6.7.

In IntelliJ I kept running into this error message

```<code>Failed to connect to the server. Please check the configuration.
Error: Fail to request https://<SONARQUBE>/api/system/status
</code>```

However I could access that URL through my browser without any issues.

When you WireShark the requests coming from the browser and the IDE you can see that the cypher suite is quite different and that the IDE plugin gets a TLS handshake failure.

That lead me to discover that Java still ships with limited strength cryptographic functions. That’s either because of US export policy or because  nobody has gotten around to fixing it. The internet isn’t quite sure.

Either way, you can download the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files from Oracle: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Once I installed those onto the IntelliJ JVM, I no longer got the underlying TLS handshake failure when trying to connect to SonarQube and the connection works.

ContentLicense: CC BY-SA 3.0

Body:
I ran into this problem myself using SonarLint 3.1 and SonarQube 6.7.

In IntelliJ I kept running into this error message

Failed to connect to the server. Please check the configuration.
Error: Fail to request https://<SONARQUBE>/api/system/status

However I could access that URL through my browser without any issues.

When you WireShark the requests coming from the browser and the IDE you can see that the cypher suite is quite different and that the IDE plugin gets a TLS handshake failure.

That lead me to discover that Java still ships with limited strength cryptographic functions. That’s either because of US export policy or because  nobody has gotten around to fixing it. The internet isn’t quite sure.

Either way, you can download the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files from Oracle: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Once I installed those onto the IntelliJ JVM, I no longer got the underlying TLS handshake failure when trying to connect to SonarQube and the connection works.


问:
Use create-react-app behind corporate firewall
there is any way for work with create-react-app behind corporate firewall by setting a proxy.

i have setted the proxy on npm and yarn, but this is what i see when try to create-react-app my-app:

```<code>Creating a new React app in F:\react\my-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

You appear to be offline.
Falling back to the local Yarn cache.

yarn add v0.23.4
info No lockfile found.
[1/4] Resolving packages...
error Couldn't find any versions for "react" that matches "latest" in our cache. Possible versions: ""
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

Aborting installation.
  yarnpkg add --exact --offline react react-dom react-scripts has failed.

Deleting generated file... package.json
Deleting my-app / from F:\react
Done.
</code>```

答:
Update: Looks like this bug has now been fixed, and should no longer be present in version 1.1.0.

This problem is caused by the fact that the yarn registry is hard-coded in react-scripts to registry.yarnpkg.com: https://github.com/facebookincubator/create-react-app/blob/master/packages/create-react-app/createReactApp.js#L692

As per this pull request, if the yarn registry is not reachable, then it will check to see if you have the https_proxy environment variable set, and then if so it will verify that that server is reachable, instead of the hard-coded yarn registry.

To reiterate, it's not enough to set the proxy/https-proxy configs in npm/yarn - you also need to set the https_proxy environment variable, because that's what create-react-app will check when determining if you are online. For example:

```<code>https_proxy=https://my.corporate.proxy create-react-app my-new-project
</code>```

Body:
there is any way for work with create-react-app behind corporate firewall by setting a proxy.

i have setted the proxy on npm and yarn, but this is what i see when try to create-react-app my-app:

Creating a new React app in F:\react\my-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

You appear to be offline.
Falling back to the local Yarn cache.

yarn add v0.23.4
info No lockfile found.
[1/4] Resolving packages...
error Couldn't find any versions for "react" that matches "latest" in our cache. Possible versions: ""
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

Aborting installation.
  yarnpkg add --exact --offline react react-dom react-scripts has failed.

Deleting generated file... package.json
Deleting my-app / from F:\react
Done.

Body:
Update: Looks like this bug has now been fixed, and should no longer be present in version 1.1.0.

This problem is caused by the fact that the yarn registry is hard-coded in react-scripts to registry.yarnpkg.com: https://github.com/facebookincubator/create-react-app/blob/master/packages/create-react-app/createReactApp.js#L692

As per this pull request, if the yarn registry is not reachable, then it will check to see if you have the https_proxy environment variable set, and then if so it will verify that that server is reachable, instead of the hard-coded yarn registry.

To reiterate, it's not enough to set the proxy/https-proxy configs in npm/yarn - you also need to set the https_proxy environment variable, because that's what create-react-app will check when determining if you are online. For example:

https_proxy=https://my.corporate.proxy create-react-app my-new-project

ContentLicense: CC BY-SA 4.0


问:
PyPy 17x faster than Python. Can Python be sped up?
Solving a recent Advent of Code problem, I found my default Python was ~40x slower than PyPy. I was able to get that down to about 17x with this code by limiting calls to len and limiting global lookups by running it in a function.

Right now, e.py runs in 5.162 seconds on python 3.6.3 and .297 seconds on PyPy on my machine.

My question is: is this the irreducible speedup of JIT, or is there some way to speed up the CPython answer? (short of extreme means: I could go to Cython/Numba or something?) How do I convince myself that there's nothing more I can do?

See the gist for the list of numbers input file.

As described in the problem statement, they represent jump offsets. position += offsets[current], and increment the current offset by 1.  You're done when a jump takes you outside the list.

Here's the example given (the full input that takes 5 seconds is much longer, and has larger numbers):

```<code>(0) 3  0  1  -3  - before we have taken any steps.
(1) 3  0  1  -3  - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1.
 2 (3) 0  1  -3  - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2.
 2  4  0  1 (-3) - jump all the way to the end; leave a 4 behind.
 2 (4) 0  1  -2  - go back to where we just were; increment -3 to -2.
 2  5  0  1  -2  - jump 4 steps forward, escaping the maze.
</code>```

The code:

```<code>def run(cmds):
    location = 0
    counter = 0
    while 1:
        try:
            cmd = cmds[location]
            if cmd >= 3:
                cmds[location] -= 1
            else:
                cmds[location] += 1
            location += cmd
            if location < 0:
                print(counter)
                break
            counter += 1
        except:
            print(counter)
            break

if __name__=="__main__":
    text = open("input.txt").read().strip().split("\n")
    cmds = [int(cmd) for cmd in text]
    run(cmds)
</code>```

edit: I compiled and ran the code with Cython, that dropped runtime to 2.53s, but that's still almost an order of magnitude slower than PyPy.

edit: Numba gets me to within 2x

edit: The best Cython I could write got down to 1.32s, a little over 4x pypy

edit: Moving the cmd variable into a cdef, as suggested by @viraptor, got the Cython down to .157 seconds! Nearly a full order of magnitude faster, and not that far from regular python. Still, I come away from this extremely impressed with the PyPy JIT, which did all this for free!

答:
You can improve small things, but pypy will (most likely) always be faster in this task.

For both CPython and Cython:

Don't read in the whole file at once. You can iterate on lines as you go, which saves you (re)allocation costs. This requires you to pre-allocate the array though.

Maybe switch from a list to an array.

For Cython:

Mark the variable types. Especially the counters as ints and the commands as an array of ints to skip most type checks.

Body:
Solving a recent Advent of Code problem, I found my default Python was ~40x slower than PyPy. I was able to get that down to about 17x with this code by limiting calls to len and limiting global lookups by running it in a function.

Right now, e.py runs in 5.162 seconds on python 3.6.3 and .297 seconds on PyPy on my machine.

My question is: is this the irreducible speedup of JIT, or is there some way to speed up the CPython answer? (short of extreme means: I could go to Cython/Numba or something?) How do I convince myself that there's nothing more I can do?

See the gist for the list of numbers input file.

As described in the problem statement, they represent jump offsets. position += offsets[current], and increment the current offset by 1.  You're done when a jump takes you outside the list.

Here's the example given (the full input that takes 5 seconds is much longer, and has larger numbers):

(0) 3  0  1  -3  - before we have taken any steps.
(1) 3  0  1  -3  - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1.
 2 (3) 0  1  -3  - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2.
 2  4  0  1 (-3) - jump all the way to the end; leave a 4 behind.
 2 (4) 0  1  -2  - go back to where we just were; increment -3 to -2.
 2  5  0  1  -2  - jump 4 steps forward, escaping the maze.

The code:

def run(cmds):
    location = 0
    counter = 0
    while 1:
        try:
            cmd = cmds[location]
            if cmd >= 3:
                cmds[location] -= 1
            else:
                cmds[location] += 1
            location += cmd
            if location < 0:
                print(counter)
                break
            counter += 1
        except:
            print(counter)
            break

if __name__=="__main__":
    text = open("input.txt").read().strip().split("\n")
    cmds = [int(cmd) for cmd in text]
    run(cmds)

edit: I compiled and ran the code with Cython, that dropped runtime to 2.53s, but that's still almost an order of magnitude slower than PyPy.

edit: Numba gets me to within 2x

edit: The best Cython I could write got down to 1.32s, a little over 4x pypy

edit: Moving the cmd variable into a cdef, as suggested by @viraptor, got the Cython down to .157 seconds! Nearly a full order of magnitude faster, and not that far from regular python. Still, I come away from this extremely impressed with the PyPy JIT, which did all this for free!


问:
Adding scripting security to an application
Let's say I have an existing application written in Java which I wish to add scripting support to. This is fairly trivial with Groovy (and just as trivial in .Net with any of the Iron range of dynamic languages).

As trivial as adding the support is, it raises a whole host of questions about script execution and security - and how to implement that security.

Has anyone come across any interesting articles/papers or have any insights into this that they'd like to share? In particular I'd be very interested in architectural things like execution contexts, script authentication, script signing and things along those lines... you know, the kind of stuff that prevents users from running arbitrary scripts they just happened to download which managed to screw up their entire application, whilst still allowing scripts to be useful and flexible.

Quick Edit

I've mentioned signing and authentication as different entities because I see them as different aspects of security.

For example, as the developer/supplier of the application I distribute a signed script. This script is legitimately "data destructive" by design. Such as it's nature, it should only be run by administrators and therefore the vast majority of users/system processes should not be able to run it. This being the case it seems to me that some sort of security/authentication context is required based on the actions the script performs and who is running that script.

答:
script signing

Conceptually, that's just reaching into your cryptographic toolbox and using the tools that exist.  Have people sign their code, validate the signatures on download, and check that the originator of the signature is trusted.

The hard(er) question is what makes people worthy of trust, and who gets to choose that.  Unless your users are techies, they don't want to think about that, and so they won't set good policy.  On the other hand, you'll probably have to let the users introduce trust [unless you want to go for an iPhone AppStore-style walled garden, which it doesn't sound like].

script authentication

How's this different from signing?  Or, is your question just that: "what are the concepts that I should be thinking about here"?

The real question is of course: what do you want your users to be secured against?  Is it only in-transit modification, or do you also want to make guarantees about the behavior of the scripts?  Some examples might be: scripts can't access the file system, scripts can only access a particular subtree of the file system, scripts can't access the network, etc.

I think it might be possible [with a modest amount of work] to provide some guarantees about how scripts access the outside world if they were done in haskell and the IO monad was broken into smaller pieces.  Or, possibly, if you had the scripts run in their own opaque monad with access to a limited part of IO.  Be sure to remove access to unsafe functions.

You may also want to look at the considerations that went into the Java (applet) security model.

I hope this gives you something to think about.

OwnerDisplayName: Leonard H Martin

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Leonard H Martin

OwnerDisplayName: Jonas Kölker


问:
Incomplete implementation of my class?
```<code>//
//  Possession.m
//  RandomPossessions
//
//  Created by Paxton Harman on 1/14/11.
//  Copyright 2011 Santa Barbara City College. All rights reserved.
//

#import "Possession.h"

@implementation Possession
@synthesize possessionName, serialNumber, valueInDollars, dateCreated;
@end

- (id)initWithPossessionName:(NSString *)name;

valueindollars:(int)value
serialNumber:(NSString *)sNumber
{
    // Call the superclass's designated initializer
        self = [super init];
    // Did the superclass's designated initializer fail?
     if (!self)
         return nil;

    // Give the instance variables initial values
    [self setPossessionsName:name];
    [self setSerialNumber:sNumber];
    [self setValueInDollars:value];
    dateCreated = [[NSDate alloc] init];

    // Return the address of the newly initialized object
    return self;

}
- (id)initWithPossessionName:(NSString *)name
{
    return [self initWithossessionName:name
                        valueInDollars:0
                         serialnNumber:@""];
}
@end

- (NSString *)description {

    NSString *descriptionString =
        [[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d, Recorded on %@",
                        possessionName,
                        serialNumber,
                        valueInDollars,
                        dateCreated];
    return descriptionString;
}

- (id)init {
    return [self initWithPossessionName:@"Possession"
                         valueInDollars:0
                           serialNumber:@""];
}

+(id)randomPossesion {

// Create two arrays with a list of possible adjectives and nouns
// Note: When using NSArray's arrayWithObjects;, you can pass as many
// objects as you like. At the end of that list, you put nil to
// signify that there are no more objects - otherwise you will crash.
// The nil value is not added to the array, but it used by the method
// to determine the end of the list.
    NSArray *randomAdjectiveList = [NSArray array WithObjects:@"Fluffy",
@"Rusty",
                                    @"Shiny", nil];
    NSArray *randomNounList = [NSArray arrayWithObjects:@"Bear",
@"Spork",
                               @"Mac", nil];

// Get the index of random adjective/noun from the lists
// Note: The % operator, called the modulo operator, gives
// you the remainder. So adjectiveIndex is a random number
// from 0 to 2 inclusive, in this case.
    int adjectiveIndex = random() % [randomAdjectiveList count];
    int nounIndex = random() % [randomNounList count];

    NSString *randomName = [NSString stringWithFormat:@"%@ %@",
                            [randomAdjectiveList objectAtIndex:adjectiveIndex],
                            [randomNounList objectAtIndex:nounIndex]];

    int randomValue = random() % 100;

    NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c",
'0' + random() % 10,
'A' + random() % 26,
'0' + random() % 10,
'A' + random() % 26,
                                    '0' + random() % 10];

// Once again, ignore the memory problems with this method
// We use "self" instead of the name of the class in class methods...
// Keep reading to find out why
Possession *newPossesion =
    [[self alloc] initWithPossessionName:randomName
                          valueInDollars:randomValue
                            serialNumber:randomSerialNumber];
    return newPossession;
}
</code>```

at line 14 and 19 it's giving me "incomplete implementation of possesion" and Expected '{' before 'valueindollars, respectfully. Any help?? new to cocoa

答:
Jacob is right. Also you should do

```<code>@interface Possession (private)

- (id)initWithPossessionName:(NSString *)name;

@end
</code>```

before your implementation block. Method declarations can't appear in an implementation; they must go in the interface. Your function prototypes are being advertised to your class only so they are in that sense private. But private isn't a special name here, you could say

```<code>@interface Possession (frobozz)
</code>```

if you wanted. Just not

```<code>@interface Possession
</code>```

because that would duplicate the interface definition that is probably in your .h file.
So the whole thing must look like

```<code>@import "Possession.h"
// public prototypes, properties, ivars etc. in the .h file

@interface Possession (private)
// prototypes here
@end

@implementation Possession

// all your code here

@end

// end is the last thing in the file
</code>```

Title: Incomplete implementation of my class?

Body:
//
//  Possession.m
//  RandomPossessions
//
//  Created by Paxton Harman on 1/14/11.
//  Copyright 2011 Santa Barbara City College. All rights reserved.
//

#import "Possession.h"

@implementation Possession
@synthesize possessionName, serialNumber, valueInDollars, dateCreated;
@end

- (id)initWithPossessionName:(NSString *)name;

valueindollars:(int)value
serialNumber:(NSString *)sNumber
{
    // Call the superclass's designated initializer
        self = [super init];
    // Did the superclass's designated initializer fail?
     if (!self)
         return nil;

    // Give the instance variables initial values
    [self setPossessionsName:name];
    [self setSerialNumber:sNumber];
    [self setValueInDollars:value];
    dateCreated = [[NSDate alloc] init];

    // Return the address of the newly initialized object
    return self;

}
- (id)initWithPossessionName:(NSString *)name
{
    return [self initWithossessionName:name
                        valueInDollars:0
                         serialnNumber:@""];
}
@end

- (NSString *)description {

    NSString *descriptionString =
        [[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d, Recorded on %@",
                        possessionName,
                        serialNumber,
                        valueInDollars,
                        dateCreated];
    return descriptionString;
}

- (id)init {
    return [self initWithPossessionName:@"Possession"
                         valueInDollars:0
                           serialNumber:@""];
}

+(id)randomPossesion {

// Create two arrays with a list of possible adjectives and nouns
// Note: When using NSArray's arrayWithObjects;, you can pass as many
// objects as you like. At the end of that list, you put nil to
// signify that there are no more objects - otherwise you will crash.
// The nil value is not added to the array, but it used by the method
// to determine the end of the list.
    NSArray *randomAdjectiveList = [NSArray array WithObjects:@"Fluffy",
@"Rusty",
                                    @"Shiny", nil];
    NSArray *randomNounList = [NSArray arrayWithObjects:@"Bear",
@"Spork",
                               @"Mac", nil];

// Get the index of random adjective/noun from the lists
// Note: The % operator, called the modulo operator, gives
// you the remainder. So adjectiveIndex is a random number
// from 0 to 2 inclusive, in this case.
    int adjectiveIndex = random() % [randomAdjectiveList count];
    int nounIndex = random() % [randomNounList count];

    NSString *randomName = [NSString stringWithFormat:@"%@ %@",
                            [randomAdjectiveList objectAtIndex:adjectiveIndex],
                            [randomNounList objectAtIndex:nounIndex]];

    int randomValue = random() % 100;

    NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c",
'0' + random() % 10,
'A' + random() % 26,
'0' + random() % 10,
'A' + random() % 26,
                                    '0' + random() % 10];

// Once again, ignore the memory problems with this method
// We use "self" instead of the name of the class in class methods...
// Keep reading to find out why
Possession *newPossesion =
    [[self alloc] initWithPossessionName:randomName
                          valueInDollars:randomValue
                            serialNumber:randomSerialNumber];
    return newPossession;
}

at line 14 and 19 it's giving me "incomplete implementation of possesion" and Expected '{' before 'valueindollars, respectfully. Any help?? new to cocoa

Body:
Jacob is right. Also you should do

@interface Possession (private)

- (id)initWithPossessionName:(NSString *)name;

@end

before your implementation block. Method declarations can't appear in an implementation; they must go in the interface. Your function prototypes are being advertised to your class only so they are in that sense private. But private isn't a special name here, you could say

@interface Possession (frobozz)

if you wanted. Just not

@interface Possession

because that would duplicate the interface definition that is probably in your .h file.
So the whole thing must look like

@import "Possession.h"
// public prototypes, properties, ivars etc. in the .h file

@interface Possession (private)
// prototypes here
@end

@implementation Possession

// all your code here

@end

// end is the last thing in the file


问:
How to groupby() aggregate on multiple columns and rename the multi-index in Pandas 0.21+?
Code

```<code>import pandas as pd
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
                    'B': range(5),
                    'C': range(5)})

df1 = df.groupby('A').B.agg({'B': ['count','nunique'],'C': ['sum','median']})
df1.columns = ["_".join(x) for x in df1.columns.ravel()]
</code>```

df1 Output

```<code>   B_count  B_nunique  C_sum  C_median
A
1        3          3      3       1.0
2        2          2      7       3.5
</code>```

Warning

```<code>__main__:1: FutureWarning: using a dict on a Series for aggregation
is deprecated and will be removed in a future version
</code>```

This was the recommended way to groupby and rename till Pandas 0.20. What is the elegant way to achieve the same df1 output without this warning?

答:
As @Wen stated in question comments, remove the '.B' before agg, and your dictionary inside of agg is proper.  Next, you can use map and join to flatten that multiindex columns.

```<code>import pandas as pd
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
                    'B': range(5),
                    'C': range(5)})

df1 = df.groupby('A').agg({'B': ['count','nunique'],'C': ['sum','median']})
df1.columns = df1.columns.map('_'.join)
</code>```

Output:

```<code>   B_count  B_nunique  C_sum  C_median
A
1        3          3      3       1.0
2        2          2      7       3.5
</code>```

Body:
Code

import pandas as pd
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
                    'B': range(5),
                    'C': range(5)})

df1 = df.groupby('A').B.agg({'B': ['count','nunique'],'C': ['sum','median']})
df1.columns = ["_".join(x) for x in df1.columns.ravel()]

df1 Output

   B_count  B_nunique  C_sum  C_median
A
1        3          3      3       1.0
2        2          2      7       3.5

Warning

__main__:1: FutureWarning: using a dict on a Series for aggregation
is deprecated and will be removed in a future version

This was the recommended way to groupby and rename till Pandas 0.20. What is the elegant way to achieve the same df1 output without this warning?

Body:
As @Wen stated in question comments, remove the '.B' before agg, and your dictionary inside of agg is proper.  Next, you can use map and join to flatten that multiindex columns.

import pandas as pd
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
                    'B': range(5),
                    'C': range(5)})

df1 = df.groupby('A').agg({'B': ['count','nunique'],'C': ['sum','median']})
df1.columns = df1.columns.map('_'.join)

Output:

   B_count  B_nunique  C_sum  C_median
A
1        3          3      3       1.0
2        2          2      7       3.5


问:
How to detect when AVPlayer video ends playing?
I'am using AVPlayer for playing local video file (mp4) in Swift.
Does anyone know how to detect when video finish with playing?
Thanks</p>

答:
I know there are a lot of accepted answers here...

But, another route might be to add a boundary time observer to your AVPlayer.  You would have to have the duration of the video, which you can get from your player.currentItem, and then add it as your desired time boundary.

```<code>fileprivate var videoEndObserver: Any?

func addVideoEndObserver() {
    guard let player = YOUR_VIDEO_PLAYER else { return }

    // This is just in case you are loading a video from a URL.
    guard let duration = player.currentItem?.duration, duration.value != 0 else {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { [weak self] in
            self?.addVideoEndObserver()
        })

        return
    }

    let endTime = NSValue(time: duration - CMTimeMakeWithSeconds(0.1, duration.timescale))
    videoEndObserver = player.addBoundaryTimeObserver(forTimes: [endTime], queue: .main, using: {
        self.removeVideoEndObserver()

        // DO YOUR STUFF HERE...
    })
}

func removeVideoEndObserver() {
    guard let observer = videoEndObserver else { return }

    videoPlayer.player?.removeTimeObserver(observer)
    videoEndObserver = nil
}
</code>```

Body:
I know there are a lot of accepted answers here...

But, another route might be to add a boundary time observer to your AVPlayer.  You would have to have the duration of the video, which you can get from your player.currentItem, and then add it as your desired time boundary.

fileprivate var videoEndObserver: Any?

func addVideoEndObserver() {
    guard let player = YOUR_VIDEO_PLAYER else { return }

    // This is just in case you are loading a video from a URL.
    guard let duration = player.currentItem?.duration, duration.value != 0 else {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { [weak self] in
            self?.addVideoEndObserver()
        })

        return
    }

    let endTime = NSValue(time: duration - CMTimeMakeWithSeconds(0.1, duration.timescale))
    videoEndObserver = player.addBoundaryTimeObserver(forTimes: [endTime], queue: .main, using: {
        self.removeVideoEndObserver()

        // DO YOUR STUFF HERE...
    })
}

func removeVideoEndObserver() {
    guard let observer = videoEndObserver else { return }

    videoPlayer.player?.removeTimeObserver(observer)
    videoEndObserver = nil
}


问:
JUnit Branch Coverage
I am getting 1/4 branch coverage when I run this JUnit test. However, when I change the if statement to "if (points == 1 || points == 2 || points == 3 || points == 4)" it passes the JUnit test. What am I doing wrong?

Main class:

```<code>public int getPoints() {
    return points;
}

public Grade(int p) throws IllegalArgumentException {
    if (p < 1 || p > 20)
        throw new IllegalArgumentException();
    points = p;
}

// Your additions/changes below this line

public Classification classify() {

    if (points >= 1 && points <= 4) {
        return Classification.First;
    }
    else {
        throw new IllegalArgumentException("Not a Grade");
    }
}
</code>```

JUnit Test:

```<code> @Test
 public void testFirst() {
    Assert.assertEquals(Classification.First, new Grade(1).classify());
    Assert.assertEquals(Classification.First, new Grade(2).classify());
    Assert.assertEquals(Classification.First, new Grade(3).classify());
    Assert.assertEquals(Classification.First, new Grade(4).classify());
}
</code>```

答:
Adding these additional tests to verify edge cases will increase your JUnit coverage to 4/4 for both the constructor and classify methods, at the cost of making a bunch of (possibly) worthless test cases, and also breaking data encapsulation (since you have duplicate validation checks in each of these methods).

```<code>@Test(expected = IllegalArgumentException.class)
public void TestSecond()
{
    new Grade(0).classify();
}

@Test(expected = IllegalArgumentException.class)
public void TestThird()
{
    new Grade(5).classify();
}

@Test(expected = IllegalArgumentException.class)
public void TestFourth()
{
    final Grade g = new Grade(1);
    g.points = 0;
    g.classify();
}

@Test(expected = IllegalArgumentException.class)
public void TestFifth()
{
    final Grade g = new Grade(1);
    g.points = 5;
    g.classify();
}
</code>```

Title: JUnit Branch Coverage

Body:
I am getting 1/4 branch coverage when I run this JUnit test. However, when I change the if statement to "if (points == 1 || points == 2 || points == 3 || points == 4)" it passes the JUnit test. What am I doing wrong?

Main class:

public int getPoints() {
    return points;
}

public Grade(int p) throws IllegalArgumentException {
    if (p < 1 || p > 20)
        throw new IllegalArgumentException();
    points = p;
}

// Your additions/changes below this line

public Classification classify() {

    if (points >= 1 && points <= 4) {
        return Classification.First;
    }
    else {
        throw new IllegalArgumentException("Not a Grade");
    }
}

JUnit Test:

 @Test
 public void testFirst() {
    Assert.assertEquals(Classification.First, new Grade(1).classify());
    Assert.assertEquals(Classification.First, new Grade(2).classify());
    Assert.assertEquals(Classification.First, new Grade(3).classify());
    Assert.assertEquals(Classification.First, new Grade(4).classify());
}

Body:
Adding these additional tests to verify edge cases will increase your JUnit coverage to 4/4 for both the constructor and classify methods, at the cost of making a bunch of (possibly) worthless test cases, and also breaking data encapsulation (since you have duplicate validation checks in each of these methods).

@Test(expected = IllegalArgumentException.class)
public void TestSecond()
{
    new Grade(0).classify();
}

@Test(expected = IllegalArgumentException.class)
public void TestThird()
{
    new Grade(5).classify();
}

@Test(expected = IllegalArgumentException.class)
public void TestFourth()
{
    final Grade g = new Grade(1);
    g.points = 0;
    g.classify();
}

@Test(expected = IllegalArgumentException.class)
public void TestFifth()
{
    final Grade g = new Grade(1);
    g.points = 5;
    g.classify();
}


问:
unable to connect to Sonarqube via intellij (SonarLint)
I am trying to integrate sonarqube(version 5.1.2) with intellij(2016.2). I have added sonarLint plugin.
when I am trying to add a sonar server to the sonarLint settings it asks for username and password for sonar server and other details like url.
But it somehow is unable to connect to the sonar server and gives error :
Fail to request : https://example.com/api/system/status

答:
I ran into something similar myself using SonarLint 3.1 and SonarQube 6.7.

In IntelliJ I kept running into this error message

```<code>Failed to connect to the server. Please check the configuration.
Error: Fail to request https://<SONARQUBE>/api/system/status
</code>```

However I could access that URL through my browser without any issues.

When you WireShark the requests coming from the browser and the IDE you can see that the cypher suite is quite different and that the IDE plugin gets a TLS handshake failure.

That lead me to discover that Java still ships with limited strength cryptographic functions. That’s either because of US export policy or because  nobody has gotten around to fixing it. The internet isn’t quite sure.

Either way, you can download the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files from Oracle: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Once I installed those onto the IntelliJ JVM, I no longer got the underlying TLS handshake failure when trying to connect to SonarQube and the connection works.

Body:
I ran into something similar myself using SonarLint 3.1 and SonarQube 6.7.

In IntelliJ I kept running into this error message

Failed to connect to the server. Please check the configuration.
Error: Fail to request https://<SONARQUBE>/api/system/status

However I could access that URL through my browser without any issues.

When you WireShark the requests coming from the browser and the IDE you can see that the cypher suite is quite different and that the IDE plugin gets a TLS handshake failure.

That lead me to discover that Java still ships with limited strength cryptographic functions. That’s either because of US export policy or because  nobody has gotten around to fixing it. The internet isn’t quite sure.

Either way, you can download the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files from Oracle: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Once I installed those onto the IntelliJ JVM, I no longer got the underlying TLS handshake failure when trying to connect to SonarQube and the connection works.


问:
How can I use threads in Java?
I use Thread in Java. I create a class that extend Thread and it's fine, but the problem is, when call this Thread, I don't know the number of instances of this class, since the user must enter this number.  For example:

```<code>multiThread multiThreadInstance = new multiThread(/* number entered from user */);
multiThreadInstance.start();
</code>```

This will call this thread once, but if i write:

```<code>multiThread multiThreadInstance1 = new multiThread(/* number entered from user */)
multiThreadInstance1.start()
multiThread multiThreadInstance2 = new multiThread(/* number entered from user */)
multiThreadInstance2.start()
</code>```

This will call it twice at the same time, and so on.

If I put it in a for loop, then if user enters 3 for example, then start1 runs, when start1 finishes, start2 runs, when start2 finishes, start3 runs.  I need to keep these instances of thread running in at the same time.  How can i do this?

答:
I suspect that you have accidentally overridden the start() method in Thread. Make sure it is the run() method you're overriding.

If you override the start() method with your own implementation, you "remove the magic" of the Thread class. The magic lies in start() which starts the execution of the run() method in a fresh thread, so keep your own code in run().

Title: How can I use threads in Java?

Body:
I use Thread in Java. I create a class that extend Thread and it's fine, but the problem is, when call this Thread, I don't know the number of instances of this class, since the user must enter this number.  For example:

multiThread multiThreadInstance = new multiThread(/* number entered from user */);
multiThreadInstance.start();

This will call this thread once, but if i write:

multiThread multiThreadInstance1 = new multiThread(/* number entered from user */)
multiThreadInstance1.start()
multiThread multiThreadInstance2 = new multiThread(/* number entered from user */)
multiThreadInstance2.start()

This will call it twice at the same time, and so on.

If I put it in a for loop, then if user enters 3 for example, then start1 runs, when start1 finishes, start2 runs, when start2 finishes, start3 runs.  I need to keep these instances of thread running in at the same time.  How can i do this?


问:
How to use Microsoft's Linguistics Analysis API?
I am trying to accomplish the ability to use Microsoft's Cognitive Service called Linguistics Analysis. The nuget package Microsoft.ProjectOxford.Linguistics does not exist, or at least I am unable to find it when I search for it.

I expect to be able to add the nuget package, however, it is not there. Has anyone tried to use it recently?

答:
There is a NuGet package (PCL.Cognitive.LinguisticAnalysis), but it is buggy (I get errors when running AnalyzeTextAsync) and its seems it is not maintained anymore.

I suggest that you use the Client Library.

Download this repository: https://github.com/Microsoft/Cognitive-LinguisticAnalysis-Windows

Copy the ClientLibrary project to your solution

Use that ClientLibrary (you may need to update Newtonsoft.Json in this project for it to work properly)


问:
access c multidemensional array with only one argument?
I am reading this C code, and I find it difficult to understand what's going on.

Here is the array:

```<code>static const char   gradient[32][4] =
{
{ 1,  1,  1,  0}, { 1,  1,  0,  1}, { 1,  0,  1,  1}, { 0,  1,  1,  1},
{ 1,  1, -1,  0}, { 1,  1,  0, -1}, { 1,  0,  1, -1}, { 0,  1,  1, -1},
{ 1, -1,  1,  0}, { 1, -1,  0,  1}, { 1,  0, -1,  1}, { 0,  1, -1,  1},
{ 1, -1, -1,  0}, { 1, -1,  0, -1}, { 1,  0, -1, -1}, { 0,  1, -1, -1},
{-1,  1,  1,  0}, {-1,  1,  0,  1}, {-1,  0,  1,  1}, { 0, -1,  1,  1},
{-1,  1, -1,  0}, {-1,  1,  0, -1}, {-1,  0,  1, -1}, { 0, -1,  1, -1},
{-1, -1,  1,  0}, {-1, -1,  0,  1}, {-1,  0, -1,  1}, { 0, -1, -1,  1},
{-1, -1, -1,  0}, {-1, -1,  0, -1}, {-1,  0, -1, -1}, { 0, -1, -1, -1},
};
</code>```

and it's 32*4, this is another part of the code that trying to access this array:

```<code>const char * g0000 = gradient[Indice (x1, y1, z1, t1)];
</code>```

Indice is a function that returns an int. So what is this g0000 (I know it's a pointer), say Indice returns 1, what is the value g0000 holds? I mostly code in C# to my understanding if you want to access multidimensional array you would need several arguments, but here is only one, I am really confused...

答:
The type of gradient is static const char[32][4] i.e. a two dimensional array of chars. When you dereference it twice using [] operator you get a char.

But in this case when you deference only once you get const char[4] which can be decayed into const char* and assigned to g0000.

Precisely, g0000 will hold the address of the 2nd sub-array if Indice(x1, y1, z1, t1) returned 1.

Body:
I am reading this C code, and I find it difficult to understand what's going on.

Here is the array:

static const char   gradient[32][4] =
{
{ 1,  1,  1,  0}, { 1,  1,  0,  1}, { 1,  0,  1,  1}, { 0,  1,  1,  1},
{ 1,  1, -1,  0}, { 1,  1,  0, -1}, { 1,  0,  1, -1}, { 0,  1,  1, -1},
{ 1, -1,  1,  0}, { 1, -1,  0,  1}, { 1,  0, -1,  1}, { 0,  1, -1,  1},
{ 1, -1, -1,  0}, { 1, -1,  0, -1}, { 1,  0, -1, -1}, { 0,  1, -1, -1},
{-1,  1,  1,  0}, {-1,  1,  0,  1}, {-1,  0,  1,  1}, { 0, -1,  1,  1},
{-1,  1, -1,  0}, {-1,  1,  0, -1}, {-1,  0,  1, -1}, { 0, -1,  1, -1},
{-1, -1,  1,  0}, {-1, -1,  0,  1}, {-1,  0, -1,  1}, { 0, -1, -1,  1},
{-1, -1, -1,  0}, {-1, -1,  0, -1}, {-1,  0, -1, -1}, { 0, -1, -1, -1},
};

and it's 32*4, this is another part of the code that trying to access this array:

const char * g0000 = gradient[Indice (x1, y1, z1, t1)];

Indice is a function that returns an int. So what is this g0000 (I know it's a pointer), say Indice returns 1, what is the value g0000 holds? I mostly code in C# to my understanding if you want to access multidimensional array you would need several arguments, but here is only one, I am really confused...


问:
Sort an array of names except for one item
Considering that I have an object like the following where it's possible to have many names and that 'The others' can appear at any index, how can I sort the array having 'The others' always as the first element and the rest of the names sorted in alphabetical order?

```<code>var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];
</code>```

For the sample array above, the desired result would be:

```<code>[
   { id: 3, name: 'The others' },
   { id: 4, name: 'John' },
   { id: 2, name: 'Mary' },
   { id: 1, name: 'Paul' }
]
</code>```

答:
Try the following:

var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];
var notConsidered = friends.filter(friend => friend.name == 'The others');
var friend = friends.filter(friend => friend.name!= 'The others');
var sortedfriend = friend.sort(function (a, b) {
  if (a.name  b.name) return 1;
  return 0;
});

sortedfriend.unshift(notConsidered[0])
console.log(sortedfriend);```

Body:
Considering that I have an object like the following where it's possible to have many names and that 'The others' can appear at any index, how can I sort the array having 'The others' always as the first element and the rest of the names sorted in alphabetical order?

var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];

For the sample array above, the desired result would be:

[
   { id: 3, name: 'The others' },
   { id: 4, name: 'John' },
   { id: 2, name: 'Mary' },
   { id: 1, name: 'Paul' }
]

Body:
Try the following:

var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];
var notConsidered = friends.filter(friend => friend.name == 'The others');
var friend = friends.filter(friend => friend.name!= 'The others');
var sortedfriend = friend.sort(function (a, b) {
  if (a.name < b.name) return -1;
  else if (a.name > b.name) return 1;
  return 0;
});

sortedfriend.unshift(notConsidered[0])
console.log(sortedfriend);


答:
copy your (The others object) and store it into a variable using filter

remove it from the array using filter

sort the array by name property.

add the (The others object) in the beginning of your array using unshift

compare function copied from this answer

var friends = [{
        id: 1,
        name: 'Paul'
    },
    {
        id: 2,
        name: 'Mary'
    },
    {
        id: 3,
        name: 'The others'
    },
    {
        id: 4,
        name: 'John'
    }
];

function compare(a,b) {
    if (a.name  b.name)
      return 1;
    return 0;
  }

// copy the others object
const theOthersObj = friends.filter(friend => friend.name === 'The others')[0];

const newFriends = friends
            .filter(friend => friend.name !== 'The others') // removing the others object
            .sort(compare) // storing the array by name
// Adding the others object in the first of the array
newFriends.unshift(theOthersObj);

console.log(newFriends);```

Title: Sort an array of names except for one item

Body:
copy your (The others object) and store it into a variable using filter

remove it from the array using filter

sort the array by name property.

add the (The others object) in the beginning of your array using unshift

compare function copied from this answer

var friends = [{
        id: 1,
        name: 'Paul'
    },
    {
        id: 2,
        name: 'Mary'
    },
    {
        id: 3,
        name: 'The others'
    },
    {
        id: 4,
        name: 'John'
    }
];

function compare(a,b) {
    if (a.name < b.name)
      return -1;
    if (a.name > b.name)
      return 1;
    return 0;
  }

// copy the others object
const theOthersObj = friends.filter(friend => friend.name === 'The others')[0];

const newFriends = friends
            .filter(friend => friend.name !== 'The others') // removing the others object
            .sort(compare) // storing the array by name
// Adding the others object in the first of the array
newFriends.unshift(theOthersObj);

console.log(newFriends);


问:
Is there a CSS Bounce Transition
Hello I wondering if there is a transition to make the purple div (the one that slides down when you hover over the feeling down? picture) bounce when it reaches the end?

here is the code- and jsFiddlle Demo link

HTML

```<code><div class="img">
    <div class="hover"><h2>project 1</h2></div>
</div>
</code>```

CSS

```<code>.img {
    width: 457px;
    height: 288px;
    background-image: url("http://i59.tinypic.com/xdulh2.png");
    position:relative;
    overflow:hidden;
}

h2 {
font-family: avenir;
font-weight: bold;
font-size: 40px;
color: #000;
}

.hover {
    position:absolute;
    top:-100%;
    width: 457px;
    height: 288px;
    background: rgba(130,76,158,0.5);
     -webkit-transition:all 1s;

}

.img:hover .hover {
    top:0;
}
</code>```

an example of the transition i mean you can see here http://www.ollygibbs.com

答:
CSS Transition doesn't have bounce-style timing function, so we have to code it with CSS animation keyframes. The problem here is - how to easily decompose a bouncing ( or any other ) functions into a keyframe series over certain style?

This was the problem I encountered when I build transition.css, so I built a tool "easing.css" to help me generate keyframes from arbitrary equations.

The idea is simple; say we want to make a bounce effect:

we first make a timing function f(t) for our desired effect, such as

Math.abs(Math.sin(1.2 + (t ** 1.4) * 23)) * ( 1 - t ) ** 2.8

according to how the output of this function changes, we sampled this function with different interval from 0 to 1.

use the sampled (t, f(t)) pairs to generate the css animation keyframes.

apply the result animation when we need a transition.

with the concept above, easing.css also provides several timing function preset so you can play with. Below is a 15-frames bouncing animations generated via easing.css, you could make it more like a real bounce by increasing the frame count or tweaking the timing function provided:

```<code>.your-block {
  animation: YourAnimation 2s linear 1s;
}
@keyframes YourAnimation {
  0% { height: 7px; }
  8% { height: 24px; }
  10% { height: 36px; }
  17% { height: 99px; }
  19% { height: 83px; }
  21% { height: 69px; }
  24% { height: 57px; }
  25% { height: 56px; }
  27% { height: 59px; }
  34% { height: 100px; }
  36% { height: 88px; }
  38% { height: 80px; }
  48% { height: 100px; }
  72% { height: 100px; }
  100% { height: 100px; }
}
</code>```

Title: Is there a CSS Bounce Transition

Body:
Hello I wondering if there is a transition to make the purple div (the one that slides down when you hover over the feeling down? picture) bounce when it reaches the end?

here is the code- and jsFiddlle Demo link

HTML

project 1

CSS

.img {
    width: 457px;
    height: 288px;
    background-image: url("http://i59.tinypic.com/xdulh2.png");
    position:relative;
    overflow:hidden;
}

h2 {
font-family: avenir;
font-weight: bold;
font-size: 40px;
color: #000;
}

.hover {
    position:absolute;
    top:-100%;
    width: 457px;
    height: 288px;
    background: rgba(130,76,158,0.5);
     -webkit-transition:all 1s;

}

.img:hover .hover {
    top:0;
}

an example of the transition i mean you can see here http://www.ollygibbs.com

Body:
CSS Transition doesn't have bounce-style timing function, so we have to code it with CSS animation keyframes. The problem here is - how to easily decompose a bouncing ( or any other ) functions into a keyframe series over certain style?

This was the problem I encountered when I build transition.css, so I built a tool "easing.css" to help me generate keyframes from arbitrary equations.

The idea is simple; say we want to make a bounce effect:

we first make a timing function f(t) for our desired effect, such as

Math.abs(Math.sin(1.2 + (t ** 1.4) * 23)) * ( 1 - t ) ** 2.8

according to how the output of this function changes, we sampled this function with different interval from 0 to 1.

use the sampled (t, f(t)) pairs to generate the css animation keyframes.

apply the result animation when we need a transition.

with the concept above, easing.css also provides several timing function preset so you can play with. Below is a 15-frames bouncing animations generated via easing.css, you could make it more like a real bounce by increasing the frame count or tweaking the timing function provided:

.your-block {
  animation: YourAnimation 2s linear 1s;
}
@keyframes YourAnimation {
  0% { height: 7px; }
  8% { height: 24px; }
  10% { height: 36px; }
  17% { height: 99px; }
  19% { height: 83px; }
  21% { height: 69px; }
  24% { height: 57px; }
  25% { height: 56px; }
  27% { height: 59px; }
  34% { height: 100px; }
  36% { height: 88px; }
  38% { height: 80px; }
  48% { height: 100px; }
  72% { height: 100px; }
  100% { height: 100px; }
}


问:
django authentication package: 'auth' not registered as a namespace
I'm trying to build a simple website with user authentication based on this tutorial, but I'm running into the above error. As per the instructions I set a url as folllows:

```<code>url('^accounts/', include('django.contrib.auth.urls'))
</code>```

I got this error in response: 'auth' is not a registered namespace So I tried to register a namespace as the tutorial repo shows:

```<code>url('^accounts/', include('django.contrib.auth.urls', namespace="auth")),
</code>```

then I get the error :
    Specifying a namespace in include() without providing an app_name

I realised that the tutorial is using django 1.8.3, but I'm on 2.0. The issue is resolved when I switch to the same django version in virtualenv, but I'm now having to a change a number of other things across the project to keep it from breaking. Any way to fix without require django 1.8? Thanks.

答:
The URL routing syntax has been changed in Django 2.0, maybe try doing:</p>

```<code>from django.urls import path
path('accounts/', include('django.contrib.auth.urls')),
</code>```

Body:
I'm trying to build a simple website with user authentication based on this tutorial, but I'm running into the above error. As per the instructions I set a url as folllows:

url('^accounts/', include('django.contrib.auth.urls'))

I got this error in response: 'auth' is not a registered namespace So I tried to register a namespace as the tutorial repo shows:

url('^accounts/', include('django.contrib.auth.urls', namespace="auth")),

then I get the error :
    Specifying a namespace in include() without providing an app_name

I realised that the tutorial is using django 1.8.3, but I'm on 2.0. The issue is resolved when I switch to the same django version in virtualenv, but I'm now having to a change a number of other things across the project to keep it from breaking. Any way to fix without require django 1.8? Thanks.

Body:
The URL routing syntax has been changed in Django 2.0, maybe try doing:

from django.urls import path
path('accounts/', include('django.contrib.auth.urls')),


问:
How to alert on queue size on azure service bus
I have a premium service bus in Azure with a number of Queues. I can set max size for these, but I can't seem to find a way to alert the support team, via any route, but I would prefer email, if these queues exceed 1,000 messages in length, ie our consumers have fallen over or are not processing fast enough.

How can I set up some form of alerting for queue length on Azure service bus?

P.S. we still seem to be waiting for it to be implemented as a first class feature: https://feedback.azure.com/forums/231545-diagnostics-and-monitoring/suggestions/4486464-alerts-based-on-queue-size

答:
Traditionally, a solution was indeed to pull message counts using NamespaceManager and report that value periodically. While it's an approach that works, there's another alternative that is emerging these days - Azure Monitor Service.

With this approach, unlike polling for data, Azure Service Bus is reporting to Monitor the metrics. Those metrics can be queried or alerts be created sending notifications to email addresses, webhook, or LogicApp. It's still fresh and in preview, but is shaping up nicely. For Azure Service Bus specifically, you can already get the metrics for a namespace and entity specific information should be available in a foreseeable future.

Update

I've raised an issue for Azure Service Bus you can track to see when it's available.


问:
Get error from my android login using php
i rececntly learn about android and now i'm trying a simple login with my php. Please check my script first

```<code>public class MainActivity extends Activity {

    final Context context = this;
    private Button button;
    private EditText username;
    private EditText passsword;

    ProgressDialog progress;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void GoLogin(View v){

        username   = (EditText)findViewById(R.id.input_email);
        passsword   = (EditText)findViewById(R.id.input_password);

        String usernameval =  username.getText().toString();
        String passswordval =  md5(passsword.getText().toString());
        new AsyncLogin().execute(usernameval,passswordval);
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }
        protected String doInBackground(String... params) {
            try {

                url = new URL("http://127.0.0.1:84/fppb/Andro_login");

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "exception";
            }
            try {
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("POST");

                conn.setDoInput(true);
                conn.setDoOutput(true);

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", params[0])
                        .appendQueryParameter("password", params[1]);
                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                e1.printStackTrace();
                return "exception";
            }

            try {

                int response_code = conn.getResponseCode();

                if (response_code == HttpURLConnection.HTTP_OK) {

                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return(result.toString());

                }else{

                    return("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }

        }
        protected void onPostExecute(String result) {

            pdLoading.dismiss();
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
            if(result.equalsIgnoreCase("true"))
            {
                Toast.makeText(MainActivity.this, "Login success", Toast.LENGTH_LONG).show();

            }else if (result.equalsIgnoreCase("false")){

                Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

            } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

                Toast.makeText(MainActivity.this, "Cannot connect to main server", Toast.LENGTH_LONG).show();

            }
        }
    }

}
</code>```

this is my androidmanifest.xml

```<code>    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
</code>```

when i try to run my app, i get this error

"Cannot connect to main server"

in my toast message after i submit at my form. How can i fix this ? thanks in advance ? sorry bad english

reference http://androidcss.com/android/android-php-mysql-login-tutorial/

after i read my log(s), i see this

```<code>W/System.err: java.net.SocketTimeoutException: failed to connect to /127.0.0.1 (port 84) from /10.0.2.15 (port 51319) after 10000ms
</code>```

答:
Connect the server and mobile on the same network or host the server in web server.

Use server system's IP Address instead of 127.0.0.1.

Use IP 10.0.2.2 if you are using an Emulator.

Every system itself is a localhost so when you call 127.0.0.1 the system calls itself.

ALSO ADD INTERNET PERMISSIONS

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

Make sure that you had put your Server Online too via Put Online from menu tray

Body:
i rececntly learn about android and now i'm trying a simple login with my php. Please check my script first

public class MainActivity extends Activity {

    final Context context = this;
    private Button button;
    private EditText username;
    private EditText passsword;

    ProgressDialog progress;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void GoLogin(View v){

        username   = (EditText)findViewById(R.id.input_email);
        passsword   = (EditText)findViewById(R.id.input_password);

        String usernameval =  username.getText().toString();
        String passswordval =  md5(passsword.getText().toString());
        new AsyncLogin().execute(usernameval,passswordval);
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }
        protected String doInBackground(String... params) {
            try {

                url = new URL("http://127.0.0.1:84/fppb/Andro_login");

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "exception";
            }
            try {
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("POST");

                conn.setDoInput(true);
                conn.setDoOutput(true);

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", params[0])
                        .appendQueryParameter("password", params[1]);
                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                e1.printStackTrace();
                return "exception";
            }

            try {

                int response_code = conn.getResponseCode();

                if (response_code == HttpURLConnection.HTTP_OK) {

                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return(result.toString());

                }else{

                    return("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }

        }
        protected void onPostExecute(String result) {

            pdLoading.dismiss();
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
            if(result.equalsIgnoreCase("true"))
            {
                Toast.makeText(MainActivity.this, "Login success", Toast.LENGTH_LONG).show();

            }else if (result.equalsIgnoreCase("false")){

                Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

            } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

                Toast.makeText(MainActivity.this, "Cannot connect to main server", Toast.LENGTH_LONG).show();

            }
        }
    }

}

this is my androidmanifest.xml

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

when i try to run my app, i get this error

"Cannot connect to main server"

in my toast message after i submit at my form. How can i fix this ? thanks in advance ? sorry bad english

reference http://androidcss.com/android/android-php-mysql-login-tutorial/

after i read my log(s), i see this

W/System.err: java.net.SocketTimeoutException: failed to connect to /127.0.0.1 (port 84) from /10.0.2.15 (port 51319) after 10000ms

Body:
Connect the server and mobile on the same network or host the server in web server.

Use server system's IP Address instead of 127.0.0.1.

Use IP 10.0.2.2 if you are using an Emulator.

Every system itself is a localhost so when you call 127.0.0.1 the system calls itself.

ALSO ADD INTERNET PERMISSIONS

<uses-permission android:name="android.permission.INTERNET" />

Make sure that you had put your Server Online too via Put Online from menu tray


问:
Return a list of similar authors
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

```<code>authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}
</code>```

And the function I came up with is this:

```<code>def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]
</code>```

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

```<code>get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
</code>```

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

答:
What you're doing now will work the same way without the for loop - you're essentially just doing a single lookup and return that, hence you get only one entry. What you need to do instead is to do your lookup, find the authors and then do a lookup for each of those authors, then rinse and repeat... The easiest way to do that is to use a bit of recursion:

```<code>def get_similar(authors, author):
    return [a for x in authors.pop(author, []) for a in [x] + get_similar(authors, x)]

get_similar(authors, 'Harlan Ellison')

# ['Neil Stephenson', 'Kurt Vonnegut', 'Terry Pratchett', 'Tom Robbins', 'Douglas Adams',
#  'Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut', 'Neil Stephenson', 'Jeff Vandemeer',
#  'Richard Morgan', 'Douglas Adams']
</code>```

Then all you need to do is to turn it into a set to get rid of the duplicates and then sort it, or if you don't mind a slight performance hit (due to recursion) you can do it right inside your function:

```<code>def get_similar(authors, author):
    return sorted(set([a for x in authors.pop(author, []) for a in [x] + get_similar(authors, x)]))

# ['Chris Moore', 'Douglas Adams', 'Jeff Vandemeer', 'Kurt Vonnegut', 'Neil Stephenson', 'Richard Morgan', 'Terry Pratchett', 'Tom Robbins']
</code>```

Keep in mind that this modifies your input dictionary to avoid infinite recursion, so if you want to keep your authors dictionary intact call the function as get_similar(authors.copy(), author).

Title: Return a list of similar authors

Body:
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}

And the function I came up with is this:

def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

Body:
What you're doing now will work the same way without the for loop - you're essentially just doing a single lookup and return that, hence you get only one entry. What you need to do instead is to do your lookup, find the authors and then do a lookup for each of those authors, then rinse and repeat... The easiest way to do that is to use a bit of recursion:

def get_similar(authors, author):
    return [a for x in authors.pop(author, []) for a in [x] + get_similar(authors, x)]

get_similar(authors, 'Harlan Ellison')

# ['Neil Stephenson', 'Kurt Vonnegut', 'Terry Pratchett', 'Tom Robbins', 'Douglas Adams',
#  'Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut', 'Neil Stephenson', 'Jeff Vandemeer',
#  'Richard Morgan', 'Douglas Adams']

Then all you need to do is to turn it into a set to get rid of the duplicates and then sort it, or if you don't mind a slight performance hit (due to recursion) you can do it right inside your function:

def get_similar(authors, author):
    return sorted(set([a for x in authors.pop(author, []) for a in [x] + get_similar(authors, x)]))

# ['Chris Moore', 'Douglas Adams', 'Jeff Vandemeer', 'Kurt Vonnegut', 'Neil Stephenson', 'Richard Morgan', 'Terry Pratchett', 'Tom Robbins']

Keep in mind that this modifies your input dictionary to avoid infinite recursion, so if you want to keep your authors dictionary intact call the function as get_similar(authors.copy(), author).


问:
how to eleminate an option from a list and have an error message appear to prompt the user again
```<code>import java.util.*;
public class Yahtzee {
String choices[] = {"1 to roll a single dice","2 for a yahtzee score","3
for a straight score","4 for a chance score"};
Dice dice3;
Dice dice2;
Dice dice1;
int CanYahtzee;
boolean canYahtzee;
boolean canStraight;
boolean canChance;
int numberOfRolls;
int total;
int turnCount;
int finalScore;
}

public void displayOptions() {
    if (numberOfRolls < 3){
        System.out.println(choices[0]);
    }
    if (canYahtzee){
        System.out.println(choices[1]);
    }
    if(canStraight){
        System.out.println(choices[2]);
    }
    if(canChance){
        System.out.println(choices[3]);
    }
}
public int promptUser(){
    boolean check = true;
    int choice = 0;
    while(check){
        System.out.println("Enter a choice");
        Scanner input = new Scanner(System.in);
        choice = input.nextInt();

        if (choice == 2 ){
            noMoreYahtzee();
        }else if(choice ==3){
            noMoreStraight();
        }else if(choice == 4){
            noMoreChance();
        }
        if( (numberOfRolls < 3 && choice == 1) || (canYahtzee && choice ==2) || (canStraight && choice == 3) || (canChance && choice == 4)){
            check = false;
            return choice;
        }
    }
    return choice;
}
public void noMoreYahtzee(){
    canYahtzee = false;
}
public void noMoreStraight(){
    canStraight = false;
}
public void noMoreChance() {
        canChance = false;
}
</code>```

Sample of what it prints.

```<code>dice are: 2 2 4
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
1
What die would you like to roll1
dice are: 4 2 4
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
4
your current total is: 10
dice are: 5 5 5
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
2
your current total is: 50
dice are: 4 4 1
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
</code>```

what it should do: if the player enters 2 3 or 4, the option to choose it should go away the second round and an error message should occur if the user trys to use an opted out choice. same example but the correct way.

```<code>dice are: 2 2 4
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
1
What die would you like to roll1
dice are: 4 2 4
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
4
your current total is: 10
dice are: 5 5 5
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
Enter a choice
2
your current total is: 50
dice are: 4 4 1
1 to roll a single dice
3 for a straight score
Enter a choice
4
Error invalid option try again
3
</code>```

ive tried using a couple different approaches to this issue but this is my current one that complies if anyone has an idea for my solution that can help i will be very greatfull.

答:
Here's what I would do:

In your promptUser() method, after the line

```<code>int choice = input.nextInt();
</code>```

I would check what choice is, whether it is 2, 3, or 4.
From here, if it is 2, call noMoreYahtzee()
or if it is 3, callnoMoreStraight() or if it is 4, call noMoreChance()

Then, because you already wrote code in your displayChoices() method to check the value of the booleans, your code should work. Hope this helps.

Also, your while(true) loop is going to cause an infinite loop.
To fix this, I would add some things into your promptUser() method.

```<code>public int promptUser(){
    boolean check = true;
    int choice;
    while(check){
        System.out.println("Enter a choice");
        Scanner input = new Scanner(System.in);
        choice = input.nextInt();
        if( (numberOfRolls < 3 && choice == 1) || (canYahtzee && choice ==2) || (canStraight && choice == 3) || (canChance && choice == 4)){
            check = false;
        }
    }
    return choice;
}
</code>```

Body:
import java.util.*;
public class Yahtzee {
String choices[] = {"1 to roll a single dice","2 for a yahtzee score","3
for a straight score","4 for a chance score"};
Dice dice3;
Dice dice2;
Dice dice1;
int CanYahtzee;
boolean canYahtzee;
boolean canStraight;
boolean canChance;
int numberOfRolls;
int total;
int turnCount;
int finalScore;
}

public void displayOptions() {
    if (numberOfRolls < 3){
        System.out.println(choices[0]);
    }
    if (canYahtzee){
        System.out.println(choices[1]);
    }
    if(canStraight){
        System.out.println(choices[2]);
    }
    if(canChance){
        System.out.println(choices[3]);
    }
}
public int promptUser(){
    boolean check = true;
    int choice = 0;
    while(check){
        System.out.println("Enter a choice");
        Scanner input = new Scanner(System.in);
        choice = input.nextInt();

        if (choice == 2 ){
            noMoreYahtzee();
        }else if(choice ==3){
            noMoreStraight();
        }else if(choice == 4){
            noMoreChance();
        }
        if( (numberOfRolls < 3 && choice == 1) || (canYahtzee && choice ==2) || (canStraight && choice == 3) || (canChance && choice == 4)){
            check = false;
            return choice;
        }
    }
    return choice;
}
public void noMoreYahtzee(){
    canYahtzee = false;
}
public void noMoreStraight(){
    canStraight = false;
}
public void noMoreChance() {
        canChance = false;
}

Sample of what it prints.

dice are: 2 2 4
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
1
What die would you like to roll1
dice are: 4 2 4
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
4
your current total is: 10
dice are: 5 5 5
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
2
your current total is: 50
dice are: 4 4 1
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice

what it should do: if the player enters 2 3 or 4, the option to choose it should go away the second round and an error message should occur if the user trys to use an opted out choice. same example but the correct way.

dice are: 2 2 4
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
1
What die would you like to roll1
dice are: 4 2 4
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
4 for a chance score
Enter a choice
4
your current total is: 10
dice are: 5 5 5
1 to roll a single dice
2 for a yahtzee score
3 for a straight score
Enter a choice
2
your current total is: 50
dice are: 4 4 1
1 to roll a single dice
3 for a straight score
Enter a choice
4
Error invalid option try again
3

ive tried using a couple different approaches to this issue but this is my current one that complies if anyone has an idea for my solution that can help i will be very greatfull.

Body:
Here's what I would do:

In your promptUser() method, after the line

int choice = input.nextInt();

I would check what choice is, whether it is 2, 3, or 4.
From here, if it is 2, call noMoreYahtzee()
or if it is 3, callnoMoreStraight() or if it is 4, call noMoreChance()

Then, because you already wrote code in your displayChoices() method to check the value of the booleans, your code should work. Hope this helps.

Also, your while(true) loop is going to cause an infinite loop.
To fix this, I would add some things into your promptUser() method.

public int promptUser(){
    boolean check = true;
    int choice;
    while(check){
        System.out.println("Enter a choice");
        Scanner input = new Scanner(System.in);
        choice = input.nextInt();
        if( (numberOfRolls < 3 && choice == 1) || (canYahtzee && choice ==2) || (canStraight && choice == 3) || (canChance && choice == 4)){
            check = false;
        }
    }
    return choice;
}