问:
Viewcontroller crashes after being presented by another viewcontroller
For some reason, viewDidLoad() crashes with

```<code>fatal error: unexpectedly found nil while unwrapping an Optional value
</code>```

in authViewController in my app while setting up the UI after it's being presented from another viewcontroller:

```<code>//authViewController
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        authState.addTarget(self, action: #selector(authStateChanged), for: .valueChanged)//<-- The place where it crashes

        emailInput.addTarget(self, action: #selector(emailPasswordTextChanged), for: .editingChanged)
        passwordInput.addTarget(self, action: #selector(emailPasswordTextChanged), for: .editingChanged)
        SignIn.addTarget(self, action: #selector(signInPressed), for: .touchUpInside)
        //Set actions

        infoView.layer.cornerRadius = 5
        SignIn.layer.cornerRadius = 5
        //UI setup
}
</code>```

The Other View Controller:

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        FIRAuth.auth()?.addStateDidChangeListener({ (auth, user) in
            if user != nil {

            }
            else {
                print("pop")
                DispatchQueue.main.async {
                    self.present(authViewController(), animated: true, completion: nil)
                }
            }
        })
    }
</code>```

Can anybody please tell me what and why it happened if you know?

答:
Instead of presenting the ViewController like

```<code>self.present(authViewController(), animated: true, completion: nil)
</code>```

Try presenting ViewController after instantiating it

```<code>let storyBoard = UIStoryboard(name: storyboardname, bundle: nil)
let authVC = storyBoard.instantiateViewController(withIdentifier: viewController Identifier) as? authViewController
self.present(authVC, animated: true, completion: nil)
</code>```

Body:
For some reason, viewDidLoad() crashes with

fatal error: unexpectedly found nil while unwrapping an Optional value

in authViewController in my app while setting up the UI after it's being presented from another viewcontroller:

//authViewController
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        authState.addTarget(self, action: #selector(authStateChanged), for: .valueChanged)//<-- The place where it crashes

        emailInput.addTarget(self, action: #selector(emailPasswordTextChanged), for: .editingChanged)
        passwordInput.addTarget(self, action: #selector(emailPasswordTextChanged), for: .editingChanged)
        SignIn.addTarget(self, action: #selector(signInPressed), for: .touchUpInside)
        //Set actions

        infoView.layer.cornerRadius = 5
        SignIn.layer.cornerRadius = 5
        //UI setup
}

The Other View Controller:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        FIRAuth.auth()?.addStateDidChangeListener({ (auth, user) in
            if user != nil {

            }
            else {
                print("pop")
                DispatchQueue.main.async {
                    self.present(authViewController(), animated: true, completion: nil)
                }
            }
        })
    }

Can anybody please tell me what and why it happened if you know?

Body:
Instead of presenting the ViewController like

self.present(authViewController(), animated: true, completion: nil)

Try presenting ViewController after instantiating it

let storyBoard = UIStoryboard(name: storyboardname, bundle: nil)
let authVC = storyBoard.instantiateViewController(withIdentifier: viewController Identifier) as? authViewController
self.present(authVC, animated: true, completion: nil)


来源: stackexchange

问:
Compare two integers doesn't work correctly in Android
I have a method that have to compare an integer with an Arraylist and if the number on the integer is on the arraylist, I recieve a false. If the integer number is not on the arraylist I recieve a true.

I need this, because I'm making a quiz game that have some questions on a BBDD and I can't show the same question twice. Also this questions are in three categories: E, I and A. I have to show five E questions, then five I questions and then five A questions.

So I have to show questions without repeat them, and also 5 of each category. I make this methods but I don't know why it repeats some questions.

The only thing works correctly is the category questions. I have always 5 E questions, then 5 I questions and at least 5 A questions.

The method that told me if the questions is on the ArrayList:

```<code>private boolean checkRandom()
{
    for(int i = 0; i < listRandom.size(); i++)
    {
        if(questionPosition == listRandom.get(i))
        {
            return false;
        }
    }

    return true;
}
</code>```

I also try with "equals", but I have the same result.

The method that check if the question is in the correct category and is not showed before:

```<code>private void loadPhase() {

    if (numQuestion < 15)
    {
        r = new Random();
        questionPosition = r.nextInt(listQuestions.size());

        if(numQuestion < 5)
        {
            while(!listPhase.get(questionPosition).equals("E") && (!listPhase.get(questionPosition).equals("E")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 4 && numQuestion < 10)
        {
            while(!listPhase.get(questionPosition).equals("I") && (!listPhase.get(questionPosition).equals("I")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 9)
        {
            while(!listPhase.get(questionPosition).equals("A") && (!listPhase.get(questionPosition).equals("A")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }

        listRandom.add(questionPosition);

        header4questions.setText(listQuestions.get(questionPosition));

        answer1.setText(listAnswers.get(questionPosition * 4));
        answer2.setText(listAnswers.get((questionPosition * 4) + 1));
        answer3.setText(listAnswers.get((questionPosition * 4) + 2));
        answer4.setText(listAnswers.get((questionPosition * 4) + 3));

        numQuestion++;
    }
    else {
        Toast.makeText(getApplicationContext(), "You have finished the quiz!", Toast.LENGTH_SHORT).show();

        uploadPoints();
    }
}
</code>```

So, what I have is all the questions on the correct category, but it repeat the questions and I don't know why.

Can anyone help me?

Thanks!

答:
Although converting the ArrayList to a HashSet effectively removes duplicates, if you need to preserve insertion order, I'd rather suggest you use this variant

list is some List of Strings
Set < String > s = new LinkedHashSet < > (list);```

Then, if you need to get back a List reference, you can use again the conversion constructor.

Answer reference: https://stackoverflow.com/a/204004/8252521

Answered by user: https://stackoverflow.com/users/27565/abahgat

ContentLicense: CC BY-SA 3.0

Body:
I have a method that have to compare an integer with an Arraylist and if the number on the integer is on the arraylist, I recieve a false. If the integer number is not on the arraylist I recieve a true.

I need this, because I'm making a quiz game that have some questions on a BBDD and I can't show the same question twice. Also this questions are in three categories: E, I and A. I have to show five E questions, then five I questions and then five A questions.

So I have to show questions without repeat them, and also 5 of each category. I make this methods but I don't know why it repeats some questions.

The only thing works correctly is the category questions. I have always 5 E questions, then 5 I questions and at least 5 A questions.

The method that told me if the questions is on the ArrayList:

private boolean checkRandom()
{
    for(int i = 0; i < listRandom.size(); i++)
    {
        if(questionPosition == listRandom.get(i))
        {
            return false;
        }
    }

    return true;
}

I also try with "equals", but I have the same result.

The method that check if the question is in the correct category and is not showed before:

private void loadPhase() {

    if (numQuestion < 15)
    {
        r = new Random();
        questionPosition = r.nextInt(listQuestions.size());

        if(numQuestion < 5)
        {
            while(!listPhase.get(questionPosition).equals("E") && (!listPhase.get(questionPosition).equals("E")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 4 && numQuestion < 10)
        {
            while(!listPhase.get(questionPosition).equals("I") && (!listPhase.get(questionPosition).equals("I")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 9)
        {
            while(!listPhase.get(questionPosition).equals("A") && (!listPhase.get(questionPosition).equals("A")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }

        listRandom.add(questionPosition);

        header4questions.setText(listQuestions.get(questionPosition));

        answer1.setText(listAnswers.get(questionPosition * 4));
        answer2.setText(listAnswers.get((questionPosition * 4) + 1));
        answer3.setText(listAnswers.get((questionPosition * 4) + 2));
        answer4.setText(listAnswers.get((questionPosition * 4) + 3));

        numQuestion++;
    }
    else {
        Toast.makeText(getApplicationContext(), "You have finished the quiz!", Toast.LENGTH_SHORT).show();

        uploadPoints();
    }
}

So, what I have is all the questions on the correct category, but it repeat the questions and I don't know why.

Can anyone help me?

Thanks!

Body:
Although converting the ArrayList to a HashSet effectively removes duplicates, if you need to preserve insertion order, I'd rather suggest you use this variant

list is some List of Strings
Set < String > s = new LinkedHashSet < > (list);

Then, if you need to get back a List reference, you can use again the conversion constructor.

Answer reference: https://stackoverflow.com/a/204004/8252521

Answered by user: https://stackoverflow.com/users/27565/abahgat


答:
I solved it by doing:</p>

```<code>let authVC = self.storyboard?.instantiateViewController(withIdentifier: "authVC")
self.present(authVC!, animated: true, completion: nil)
</code>```

Title: Viewcontroller crashes after being presented by another viewcontroller

Body:
I solved it by doing:

let authVC = self.storyboard?.instantiateViewController(withIdentifier: "authVC")
self.present(authVC!, animated: true, completion: nil)


问:
Spring boot test "No qualifying bean of type available"
I'm quite a newbie to Spring boot, but here's the problem I'm facing now:

```<code>// Application.java
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Autowired
  private Cluster cluster = null;

  @PostConstruct
  private void migrateCassandra() {
    Database database = new Database(this.cluster, "foo");
    MigrationTask migration = new MigrationTask(database, new MigrationRepository());
    migration.migrate();
  }
}
</code>```

So basically, I'm trying to bootstrap a spring application, and after that, do some cassandra migrations.

I also have defined a repository for my user model:

```<code>// UserRepo.java
public interface UserRepo extends CassandraRepository<User> {
}
</code>```

Now I'm trying to test my repo class using the following simple test case:

```<code>// UserRepoTest.java
@RunWith(SpringRunner.class)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@DataJpaTest
public class UserRepoTest {

  @Autowired
  private UserRepo userRepo = null;

  @Autowired
  private TestEntityManager entityManager = null;

  @Test
  public void findOne_whenUserExists_thenReturnUser() {
    String id = UUID.randomUUID().toString();
    User user = new User();
    user.setId(id);
    this.entityManager.persist(user);

    assertEquals(this.userRepo.findOne(user.getId()).getId(), id);
  }

  @Test
  public void findOne_whenUserNotExists_thenReturnNull() {
    assertNull(this.userRepo.findOne(UUID.randomUUID().toString()));
  }
}
</code>```

I would expect the test to pass, but instead, I got an error saying "No qualifying bean of type 'com.datastax.driver.core.Cluster' available". It looks like spring failed to autowire the cluster object, but why is that? How do I fix this? Thanks a lot!

答:
The test environment needs to know where your beans are defined, so you have to tell it the location.

In your test class, add the @ContextConfiguration annotation:

@RunWith(SpringRunner.class)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@DataJpaTest
@ContextConfiguration(classes = {YourBeans.class, MoreOfYourBeans.class})
public class UserRepoTest {

  @Autowired
  private UserRepo userRepo = null;

  @Autowired
  private TestEntityManager entityManager = null;
```

Body:
I'm quite a newbie to Spring boot, but here's the problem I'm facing now:

// Application.java
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Autowired
  private Cluster cluster = null;

  @PostConstruct
  private void migrateCassandra() {
    Database database = new Database(this.cluster, "foo");
    MigrationTask migration = new MigrationTask(database, new MigrationRepository());
    migration.migrate();
  }
}

So basically, I'm trying to bootstrap a spring application, and after that, do some cassandra migrations.

I also have defined a repository for my user model:

// UserRepo.java
public interface UserRepo extends CassandraRepository<User> {
}

Now I'm trying to test my repo class using the following simple test case:

// UserRepoTest.java
@RunWith(SpringRunner.class)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@DataJpaTest
public class UserRepoTest {

  @Autowired
  private UserRepo userRepo = null;

  @Autowired
  private TestEntityManager entityManager = null;

  @Test
  public void findOne_whenUserExists_thenReturnUser() {
    String id = UUID.randomUUID().toString();
    User user = new User();
    user.setId(id);
    this.entityManager.persist(user);

    assertEquals(this.userRepo.findOne(user.getId()).getId(), id);
  }

  @Test
  public void findOne_whenUserNotExists_thenReturnNull() {
    assertNull(this.userRepo.findOne(UUID.randomUUID().toString()));
  }
}

I would expect the test to pass, but instead, I got an error saying "No qualifying bean of type 'com.datastax.driver.core.Cluster' available". It looks like spring failed to autowire the cluster object, but why is that? How do I fix this? Thanks a lot!


问:
Appending to PATH in a Windows Docker container
I need to append to the PATH within a Windows Docker container, and I've tried many permutations.

```<code>ENV PATH=%PATH%;C:\\Foo\\bin
ENV PATH=$PATH;C:\\Foo\\bin
ENV PATH="%PATH%;C:\Foo\bin"
ENV PATH="$PATH;C:\Foo\bin"
RUN "set PATH=%PATH%;C:\Foo\bin"
</code>```

None of these work: they don't evaluate the preexisting PATH variable.

What is the right syntax to append to the PATH? Can I even append to the PATH inside Docker? (I can on similar Linux containers)

答:
You can set environment variables permanently in the container using a powershell script.

Create a powershell script in yout docker context (e.g. setpath.ps1 ) containing this:

```<code>[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\Foo\bin", [EnvironmentVariableTarget]::Machine)
</code>```

Add this script to your container dockerfile and RUN the script. Add something like this to your dockerfile:

```<code>ADD ./setpath.ps1 c:/MyScripts/setpath.ps1
RUN powershell -Command c:\MyScripts\setpath.ps1
</code>```

Body:
I need to append to the PATH within a Windows Docker container, and I've tried many permutations.

ENV PATH=%PATH%;C:\\Foo\\bin
ENV PATH=$PATH;C:\\Foo\\bin
ENV PATH="%PATH%;C:\Foo\bin"
ENV PATH="$PATH;C:\Foo\bin"
RUN "set PATH=%PATH%;C:\Foo\bin"

None of these work: they don't evaluate the preexisting PATH variable.

What is the right syntax to append to the PATH? Can I even append to the PATH inside Docker? (I can on similar Linux containers)

Body:
You can set environment variables permanently in the container using a powershell script.

Create a powershell script in yout docker context (e.g. setpath.ps1 ) containing this:

[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\Foo\bin", [EnvironmentVariableTarget]::Machine)

Add this script to your container dockerfile and RUN the script. Add something like this to your dockerfile:

ADD ./setpath.ps1 c:/MyScripts/setpath.ps1
RUN powershell -Command c:\MyScripts\setpath.ps1


问:
EF classes vs L2S classes
According to this article:

http://dotnetanonymous.blogspot.com/2010/03/entity-framework.html

There are some L2S classes that have the name "Entity" in them, but actually do not belong to EF.  Which classes are these?

ContentLicense: CC BY-SA 2.5

Title: EF classes vs L2S classes

Body: System.Data.Linq.EntityRef and System.Data.Linq.EntitySet.


问:
Create a sheet that isn't a warning message
I have an app that reads data from a smartcard. Since doing so can take a while, I'm using a modal sheet to prevent interaction with the app while data is being read:

```<code>[_spinner startAnimation:self];
[NSApp beginSheet:_CardReadSheet modalForWindow:_window modalDelegate:self didEndSelector:@selector(endSheet:returnCode:contextInfo:) contextInfo:nil];
</code>```

Where _CardReadSheet shows _spinner and a localized text to the effect of "Reading data, please wait", _window is my main window, and endSheet:returnCode:contextInfo just tells the sheet to close.

The problem is that using a modal sheet is apparently meant only as an error or warning message, so showing it to the user in this way results in the default warning sound being produced. This is not the intent.

How can I make it not produce a sound? If I'm using the wrong way to show the sheet, or if using a sheet is not the right thing to do, what should I do instead?

答:
The warning sound is because you're asking NSApp to provide the sheet: it does so as an alert. I can't find an official source explaining why but this is what is happening.

To get a similar sheet but without any alert sound, call beginSheet on NSWindow instead of NSApp.

Quick example in Swift:

```<code>myExistingWindow.beginSheet(myNewSheet, completionHandler: nil)
</code>```

And to close it:

```<code>myExistingWindow.endSheet(myNewSheet)
</code>```

Body:
I have an app that reads data from a smartcard. Since doing so can take a while, I'm using a modal sheet to prevent interaction with the app while data is being read:

[_spinner startAnimation:self];
[NSApp beginSheet:_CardReadSheet modalForWindow:_window modalDelegate:self didEndSelector:@selector(endSheet:returnCode:contextInfo:) contextInfo:nil];

Where _CardReadSheet shows _spinner and a localized text to the effect of "Reading data, please wait", _window is my main window, and endSheet:returnCode:contextInfo just tells the sheet to close.

The problem is that using a modal sheet is apparently meant only as an error or warning message, so showing it to the user in this way results in the default warning sound being produced. This is not the intent.

How can I make it not produce a sound? If I'm using the wrong way to show the sheet, or if using a sheet is not the right thing to do, what should I do instead?

Body:
The warning sound is because you're asking NSApp to provide the sheet: it does so as an alert. I can't find an official source explaining why but this is what is happening.

To get a similar sheet but without any alert sound, call beginSheet on NSWindow instead of NSApp.

Quick example in Swift:

myExistingWindow.beginSheet(myNewSheet, completionHandler: nil)

And to close it:

myExistingWindow.endSheet(myNewSheet)


问:
How to pass data to controller using Fetch api in asp.net core
I post data using fetch like this in my client js scripts

```<code>    fetch('/myarea/mycontroller/myaction', {
        method: 'post',
        body: JSON.stringify({ name: namevalue, address: addressvalue })
    })
        .then(function (response) {
            if (response.status !== 200) {
                console.log('fetch returned not ok' + response.status);
            }

            response.json().then(function (data) {
                console.log('fetch returned ok');
                console.log(data);
            });
        })
        .catch(function (err) {
            console.log(`error: ${err}`);
        });
    }, false);
</code>```

Then on my controller

```<code>    [HttpPost]
    public async Task<IActionResult> MyAction(string name, string address)
    {
        // Error, name and address is null here, shouldn't be!
        // more code here ...
    }
</code>```

My controller action is being called correctly, and I am able to debug inside it, but no data being passed. What could be wrong here? Thanks

答:
The controller action is expecting query parameters (/myaction?name=myname&address=myaddress). That's the default.
You're sending them in the body.

You can change the javascript to send them as query parameters. (see here: https://github.com/github/fetch/issues/256)

Or you can tell the controller action to take the values from the body:

```<code>[HttpPost]
public async Task<IActionResult> MyAction([FromBody] Person person)
{
    var myName = person.Name;
}

public class Person
{
    public string Name {get; set; }

    public string Address {get; set; }
}
</code>```

Body:
I post data using fetch like this in my client js scripts

    fetch('/myarea/mycontroller/myaction', {
        method: 'post',
        body: JSON.stringify({ name: namevalue, address: addressvalue })
    })
        .then(function (response) {
            if (response.status !== 200) {
                console.log('fetch returned not ok' + response.status);
            }

            response.json().then(function (data) {
                console.log('fetch returned ok');
                console.log(data);
            });
        })
        .catch(function (err) {
            console.log(`error: ${err}`);
        });
    }, false);

Then on my controller

    [HttpPost]
    public async Task<IActionResult> MyAction(string name, string address)
    {
        // Error, name and address is null here, shouldn't be!
        // more code here ...
    }

My controller action is being called correctly, and I am able to debug inside it, but no data being passed. What could be wrong here? Thanks

Body:
The controller action is expecting query parameters (/myaction?name=myname&address=myaddress). That's the default.
You're sending them in the body.

You can change the javascript to send them as query parameters. (see here: https://github.com/github/fetch/issues/256)

Or you can tell the controller action to take the values from the body:

[HttpPost]
public async Task<IActionResult> MyAction([FromBody] Person person)
{
    var myName = person.Name;
}

public class Person
{
    public string Name {get; set; }

    public string Address {get; set; }
}


问:
Swift Package Manager - Custom Framework
I am new to the Swift Package Manager so bear with me. I have searched around and haven't found an answer to my current problem. I am creating a custom framework. When I create a CocoaTouch Framework and then build it, I am able to find the ProjectName.framework in my "Products" folder in the project directory. However, when I use SPM to add a dependency (Alamofire for example) and generate a new project file with the

swift package generate-xcodeproj

terminal command, the Alamofire.framework shows up in "Products" but the ProjectName.framework is no longer available. Instead there is a ProjectName executable file. I am no longer able to find the framework or even include the whole project in another as a dependency.

In the image above, I expect to see KonvurjKit.framework in "Products" but I no longer see it. Any help would be greatly appreciated.

答:
Since your project contains main.swift, Swift Package Manager produces an executable. You should add your framework files, other than main.swift and then run swift package generate-xcodeproj. A framework will be generated in Products in the generated Xcode project.

If you want to create both an executable and a library (framework), a possible Source layout is this:

Sources
   - KonvurjKitExecutable
     main.swift
   - KonvurjKit
     <your framework files here>

Add two targets to your Package.swift:

targets: [
     Target(name: "KonvurjKitExecutable",
            dependencies: [.Target(name: "KonvurjKit")]),
     Target(name: "KonvurjKit")]

If you want to create a library (framework) only, just remove main.swift and add your framework files directly to Sources.


问:
How to get Plotly.js default colors list?
I am plotting a plotly bubble chart on a webpage.. I want to get the list of default colors, plotly uses to draw the bubbles.</p>

答:
You can also use something like this to retrieve the colours used in your plot:</p>

```<code>return.plot_ly.ColorsUsed <- function( plotlyObject ) {

      explorePlot = plotly_json(plotlyObject)
      explorePlot = jsonlite::fromJSON(explorePlot$x$data)

      # Extract colors, names and fillcolors
      colors = explorePlot$data$marker$color
      names = explorePlot$data$name
      fillcolors = explorePlot$data$marker$fillcolor

      # Returns a list with the names, colors and fillcolors used in the plot
      toReturn = list( "names" = names,
                       "colors" = colors,
                       "fillcolors" = fillcolors )

      return(toReturn)

} # End FUnction return.plot_ly.ColorsUsed
</code>```

Body:
You can also use something like this to retrieve the colours used in your plot:

return.plot_ly.ColorsUsed <- function( plotlyObject ) {

      explorePlot = plotly_json(plotlyObject)
      explorePlot = jsonlite::fromJSON(explorePlot$x$data)

      # Extract colors, names and fillcolors
      colors = explorePlot$data$marker$color
      names = explorePlot$data$name
      fillcolors = explorePlot$data$marker$fillcolor

      # Returns a list with the names, colors and fillcolors used in the plot
      toReturn = list( "names" = names,
                       "colors" = colors,
                       "fillcolors" = fillcolors )

      return(toReturn)

} # End FUnction return.plot_ly.ColorsUsed


问:
Why Regex is not Working? for [^#]
I need a regex that matches the below link patterns as follows.

'https://website/1/extension1' -> True

'https://website/1.1/extension1' -> False

'https://website/1/#extension1' -> False

My regex is

```<code>regex = re.compile('https://website/1[^\.]/*[^#]')
</code>```

It works find for the case two. But I wonder why this doesn't return False in case of occurrence of # in link.

答:
Your regex matches the https://website/1/ prefix, and nothing more. It doesn't matter that the string contains more text beyond that / after the version number.

You need to include anchors, to make sure you are not just matching a substring. Use ^ and $ to anchor to the start and end of a string, so there is no room left for other strings. You need to match paths that don't include any # characters:

```<code>^https://docs\.python\.org/\d/[^#]*$
</code>```

I also escaped the dots in the hostname, you don't want to match 'any' character, you want to match literal '.' characters. \d matches one digit (so 2 and 3 for major Python versions, but no more).

Online demo: https://regex101.com/r/gL7X7o/3

Python demo using Python documentation URLs:

```<code>>>> import re
>>> pattern = re.compile(r'^https://docs\.python\.org/3/[^#]*$')
>>> links = [
...     'https://docs.python.org/3/library/re.html#regular-expression-syntax',
...     'https://docs.python.org/3/library/re.html',
...     'https://docs.python.org/3.6/library/re.html',
...     'https://docs.python.org/2/library/re.html',
... ]
>>> for link in links:
...     print('{!r} -> {}'.format(link, bool(pattern.search(link)))
...
'https://docs.python.org/3/library/re.html#regular-expression-syntax' -> False
'https://docs.python.org/3/library/re.html' -> True
'https://docs.python.org/3.6/library/re.html' -> False
'https://docs.python.org/2/library/re.html' -> True
</code>```

Title: Why Regex is not Working? for [^#]

Body:
I need a regex that matches the below link patterns as follows.

'https://website/1/extension1' -> True

'https://website/1.1/extension1' -> False

'https://website/1/#extension1' -> False

My regex is

regex = re.compile('https://website/1[^\.]/*[^#]')

It works find for the case two. But I wonder why this doesn't return False in case of occurrence of # in link.

Body:
Your regex matches the https://website/1/ prefix, and nothing more. It doesn't matter that the string contains more text beyond that / after the version number.

You need to include anchors, to make sure you are not just matching a substring. Use ^ and $ to anchor to the start and end of a string, so there is no room left for other strings. You need to match paths that don't include any # characters:

^https://docs\.python\.org/\d/[^#]*$

I also escaped the dots in the hostname, you don't want to match 'any' character, you want to match literal '.' characters. \d matches one digit (so 2 and 3 for major Python versions, but no more).

Online demo: https://regex101.com/r/gL7X7o/3

Python demo using Python documentation URLs:

>>> import re
>>> pattern = re.compile(r'^https://docs\.python\.org/3/[^#]*$')
>>> links = [
...     'https://docs.python.org/3/library/re.html#regular-expression-syntax',
...     'https://docs.python.org/3/library/re.html',
...     'https://docs.python.org/3.6/library/re.html',
...     'https://docs.python.org/2/library/re.html',
... ]
>>> for link in links:
...     print('{!r} -> {}'.format(link, bool(pattern.search(link)))
...
'https://docs.python.org/3/library/re.html#regular-expression-syntax' -> False
'https://docs.python.org/3/library/re.html' -> True
'https://docs.python.org/3.6/library/re.html' -> False
'https://docs.python.org/2/library/re.html' -> True


问:
How can I instantiate singleton class implemented in Bill Pugh method?
Hi Can please someone tell me the correct way how I can instantiate the below given singleton class?</p>

```<code>    public class BillPughSingleton {

    private BillPughSingleton(){}

    private static class SingletonHelper{
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance(){
        return SingletonHelper.INSTANCE;
    }
}
</code>```

答:
you can rewrite your class simply like this and no more need to SingletonHelper class

```<code>public class BillPughSingleton {

private static BillPughSingleton INSTANCE;
private BillPughSingleton(){}

public static BillPughSingleton getInstance(){
    if (INSTANCE==null) {
        INSTANCE = new BillPughSingleton();
    }
    return INSTANCE;
}
</code>```

}

for instansiate you can try this:

```<code>BillPughSingleton instance = BillPughSingleton.getInstance();
</code>```

you can find more another example here

Body:
Hi Can please someone tell me the correct way how I can instantiate the below given singleton class?

    public class BillPughSingleton {

    private BillPughSingleton(){}

    private static class SingletonHelper{
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance(){
        return SingletonHelper.INSTANCE;
    }
}

Body:
you can rewrite your class simply like this and no more need to SingletonHelper class

public class BillPughSingleton {

private static BillPughSingleton INSTANCE;
private BillPughSingleton(){}

public static BillPughSingleton getInstance(){
    if (INSTANCE==null) {
        INSTANCE = new BillPughSingleton();
    }
    return INSTANCE;
}

}

for instansiate you can try this:

BillPughSingleton instance = BillPughSingleton.getInstance();

you can find more another example here


问:
Suming different fields when active - Odoo v8
Let's say I have these fields:

```<code>#Lamination packeting
@api.onchange('cost_rs18', 'qty__m_18')
def total18(self):
    if self.cost_rs18 or self.qty__m_18:
        self.total_18 = self.cost_rs18 * self.qty__m_18

cost_rs18 = fields.Float("Cost Rs.")
qty__m_18 = fields.Integer("Qty")
total_18 = fields.Float(string="Total")
#Packing
@api.onchange('cost_rs19', 'qty__m_19')
def total19(self):
    if self.cost_rs19 or self.qty__m_19:
        self.total_19 = self.cost_rs19 * self.qty__m_19

cost_rs19 = fields.Float("Cost Rs.")
qty__m_19 = fields.Integer("Qty")
total_19 = fields.Float(string="Total")
#Others
@api.onchange('cost_rs20', 'qty__m_20')
def total20(self):
    if self.cost_rs20 or self.qty__m_20:
        self.total_20 = self.cost_rs20 * self.qty__m_20

cost_rs20 = fields.Float("Cost Rs.")
qty__m_20 = fields.Integer("Qty")
total_20 = fields.Float(string="Total")
</code>```

These obviously sum up on their respective total_n fields.

But on the other hand, not always they should be sumed, let me explain myself.

All these 3 fields (they are actually 20 in my code), have their respective total_n fields which sum up every couple of cost_rs_n and qty__m_n ones.

Now I want to create a "total of totals" which should sum up all the 20 fields, this isn't difficult to figure out, but, my point is, that not always you will be suming all 20, sometimes are 12 active totals, sometimes 2, or sometimes all 20 of them.

How can I achieve this? Can I use the same logic I use on my @api.onchange but for all of them? knowing that not always they all will have data to sum?

EDIT

This is the function I'm actually using, it sums all the totals from all the actual fields I have on my model:

```<code>@api.onchange('total_1', 'total_2',
    'total_3', 'total_4', 'total_5', 'total_6',
    'total_7', 'total_8', 'total_9', 'total_10',
    'total_11', 'total_12', 'total_13', 'total_14',
    'total_15', 'total_16', 'total_17', 'total_18',
    'total_19', 'total_20')
def total21(self):
    if self.total_1 or self.total_2 or self.total_3 or self.total_4 or self.total_5 or self.total_6 or self.total_7 or self.total_8 or self.total_9 or self.total_10 \
    or self.total_11 or self.total_12 or self.total_13 or self.total_14 or self.total_15 or self.total_16 or self.total_17 or self.total_18 or self.total_19 or self.total_20:
        self.total_totals = self.total_1 * self.total_2 * self.total_3 * self.total_4 * self.total_5 * self.total_6 * self.total_7 * self.total_8 * self.total_9 * self.total_10 \
        * self.total_11 * self.total_12 * self.total_13 * self.total_14 * self.total_15 * self.total_16 * self.total_17 * self.total_18 * self.total_19 * self.total_20

total_totals = fields.Float(string="Total")
</code>```

I've added the default=0.00 to all these totals, but with no results, the total_totals field doesn't do anything, any ideas?

答:
I think your code is working fine. In you multiplication make sure all totals are !=0.

EDIT
I am not sure it is the best answer, but it will full fill your requirement, try below code.

```<code>@api.onchange('total_19','total_18','total_20')
def total21(self):
    total = 1
    for rec in self:
        for i in range(18,21):
            rec1 = eval('rec.total_'+str(i))
            if rec1:
                total = total * rec1
        if total !=1:
            self.total_totals=total
        else:
            self.total_totals=None
</code>```

Body:
Let's say I have these fields:

#Lamination packeting
@api.onchange('cost_rs18', 'qty__m_18')
def total18(self):
    if self.cost_rs18 or self.qty__m_18:
        self.total_18 = self.cost_rs18 * self.qty__m_18

cost_rs18 = fields.Float("Cost Rs.")
qty__m_18 = fields.Integer("Qty")
total_18 = fields.Float(string="Total")
#Packing
@api.onchange('cost_rs19', 'qty__m_19')
def total19(self):
    if self.cost_rs19 or self.qty__m_19:
        self.total_19 = self.cost_rs19 * self.qty__m_19

cost_rs19 = fields.Float("Cost Rs.")
qty__m_19 = fields.Integer("Qty")
total_19 = fields.Float(string="Total")
#Others
@api.onchange('cost_rs20', 'qty__m_20')
def total20(self):
    if self.cost_rs20 or self.qty__m_20:
        self.total_20 = self.cost_rs20 * self.qty__m_20

cost_rs20 = fields.Float("Cost Rs.")
qty__m_20 = fields.Integer("Qty")
total_20 = fields.Float(string="Total")

These obviously sum up on their respective total_n fields.

But on the other hand, not always they should be sumed, let me explain myself.

All these 3 fields (they are actually 20 in my code), have their respective total_n fields which sum up every couple of cost_rs_n and qty__m_n ones.

Now I want to create a "total of totals" which should sum up all the 20 fields, this isn't difficult to figure out, but, my point is, that not always you will be suming all 20, sometimes are 12 active totals, sometimes 2, or sometimes all 20 of them.

How can I achieve this? Can I use the same logic I use on my @api.onchange but for all of them? knowing that not always they all will have data to sum?

EDIT

This is the function I'm actually using, it sums all the totals from all the actual fields I have on my model:

@api.onchange('total_1', 'total_2',
    'total_3', 'total_4', 'total_5', 'total_6',
    'total_7', 'total_8', 'total_9', 'total_10',
    'total_11', 'total_12', 'total_13', 'total_14',
    'total_15', 'total_16', 'total_17', 'total_18',
    'total_19', 'total_20')
def total21(self):
    if self.total_1 or self.total_2 or self.total_3 or self.total_4 or self.total_5 or self.total_6 or self.total_7 or self.total_8 or self.total_9 or self.total_10 \
    or self.total_11 or self.total_12 or self.total_13 or self.total_14 or self.total_15 or self.total_16 or self.total_17 or self.total_18 or self.total_19 or self.total_20:
        self.total_totals = self.total_1 * self.total_2 * self.total_3 * self.total_4 * self.total_5 * self.total_6 * self.total_7 * self.total_8 * self.total_9 * self.total_10 \
        * self.total_11 * self.total_12 * self.total_13 * self.total_14 * self.total_15 * self.total_16 * self.total_17 * self.total_18 * self.total_19 * self.total_20

total_totals = fields.Float(string="Total")

I've added the default=0.00 to all these totals, but with no results, the total_totals field doesn't do anything, any ideas?

Body:
I think your code is working fine. In you multiplication make sure all totals are !=0.

EDIT
I am not sure it is the best answer, but it will full fill your requirement, try below code.

@api.onchange('total_19','total_18','total_20')
def total21(self):
    total = 1
    for rec in self:
        for i in range(18,21):
            rec1 = eval('rec.total_'+str(i))
            if rec1:
                total = total * rec1
        if total !=1:
            self.total_totals=total
        else:
            self.total_totals=None


问:
How to create a web page with the link like page.example.com
I am creating a website in 000webhost. If I purchase a domain ( for example www.example.com ), the index.html page opens when the user types the address in the URL bar. I want a specific page (for example page.html) to open when the user types page.example.com . How do I do that?</p>

答:
You can write a the index.php with the following code:</p>

```<code><?php
  header("Location: page.html");
?>
</code>```

Body:
You can write a the index.php with the following code:

<?php
  header("Location: page.html");
?>


问:
Timing interval between GET and POST request in Node/Express
I am building a quiz website using Node/Express.

How do I ensure that users submit quiz within a specified period of time without using client-side javascript? That is, if the quiz takes 10 minutes, submission afterwards should marked as too late.

Both GET and POST requests are to the same url

答:
I had the same question to solve in a evaluations app.

Here is the way I save a new date allowing to later check on server if the time is bigger than my limit when answering:

Client code:

```<code>startEvaluation: function (data) {
        return $http.put(startUrl + '/' + data._id,data);
      },
</code>```

Server code:

```<code>exports.startEvaluation = function (req, res) {
  if(req.body.status==="NEW")req.body.status="STARTED";
  req.body.started=Date.now();
    Evaluation.findOneAndUpdate({_id: req.body._id}, req.body, {upsert:true , new: true }, function(err, evaluation)
    {
       if (err) {
            return handleError(res, err);
         }
         if (!evaluation) {
            return res.send(404);
         }
    });
};
</code>```

Hope it helps

EDIT:

As you said are the same urls, you can use the parameter (like new for example). This way, if you answer with a NEW condition, you just call the begin  method:

```<code>exports.answer = function (req, res) {
  if(req.body.status==="NEW")
  {
    req.body.status="STARTED";
    req.body.started=Date.now();
  }
  else
  {
    //Process answer here and compare another Date.now() with the stored date, and your time limit to answer
    console.log("answer");
  }

    Evaluation.findOneAndUpdate({_id: req.body._id}, req.body, {upsert:true , new: true }, function(err, evaluation)
    {
       if (err) {
            return handleError(res, err);
         }
         if (!evaluation) {
            return res.send(404);
         }
        //here is the updated evaluation with the started value.
        return res.json(200, evaluations);

    });
};
</code>```

The method on the client:

```<code> $scope.saveAnswer = function ()
            {

                if($rootScope.evaluation.status==="NEW")
                {
                    evaluationService.startEvaluation($rootScope.evaluation);
                }
                else
                {
                  //Your answer treatment
                }

}
</code>```

Anyway, a little improve on server could be done checking the test
  must be started to allow answering.

EDIT

Here is the code for the server to control the status of the
  evaluation/quiz from the backside. This allows you to mark as
  "outdated" the evaluations the user did not finish during the allowed
  20 mins after the beginning of the quiz. Note that a setTimeout is
  done to leave the task on server side, waiting to reach the max time
  configured (20 mins in example)

```<code>function marcarNoTerminada(id, body) {
         //later you can check the status to filter answers given after limit hour
         body.status="NOT FINISHED";
         Evaluation.findOneAndUpdate({_id: id}, body, {upsert:true , new: true }, function(err, evaluation)
    {
       console.log("Evaluacion sin finalizar");
    });
}

exports.startEvaluation = function (req, res) {
  if(req.body.status==="NEW")req.body.status="STARTED";
  req.body.started=Date.now();
  req.body.validEnd= new Date(req.body.started+(60000*20));

    var theTimer = setTimeout(function(){marcarNoTerminada(req.body._id, req.body);}, 60000*20);
    Evaluation.findOneAndUpdate({_id: req.body._id}, req.body, {upsert:true , new: true }, function(err, evaluation)
    {
       if (err) {
            return handleError(res, err);
         }
         if (!evaluation) {
            return res.send(404);
         }

        return res.json(200, evaluation);
    });
};
</code>```

Body:
I had the same question to solve in a evaluations app.

Here is the way I save a new date allowing to later check on server if the time is bigger than my limit when answering:

Client code:

startEvaluation: function (data) {
        return $http.put(startUrl + '/' + data._id,data);
      },

Server code:

exports.startEvaluation = function (req, res) {
  if(req.body.status==="NEW")req.body.status="STARTED";
  req.body.started=Date.now();
    Evaluation.findOneAndUpdate({_id: req.body._id}, req.body, {upsert:true , new: true }, function(err, evaluation)
    {
       if (err) {
            return handleError(res, err);
         }
         if (!evaluation) {
            return res.send(404);
         }
    });
};

Hope it helps

EDIT:

As you said are the same urls, you can use the parameter (like new for example). This way, if you answer with a NEW condition, you just call the begin  method:

exports.answer = function (req, res) {
  if(req.body.status==="NEW")
  {
    req.body.status="STARTED";
    req.body.started=Date.now();
  }
  else
  {
    //Process answer here and compare another Date.now() with the stored date, and your time limit to answer
    console.log("answer");
  }

    Evaluation.findOneAndUpdate({_id: req.body._id}, req.body, {upsert:true , new: true }, function(err, evaluation)
    {
       if (err) {
            return handleError(res, err);
         }
         if (!evaluation) {
            return res.send(404);
         }
        //here is the updated evaluation with the started value.
        return res.json(200, evaluations);

    });
};

The method on the client:

 $scope.saveAnswer = function ()
            {

                if($rootScope.evaluation.status==="NEW")
                {
                    evaluationService.startEvaluation($rootScope.evaluation);
                }
                else
                {
                  //Your answer treatment
                }

}

Anyway, a little improve on server could be done checking the test
  must be started to allow answering.

EDIT

Here is the code for the server to control the status of the
  evaluation/quiz from the backside. This allows you to mark as
  "outdated" the evaluations the user did not finish during the allowed
  20 mins after the beginning of the quiz. Note that a setTimeout is
  done to leave the task on server side, waiting to reach the max time
  configured (20 mins in example)

function marcarNoTerminada(id, body) {
         //later you can check the status to filter answers given after limit hour
         body.status="NOT FINISHED";
         Evaluation.findOneAndUpdate({_id: id}, body, {upsert:true , new: true }, function(err, evaluation)
    {
       console.log("Evaluacion sin finalizar");
    });
}

exports.startEvaluation = function (req, res) {
  if(req.body.status==="NEW")req.body.status="STARTED";
  req.body.started=Date.now();
  req.body.validEnd= new Date(req.body.started+(60000*20));

    var theTimer = setTimeout(function(){marcarNoTerminada(req.body._id, req.body);}, 60000*20);
    Evaluation.findOneAndUpdate({_id: req.body._id}, req.body, {upsert:true , new: true }, function(err, evaluation)
    {
       if (err) {
            return handleError(res, err);
         }
         if (!evaluation) {
            return res.send(404);
         }

        return res.json(200, evaluation);
    });
};


问:
How to access "hidden" file(s) inside .jpg file?
I have this .jpg file that cannot be opened nor viewed. But the thing is my friend who sent me this file said that this file actually contains hidden files inside and is MOST likely encrypted. I searched on Google and I found out that I had to rename the extension ".jpg" to ".zip" and tried to extract the file but it doesn't work. I forgot the message that was shown during my attempt to extract. Maybe the file is actually not a .jpg but something else and is corrupt or maybe it has "hidden" files inside.

So I'm wondering if you guys could help me out.

答: You should use TrIDNet http://mark0.net/soft-tridnet-e.html. I didn't test it but I think that you seek for something like this. Your file has an unknown type and you must find with which known type it matches. </p>


问:
Google play store not showing update option for new apk
I have my app installed in my cell with version 1.0.3 ( Version code 1)  In Google Play Store, I can see my app with version 2.0.1 ( Version code 2 ), but it doesn't show me the button update ( it is showing me the button "Open")  Is it something I have to include in my app???  Is it a bug in Play Store???  Is it a configuration problem??? </p>

答:
Try to clear cache of your Google Play Store and the update button will be shown.

EDIT

As mentioned in this link

Updating system apps

Users will see system apps (including any pre-loaded apps) in the My Apps section of the Google Play Store as soon as an application with the same package name is uploaded to the Play Console (even if the application is unpublished).

Google Play can manage updates to preloaded applications, provided the following conditions are met:

The preloaded app needs to be in the system partition

The preloaded app needs to be free

The preloaded app needs to be signed with the same signature as the app published in Google Play

The package name of the preloaded and updated app needs to be the same

The version code of the updated app needs to be greater than that of the preloaded app


问:
Complex video before starting need a basic simple test
In my Fedora 12, when I run this for just a test, it shows a window but then it shows nothing like its frozen. And, it keeps my terminal image instead of video source.

```<code>$ gst-launch-0.10 v4l2src ! xvimagesink
</code>```

or

```<code>$ gst-launch-0.10 autovideosrc ! autovideosink
</code>```

How to do a test loopback, not having my screen shot inside the popup window?

答:
This works:

```<code>$ gst-launch videotestsrc ! ffmpegcolorspace ! ximagesink
</code>```

Which means, I have colorspace problem while using autovideosink. Any experts tips, would be appreciated.

Thanks

Body:
In my Fedora 12, when I run this for just a test, it shows a window but then it shows nothing like its frozen. And, it keeps my terminal image instead of video source.

$ gst-launch-0.10 v4l2src ! xvimagesink

or

$ gst-launch-0.10 autovideosrc ! autovideosink

How to do a test loopback, not having my screen shot inside the popup window?

Body:
This works:

$ gst-launch videotestsrc ! ffmpegcolorspace ! ximagesink

Which means, I have colorspace problem while using autovideosink. Any experts tips, would be appreciated.

Thanks


问:
Hide div while scrolling down
I just want to hide an image when scroll down and show another image. When scroll to top of the page, first image needs to show and other image needs to be hide.

I tried with this code.

```<code>//This is the image I just want to show at first
<img src="images/logo-wh.png" alt="" class="logo-white">

//This is the image I just want to show when scroll down
<img src="images/logo.png" alt="" class="logo-default">

.logo-default{
  display:none;
}

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
    } else {
        $('.logo-default').show();
    }
 });
</code>```

But it isn't working as I expected. Any suggestions?

答:
Maybe like so:

$(window).scroll(function() {
    if ($(this).scrollTop() <= 0) {
        $('.logo-default').hide();
        $('.logo-white').show();
    } else {
        $('.logo-default').show();
        $('.logo-white').hide();
    }
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.logo-white,
.logo-default {
    position: fixed;
    top: 0px;
}

.logo-default{
    display:none;
}</code>```

```

Title: Hide div while scrolling down

Body:
I just want to hide an image when scroll down and show another image. When scroll to top of the page, first image needs to show and other image needs to be hide.

I tried with this code.

//This is the image I just want to show at first

//This is the image I just want to show when scroll down

.logo-default{
  display:none;
}

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
    } else {
        $('.logo-default').show();
    }
 });

But it isn't working as I expected. Any suggestions?

Body:
Maybe like so:

$(window).scroll(function() {
    if ($(this).scrollTop() <= 0) {
        $('.logo-default').hide();
        $('.logo-white').show();
    } else {
        $('.logo-default').show();
        $('.logo-white').hide();
    }
 });

.logo-white,
.logo-default {
    position: fixed;
    top: 0px;
}

.logo-default{
    display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://lorempixel.com/400/200/sports/1/" alt="" class="logo-white">

<img src="http://lorempixel.com/400/200/sports/2/" alt="" class="logo-default">

<div style="height: 2000px;width: 10px;background-color: orange;"></div>


问:
Permutations with repetition without two consecutive equal elements
I need a function that generates all the permutation with repetition of an iterable with the clause that two consecutive elements must be different; for example

```<code>f([0,1],3).sort()==[(0,1,0),(1,0,1)]
#or
f([0,1],3).sort()==[[0,1,0],[1,0,1]]
#I don't need the elements in the list to be sorted.
#the elements of the return can be tuples or lists, it doesn't change anything
</code>```

Unfortunatly itertools.permutation doesn't work for what I need (each element in the iterable is present once or no times in the return)

I've tried a bunch of definitions; first, filterting elements from itertools.product(iterable,repeat=r) input, but is too slow for what I need.

```<code>from itertools import product
def crp0(iterable,r):
l=[]
for f in product(iterable,repeat=r):
    #print(f)
    b=True
    last=None #supposing no element of the iterable is None, which is fine for me
    for element in f:
        if element==last:
            b=False
            break
        last=element
    if b: l.append(f)
return l
</code>```

Second, I tried to build r for cycle, one inside the other (where r is the class of the permutation, represented as k in math).

```<code>def crp2(iterable,r):
    a=list(range(0,r))
    s="\n"
    tab="    " #4 spaces
    l=[]
    for i in a:
        s+=(2*i*tab+"for a["+str(i)+"] in iterable:\n"+
        (2*i+1)*tab+"if "+str(i)+"==0 or a["+str(i)+"]!=a["+str(i-1)+"]:\n")
    s+=(2*i+2)*tab+"l.append(a.copy())"
    exec(s)
    return l
</code>```

I know, there's no need you remember me: exec is ugly, exec can be dangerous, exec isn't easy-readable... I know.
To understand better the function I suggest you to replace exec(s) with print(s).

I give you an example of what string is inside the exec for crp([0,1],2):

```<code>for a[0] in iterable:
    if 0==0 or a[0]!=a[-1]:
        for a[1] in iterable:
            if 1==0 or a[1]!=a[0]:
                l.append(a.copy())
</code>```

But, apart from using exec, I need a better functions because crp2 is still too slow (even if faster than crp0); there's any way to recreate the code with r for without using exec? There's any other way to do what I need?

答:
You could prepare the sequences in two halves, then preprocess the second halves to find the compatible choices.

```<code>def crp2(I,r):
    r0=r//2
    r1=r-r0
    A=crp0(I,r0) # Prepare first half sequences
    B=crp0(I,r1) # Prepare second half sequences
    D = {} # Dictionary showing compatible second half sequences for each token
    for i in I:
        D[i] = [b for b in B if b[0]!=i]
    return [a+b for a in A for b in D[a[-1]]]
</code>```

In a test with iterable=[0,1,2] and r=15, I found this method to be over a hundred times faster than just using crp0.

ContentLicense: CC BY-SA 4.0

Body:
I need a function that generates all the permutation with repetition of an iterable with the clause that two consecutive elements must be different; for example

f([0,1],3).sort()==[(0,1,0),(1,0,1)]
#or
f([0,1],3).sort()==[[0,1,0],[1,0,1]]
#I don't need the elements in the list to be sorted.
#the elements of the return can be tuples or lists, it doesn't change anything

Unfortunatly itertools.permutation doesn't work for what I need (each element in the iterable is present once or no times in the return)

I've tried a bunch of definitions; first, filterting elements from itertools.product(iterable,repeat=r) input, but is too slow for what I need.

from itertools import product
def crp0(iterable,r):
l=[]
for f in product(iterable,repeat=r):
    #print(f)
    b=True
    last=None #supposing no element of the iterable is None, which is fine for me
    for element in f:
        if element==last:
            b=False
            break
        last=element
    if b: l.append(f)
return l

Second, I tried to build r for cycle, one inside the other (where r is the class of the permutation, represented as k in math).

def crp2(iterable,r):
    a=list(range(0,r))
    s="\n"
    tab="    " #4 spaces
    l=[]
    for i in a:
        s+=(2*i*tab+"for a["+str(i)+"] in iterable:\n"+
        (2*i+1)*tab+"if "+str(i)+"==0 or a["+str(i)+"]!=a["+str(i-1)+"]:\n")
    s+=(2*i+2)*tab+"l.append(a.copy())"
    exec(s)
    return l

I know, there's no need you remember me: exec is ugly, exec can be dangerous, exec isn't easy-readable... I know.
To understand better the function I suggest you to replace exec(s) with print(s).

I give you an example of what string is inside the exec for crp([0,1],2):

for a[0] in iterable:
    if 0==0 or a[0]!=a[-1]:
        for a[1] in iterable:
            if 1==0 or a[1]!=a[0]:
                l.append(a.copy())

But, apart from using exec, I need a better functions because crp2 is still too slow (even if faster than crp0); there's any way to recreate the code with r for without using exec? There's any other way to do what I need?

Body:
You could prepare the sequences in two halves, then preprocess the second halves to find the compatible choices.

def crp2(I,r):
    r0=r//2
    r1=r-r0
    A=crp0(I,r0) # Prepare first half sequences
    B=crp0(I,r1) # Prepare second half sequences
    D = {} # Dictionary showing compatible second half sequences for each token
    for i in I:
        D[i] = [b for b in B if b[0]!=i]
    return [a+b for a in A for b in D[a[-1]]]

In a test with iterable=[0,1,2] and r=15, I found this method to be over a hundred times faster than just using crp0.


问:
Controller Function Not called inside Directive
I have a controller function and I cannot call it inside the directive. I am trying hard. is there any thing Else i am failing to do? please tell me. I have included my code here. I have searched many places followed many answers and now I am stuck at this

(function () {
  var app = angular.module("featureModule", ['ngRoute']);
//

app.directive('myGoogleAutocomplete', function () {
 return {
  replace: true,
  require: 'ngModel',
  scope: {
   ngModel: '=',
   googleModel: '=',
   onSelect: '&?', // optional callback on selected successfully: 'onPostedBid(googleModel)'
  },
  template: '<input class="form-control" type="text" style="z-index: 100000;" autocomplete="on">',
  link: function ($scope, element, attrs, model)
  {

   var autocomplete = new google.maps.places.Autocomplete(element[0], googleOptions);

   google.maps.event.addListener(autocomplete, 'place_changed', function () {

    $scope.$apply(function () {
     var place = autocomplete.getPlace();
     if (!place.geometry)
      {
      // User entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed.
      model.$setValidity('place', false);
      //console.log("No details available for input: '" + place.name + "'");
      return;
     }

     $scope.googleModel = {};
     $scope.googleModel.placeId = place.place_id;
     $scope.googleModel.latitude = place.geometry.location.lat();
     $scope.googleModel.longitude = place.geometry.location.lng();
     $scope.googleModel.formattedAddress = place.formatted_address;
     if (place.address_components) {
      $scope.googleModel.address = [
       $scope.extract(place.address_components, 'route'),
       $scope.extract(place.address_components, 'street_number')
      ].join(' ');

     }

     model.$setViewValue(element.val());
     model.$setValidity('place', true);
     if (attrs.onSelect)
     {
     //how to call controller function here?
      $scope.onSelect({ $item: $scope.googleModel });
    }
    });
   });
  }
 }

});

app.controller("featureController", function($scope,$http,$rootScope,close,ModalService,NgMap) {
console.log($rootScope.permService);

$scope.onSelect=function(val)
{

 console.log(val);
}

});

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <my-google-autocomplete id="address"  name="address" ng-model="task.house_no" google-model="model.googleAddress"
                on-select="vm.onSelectGoogleAddress($item)" autocomplete="off" required>
              </my-google-autocomplete></code>```

答:
There is no onSelectGoogleAddress() function in the controller. I see only onSelect() function. Change on-select value passed in the html.</p>

```<code> <my-google-autocomplete id="address"  name="address" ng-model="task.house_no" google-model="model.googleAddress"
            on-select="onSelect($item)" autocomplete="off" required>
          </my-google-autocomplete>
</code>```

Body:
I have a controller function and I cannot call it inside the directive. I am trying hard. is there any thing Else i am failing to do? please tell me. I have included my code here. I have searched many places followed many answers and now I am stuck at this

(function () {
  var app = angular.module("featureModule", ['ngRoute']);
//

app.directive('myGoogleAutocomplete', function () {
 return {
  replace: true,
  require: 'ngModel',
  scope: {
   ngModel: '=',
   googleModel: '=',
   onSelect: '&?', // optional callback on selected successfully: 'onPostedBid(googleModel)'
  },
  template: '<input class="form-control" type="text" style="z-index: 100000;" autocomplete="on">',
  link: function ($scope, element, attrs, model)
  {

   var autocomplete = new google.maps.places.Autocomplete(element[0], googleOptions);

   google.maps.event.addListener(autocomplete, 'place_changed', function () {

    $scope.$apply(function () {
     var place = autocomplete.getPlace();
     if (!place.geometry)
      {
      // User entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed.
      model.$setValidity('place', false);
      //console.log("No details available for input: '" + place.name + "'");
      return;
     }

     $scope.googleModel = {};
     $scope.googleModel.placeId = place.place_id;
     $scope.googleModel.latitude = place.geometry.location.lat();
     $scope.googleModel.longitude = place.geometry.location.lng();
     $scope.googleModel.formattedAddress = place.formatted_address;
     if (place.address_components) {
      $scope.googleModel.address = [
       $scope.extract(place.address_components, 'route'),
       $scope.extract(place.address_components, 'street_number')
      ].join(' ');

     }

     model.$setViewValue(element.val());
     model.$setValidity('place', true);
     if (attrs.onSelect)
     {
     //how to call controller function here?
      $scope.onSelect({ $item: $scope.googleModel });
    }
    });
   });
  }
 }

});

app.controller("featureController", function($scope,$http,$rootScope,close,ModalService,NgMap) {
console.log($rootScope.permService);

$scope.onSelect=function(val)
{

 console.log(val);
}

});

 <my-google-autocomplete id="address"  name="address" ng-model="task.house_no" google-model="model.googleAddress"
                on-select="vm.onSelectGoogleAddress($item)" autocomplete="off" required>
              </my-google-autocomplete>

Body:
There is no onSelectGoogleAddress() function in the controller. I see only onSelect() function. Change on-select value passed in the html.

 <my-google-autocomplete id="address"  name="address" ng-model="task.house_no" google-model="model.googleAddress"
            on-select="onSelect($item)" autocomplete="off" required>
          </my-google-autocomplete>


问:
HikariCP: What database level timeouts should be considered to set maxLifetime for Oracle 11g
In the documentation for HikariCP, it is mentioned that

We strongly recommend setting this value, and it should be at least 30 seconds less than any database-level connection timeout.

What are those database-level connection timeouts that should be taken into account for Oracle11.2 database? And how could I find those timeouts (queries to execute)?

答:
Short answer: none (by default).

For the record (to include details here in case the link changes), we're talking about property maxLifetime of HikariCP:

This property controls the maximum lifetime of a connection in the pool. An in-use connection will never be retired, only when it is closed will it then be removed. We strongly recommend setting this value, and it should be at least 30 seconds less than any database or infrastructure imposed connection time limit. A value of 0 indicates no maximum lifetime (infinite lifetime), subject of course to the idleTimeout setting. Default: 1800000 (30 minutes)

In my experience, it's a good thing that HikariCP does that. As far as I can tell by default Oracle does not enforce a max lifetime for connections (neither on JDBC driver side (1), nor on server side(2)). So in this respect, the "infrastructure-imposed connection time limit" is +infinity -- and that was a problem for us, as we did observe issues with long-lived connections. It also means any value is "at least 30 seconds less", including the default :)

I suppose the connection layer does not do anything about this because it counts on the pool layer above to handle such things. It was not possible with (now deprecated) implicit connection pool, and I don't know if UCP (the replacement) does that, but if you use HikariCP you don't use those.

Now, after 30 minutes (usually after many reuses for various purposes) for a given connection, HikariCP closes it and creates a fresh one. That has a very minor cost, and fixed our issues with long-lived connections. We're happy with that default, but still make it configurable just in case (see 2 below).

(1) OracleDataSource does not offer any configuration point (property or system property) to control that, and I observed infinite lifetime.

(2) For server-side limits, see profile parameter IDLE_TIME. Quoting
this answer:

Oracle by default will not close a connection due to inactivity. You can configure a profile with an IDLE_TIME to cause Oracle to close inactive connections.

To verify what is the value of IDLE_TIME for your user, combining answers from this Q&A:

```<code>select p.limit
from dba_profiles p, dba_users u
where p.resource_name = 'IDLE_TIME' and p.profile = u.profile and u.username = '...'
;
</code>```

Default value is UNLIMITED.

Please note there can be other limits enforced elsewhere (firewall... yes I've been bitten by that, although most DB systems have a keep-alive mechanism) that might interfere. So you'd better make it configurable, in case such issues are discovered when you deploy your product.

On Linux, you can verify max lifetime of physical connections by monitoring TCP sockets connected to your database. I've been running script below on my server (from the DB point of view that's the client host), it takes 1 argument, the ip:port of your oracle node, as it appears in output of netstat -tan (or a pattern if you have several nodes).

```<code>#!/bin/bash
target="$1"
dir=$(mktemp -d)
while sleep 10
do
    echo "------------ "$(date)
    now=$(date +%s)
    netstat -tan | grep " $target " | awk '{print $4}' | cut -f2 -d: | while read port
    do
        file="p_$port"
        [ ! -e $file ] && touch $file
        ftime=$(stat -c %Z "$file")
        echo -e "$port :\t "$(( now - ftime))
    done
done
\rm "$dir"/p_*
\rmdir "$dir"
</code>```

If you run that and stop it with ctrl-c during sleep time, it should exit the loop and clean up the temp directory, but this is not 100% foolproof

In the results none of the ports should show a value that exceeds 1800 seconds (ie 30 minutes), give or take a minute. See example output below, first sample shows 2 sockets above 1800s, they're gone 10s later.

```<code>------------ Thu Jul 6 16:09:00 CEST 2017
49806 :  1197
49701 :  1569
49772 :  1348
49782 :  1317
49897 :  835
49731 :  1448
49620 :  1830
49700 :  1569
49986 :  523
49722 :  1498
49715 :  1509
49711 :  1539
49629 :  1820
49732 :  1448
50026 :  332
49849 :  1036
49858 :  1016
------------ Thu Jul 6 16:09:10 CEST 2017
49806 :  1207
49701 :  1579
49772 :  1358
49782 :  1327
49897 :  845
49731 :  1458
49700 :  1579
49986 :  533
49722 :  1508
49715 :  1519
49711 :  1549
49732 :  1458
50026 :  342
49849 :  1046
49858 :  1026
</code>```

You'll need to run the script for more than 30 minutes to see that, because it does not know age of sockets that existed before

Body:
Short answer: none (by default).

For the record (to include details here in case the link changes), we're talking about property maxLifetime of HikariCP:

This property controls the maximum lifetime of a connection in the pool. An in-use connection will never be retired, only when it is closed will it then be removed. We strongly recommend setting this value, and it should be at least 30 seconds less than any database or infrastructure imposed connection time limit. A value of 0 indicates no maximum lifetime (infinite lifetime), subject of course to the idleTimeout setting. Default: 1800000 (30 minutes)

In my experience, it's a good thing that HikariCP does that. As far as I can tell by default Oracle does not enforce a max lifetime for connections (neither on JDBC driver side (1), nor on server side(2)). So in this respect, the "infrastructure-imposed connection time limit" is +infinity -- and that was a problem for us, as we did observe issues with long-lived connections. It also means any value is "at least 30 seconds less", including the default :)

I suppose the connection layer does not do anything about this because it counts on the pool layer above to handle such things. It was not possible with (now deprecated) implicit connection pool, and I don't know if UCP (the replacement) does that, but if you use HikariCP you don't use those.

Now, after 30 minutes (usually after many reuses for various purposes) for a given connection, HikariCP closes it and creates a fresh one. That has a very minor cost, and fixed our issues with long-lived connections. We're happy with that default, but still make it configurable just in case (see 2 below).

(1) OracleDataSource does not offer any configuration point (property or system property) to control that, and I observed infinite lifetime.

(2) For server-side limits, see profile parameter IDLE_TIME. Quoting
this answer:

Oracle by default will not close a connection due to inactivity. You can configure a profile with an IDLE_TIME to cause Oracle to close inactive connections.

To verify what is the value of IDLE_TIME for your user, combining answers from this Q&A:

select p.limit
from dba_profiles p, dba_users u
where p.resource_name = 'IDLE_TIME' and p.profile = u.profile and u.username = '...'
;

Default value is UNLIMITED.

Please note there can be other limits enforced elsewhere (firewall... yes I've been bitten by that, although most DB systems have a keep-alive mechanism) that might interfere. So you'd better make it configurable, in case such issues are discovered when you deploy your product.

On Linux, you can verify max lifetime of physical connections by monitoring TCP sockets connected to your database. I've been running script below on my server (from the DB point of view that's the client host), it takes 1 argument, the ip:port of your oracle node, as it appears in output of netstat -tan (or a pattern if you have several nodes).

#!/bin/bash
target="$1"
dir=$(mktemp -d)
while sleep 10
do
    echo "------------ "$(date)
    now=$(date +%s)
    netstat -tan | grep " $target " | awk '{print $4}' | cut -f2 -d: | while read port
    do
        file="p_$port"
        [ ! -e $file ] && touch $file
        ftime=$(stat -c %Z "$file")
        echo -e "$port :\t "$(( now - ftime))
    done
done
\rm "$dir"/p_*
\rmdir "$dir"

If you run that and stop it with ctrl-c during sleep time, it should exit the loop and clean up the temp directory, but this is not 100% foolproof

In the results none of the ports should show a value that exceeds 1800 seconds (ie 30 minutes), give or take a minute. See example output below, first sample shows 2 sockets above 1800s, they're gone 10s later.

------------ Thu Jul 6 16:09:00 CEST 2017
49806 :  1197
49701 :  1569
49772 :  1348
49782 :  1317
49897 :  835
49731 :  1448
49620 :  1830
49700 :  1569
49986 :  523
49722 :  1498
49715 :  1509
49711 :  1539
49629 :  1820
49732 :  1448
50026 :  332
49849 :  1036
49858 :  1016
------------ Thu Jul 6 16:09:10 CEST 2017
49806 :  1207
49701 :  1579
49772 :  1358
49782 :  1327
49897 :  845
49731 :  1458
49700 :  1579
49986 :  533
49722 :  1508
49715 :  1519
49711 :  1549
49732 :  1458
50026 :  342
49849 :  1046
49858 :  1026

You'll need to run the script for more than 30 minutes to see that, because it does not know age of sockets that existed before


问:
Autodetect classes in Hibernate from jar
I have a JavaEE project with several entities with the following persistence.xml file:

```<code>...
<properties>
    <!-- Scan for annotated classes -->
    <property name="hibernate.archive.autodetection" value="class"/>
...
</code>```

And it seems to work. The project is then deployed as a JAR to two different projects. In one them, the persistence.xml file is basically the same as the one above, i.e. uses the autodetection feature of Hibernate. However, it does not seem to work (because I think it needs to load search for the entities in a jar). When I tried manually listing all the entities in both xml files, everything works correctly.

Edit: It works with jar-file but only with the absolute path to the jar. Pretty useless for a team project.

答:
Using the empty element <jar-file></jar-file> works e.g. with WildFly 8.2.1.Final (Hibernate 4.3.7.Final) :) as mentioned here.
(<property name="hibernate.archive.autodetection" value="class, hbm" /> did not work)

(but it did not work outside of WildFly for Eclipse-run JUnit tests where we had to remove it. Which is not a problem since the libraries are already in the classpath. The error was something like: java.net.URISyntaxException: Expected scheme-specific part at index 5: file:> => <java.lang.IllegalArgumentException: Unable to visit JAR file:. Cause: Expected scheme-specific part at index 5: file:> => <javax.persistence.PersistenceException: Unable to build entity manager factory)

Body:
I have a JavaEE project with several entities with the following persistence.xml file:

...
<properties>

    <property name="hibernate.archive.autodetection" value="class"/>
...

And it seems to work. The project is then deployed as a JAR to two different projects. In one them, the persistence.xml file is basically the same as the one above, i.e. uses the autodetection feature of Hibernate. However, it does not seem to work (because I think it needs to load search for the entities in a jar). When I tried manually listing all the entities in both xml files, everything works correctly.

Edit: It works with jar-file but only with the absolute path to the jar. Pretty useless for a team project.


问:
How to install packages in Python 2.7 without internet connections in Windows machine?
I have a machine which is a Windows server, where installation by downloading packages from internet is prohibited. Before that I tried to set up Python 2.7 on my windows machine with internet.I have downloaded and installed pysftp, paramiko, bcrypt, cryptography, pyasn, PyNaCl etc. and also have installed Microsoft visual c++ which was required for pyasn. I have updated pip to 9.0.1 as well. But when I tried to set up on another Windows machine with the help of all packages (unzipped and copied to that machine),installation failed always.
I have tried with
    python setup.py install
and
    pip install

So can we install packages without internet connection?

Please help me on this.

Thanks and regards,
Shreeram

答: Can't you just copy the source and execute "pip install ." in the directory ?</p>


问:
I have created two classes, when I entered negative quantity and negative price it does not set to be "0" and "0.0"
I have created two classes, when I entered negative quantity and negative price it does not set to be "0" and "0.0" respectively as I assigned condition in  setitmprch(int itmprch) and setitmprch(int itmprch) methods. Kindly tell where I did a mistake.

```<code>public class INVOICE {
private String pn;
private String pdscp;
private int itmprch;
private double prpitm;
private double amount;

public INVOICE(String pn, String pdscp, int itmprch, double prpitm ){
    this.pn=pn;
    this.pdscp=pdscp;
    this.itmprch=itmprch;
    this.prpitm=prpitm;

}

public void setpn(String pn){
    this.pn=pn;
}
public void setpdscp(String pdscp){
    this.pdscp=pdscp;
   }

public void setitmprch(int itmprch){
    if (itmprch < 0)
        itmprch=0;
}
public void setprpitm(double prpitm){
   if(prpitm > 0.0)
       this.prpitm=prpitm;
   else if(prpitm < 0.0)
       this.prpitm=0.0;
}

public String getpn(){
return pn;
}

public String getpdscp(){
return pdscp;
}
public int getitmprch(){
return itmprch;
}
public double getprpitm(){
return prpitm;
}
public double getInvoiceAmount(){
amount= getitmprch()*getprpitm();
return amount;
}
}

   public class INVOICETEST {

public static void main(String[] args) {
    // TODO code application logic here
INVOICE in= new INVOICE("Mercedez","Arw 777",-3,-2.0);

System.out.printf("Part number is: %s\n",in.getpn());
System.out.printf("Part decription is: %s\n", in.getpdscp());
System.out.printf("Item purchased: %s\n",in.getitmprch());
System.out.printf("Price per item is: %s\n",in.getprpitm());
System.out.printf("Total amount is: %s\n",in.getInvoiceAmount());

}

}
</code>```

答:
You are assigning values to the method parameters, which will be lost as soon as you exit your method. Add this.itmprch = itmprch to your setitmprch method. Also have a look at some Java programming guidelines to improve code readability.

```<code>public void setitmprch(int itmprch){
    if (itmprch < 0)
        itmprch=0;
    this.itmprch = itmprch;
}
</code>```

Also your constructor should call the setter methods instead of assign values directly. It would look something like this:

```<code>public INVOICE(String pn, String pdscp, int itmprch, double prpitm ){
    setpn(pn);
    setpdscp(pdscp);
    setitmprch(itmprch);
    setprpitm(prpitm);
}
</code>```

Body:
I have created two classes, when I entered negative quantity and negative price it does not set to be "0" and "0.0" respectively as I assigned condition in  setitmprch(int itmprch) and setitmprch(int itmprch) methods. Kindly tell where I did a mistake.

public class INVOICE {
private String pn;
private String pdscp;
private int itmprch;
private double prpitm;
private double amount;

public INVOICE(String pn, String pdscp, int itmprch, double prpitm ){
    this.pn=pn;
    this.pdscp=pdscp;
    this.itmprch=itmprch;
    this.prpitm=prpitm;

}

public void setpn(String pn){
    this.pn=pn;
}
public void setpdscp(String pdscp){
    this.pdscp=pdscp;
   }

public void setitmprch(int itmprch){
    if (itmprch < 0)
        itmprch=0;
}
public void setprpitm(double prpitm){
   if(prpitm > 0.0)
       this.prpitm=prpitm;
   else if(prpitm < 0.0)
       this.prpitm=0.0;
}

public String getpn(){
return pn;
}

public String getpdscp(){
return pdscp;
}
public int getitmprch(){
return itmprch;
}
public double getprpitm(){
return prpitm;
}
public double getInvoiceAmount(){
amount= getitmprch()*getprpitm();
return amount;
}
}

   public class INVOICETEST {

public static void main(String[] args) {
    // TODO code application logic here
INVOICE in= new INVOICE("Mercedez","Arw 777",-3,-2.0);

System.out.printf("Part number is: %s\n",in.getpn());
System.out.printf("Part decription is: %s\n", in.getpdscp());
System.out.printf("Item purchased: %s\n",in.getitmprch());
System.out.printf("Price per item is: %s\n",in.getprpitm());
System.out.printf("Total amount is: %s\n",in.getInvoiceAmount());

}

}

Body:
You are assigning values to the method parameters, which will be lost as soon as you exit your method. Add this.itmprch = itmprch to your setitmprch method. Also have a look at some Java programming guidelines to improve code readability.

public void setitmprch(int itmprch){
    if (itmprch < 0)
        itmprch=0;
    this.itmprch = itmprch;
}

Also your constructor should call the setter methods instead of assign values directly. It would look something like this:

public INVOICE(String pn, String pdscp, int itmprch, double prpitm ){
    setpn(pn);
    setpdscp(pdscp);
    setitmprch(itmprch);
    setprpitm(prpitm);
}


问:
Select most unique markers, linestyles and colours
i would like to automatise the selection of line styles, markers and colours.  I would like to have a function like this:

```<code>function [selected_lineStyles, selected_markers, selected_colours] = plot_lineStyle_markers_and_colours(i)
    linestyles = {'-', '--', ':', '-.'};
    colours = {'red', [0.0, 220.0, 0.0]./255.0, 'blue', 'black', [255.0, 180.0, 0.0]./255.0, [0.0, 128.0, 0.0]./255.0, [0.0, 255.0, 255.0]./255.0, [1.0, 0.0, 1.0]};
    markers = {'d', '*', '+', 'x', 'o', 's', '^', 'v', '.', '>', '<', 'p', 'h'};
    num_different_lineStyles = numel(linestyles);
    num_different_markers = numel(markers);
    num_different_colours = numel(colours);
    num_different_combinations = num_different_markers*num_different_lineStyles*num_different_colours;
    if any(i(:) > num_different_combinations)
        warning('Not enough unique combinations of line styles, markers and colours available!');
    end
    i = 1 + mod(i - 1, num_different_combinations);
    [lineStyle_i, marker_i, colour_i] = ind2sub([num_different_lineStyles, num_different_markers, num_different_colours], i);
    selected_lineStyles = linestyles(lineStyle_i);
    selected_markers = markers(marker_i);
    selected_colours = colours(colour_i);
end
</code>```

For

```<code>i = 1:4
</code>```

this function returns different linestyles, but the same markers and colours.

But I would like to have it like this: For i = 1, it should return the first linestyle, the first marker and the first colour. For i = 2, it should return the second linestyle, the second marker and the second colour. Same with i = 3 and i = 4. For i = 5, the linestyle has to be repeated for the first time, because there are only 4 of them. However, the function should return the fifth colour and the fifth marker.

In general, the "most unique" combinations of linestyle, marker and colour should be returned for low i, so that in plots they are easy to distinguish.

I have no idea how to phrase, or even solve, this problem mathematically. I guess one has to walk along the diagonals of an n-dimensional, non-square array.

Can somebody help me with this or point me into the right direction?

答:
I noticed that there is something called the distance of an array element to the main array diagonal, and that I want to have the indices in ascending order of this distance. For a 3D subscript index A, this distance is defined as sum(abs([A(1) - A(2), A(2) - A(3), A(3) - A(1)])). Right now I use this function:

```<code>function subs_sorted_by_dist_from_main_diagonal = subs_sorted_by_dist_from_main_diagonal(siz)
    d = numel(siz);
    n = prod(siz);
    i = arrayfun(@(n)1:n, siz, 'UniformOutput', false);
    sub = cell(1, d);
    [sub{:}] = ndgrid(i{:});

    sub2 = zeros(n, d);
    for j = 1:d
        sub2(:, j) = sub{j}(:);
    end

    dist_from_main_diagonal = sum(abs(sub2 - sub2(:, [2:end, 1])), 2);

    [~, sort_index] = sort(dist_from_main_diagonal, 'ascend');

    subs_sorted_by_dist_from_main_diagonal = sub2(sort_index, :);
end
</code>```

which is not optimal, because it sorts all subscript indices, instead of generating them without sorting.

Body:
i would like to automatise the selection of line styles, markers and colours.  I would like to have a function like this:

function [selected_lineStyles, selected_markers, selected_colours] = plot_lineStyle_markers_and_colours(i)
    linestyles = {'-', '--', ':', '-.'};
    colours = {'red', [0.0, 220.0, 0.0]./255.0, 'blue', 'black', [255.0, 180.0, 0.0]./255.0, [0.0, 128.0, 0.0]./255.0, [0.0, 255.0, 255.0]./255.0, [1.0, 0.0, 1.0]};
    markers = {'d', '*', '+', 'x', 'o', 's', '^', 'v', '.', '>', '<', 'p', 'h'};
    num_different_lineStyles = numel(linestyles);
    num_different_markers = numel(markers);
    num_different_colours = numel(colours);
    num_different_combinations = num_different_markers*num_different_lineStyles*num_different_colours;
    if any(i(:) > num_different_combinations)
        warning('Not enough unique combinations of line styles, markers and colours available!');
    end
    i = 1 + mod(i - 1, num_different_combinations);
    [lineStyle_i, marker_i, colour_i] = ind2sub([num_different_lineStyles, num_different_markers, num_different_colours], i);
    selected_lineStyles = linestyles(lineStyle_i);
    selected_markers = markers(marker_i);
    selected_colours = colours(colour_i);
end

For

i = 1:4

this function returns different linestyles, but the same markers and colours.

But I would like to have it like this: For i = 1, it should return the first linestyle, the first marker and the first colour. For i = 2, it should return the second linestyle, the second marker and the second colour. Same with i = 3 and i = 4. For i = 5, the linestyle has to be repeated for the first time, because there are only 4 of them. However, the function should return the fifth colour and the fifth marker.

In general, the "most unique" combinations of linestyle, marker and colour should be returned for low i, so that in plots they are easy to distinguish.

I have no idea how to phrase, or even solve, this problem mathematically. I guess one has to walk along the diagonals of an n-dimensional, non-square array.

Can somebody help me with this or point me into the right direction?

Body:
I noticed that there is something called the distance of an array element to the main array diagonal, and that I want to have the indices in ascending order of this distance. For a 3D subscript index A, this distance is defined as sum(abs([A(1) - A(2), A(2) - A(3), A(3) - A(1)])). Right now I use this function:

function subs_sorted_by_dist_from_main_diagonal = subs_sorted_by_dist_from_main_diagonal(siz)
    d = numel(siz);
    n = prod(siz);
    i = arrayfun(@(n)1:n, siz, 'UniformOutput', false);
    sub = cell(1, d);
    [sub{:}] = ndgrid(i{:});

    sub2 = zeros(n, d);
    for j = 1:d
        sub2(:, j) = sub{j}(:);
    end

    dist_from_main_diagonal = sum(abs(sub2 - sub2(:, [2:end, 1])), 2);

    [~, sort_index] = sort(dist_from_main_diagonal, 'ascend');

    subs_sorted_by_dist_from_main_diagonal = sub2(sort_index, :);
end

which is not optimal, because it sorts all subscript indices, instead of generating them without sorting.