问:
angular 5 - ng2-file-upload: Can't bind to 'uploader' since it isn't a known property of 'div'
I read previous questions and the solutions to the answers were already in place, which is why I started another question

I get the following error with ng2-file-upload in Angular 5:

```<code>    Uncaught Error: Template parse errors:
Can't bind to 'uploader' since it isn't a known property of 'div'. ("s': hasAnotherDropZoneOver}"
                 (fileOver)="fileOverAnother($event)"
                 [ERROR ->][uploader]="uploader"
                 class="well my-drop-zone">
                Another drop zone
"): ng:///AppModule/UploadComponent.html@25:17
    at syntaxError (compiler.js:466)
    at TemplateParser.parse (compiler.js:24312)
    at JitCompiler._parseTemplate (compiler.js:33699)
    at JitCompiler._compileTemplate (compiler.js:33674)
    at eval (compiler.js:33576)
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (compiler.js:33576)
    at eval (compiler.js:33446)
    at Object.then (compiler.js:455)
    at JitCompiler._compileModuleAndComponents (compiler.js:33445)
</code>```

I imported and declared the directive into my app.module.ts and the error persisted. Has anyone had this issue with ng-file-upload and angular 5?

答:
FileUploadModule needs to be imported and added to imports in the module declaring the component.

```<code>import { FileUploadModule } from "ng2-file-upload";   //Should import HERE

imports: [  ...FileUploadModule ... ]   //RIGHT PLACE
</code>```

Angular 2: Can't bind to 'uploader' since it isn't a known property of 'input'

Body:
I read previous questions and the solutions to the answers were already in place, which is why I started another question

I get the following error with ng2-file-upload in Angular 5:

    Uncaught Error: Template parse errors:
Can't bind to 'uploader' since it isn't a known property of 'div'. ("s': hasAnotherDropZoneOver}"
                 (fileOver)="fileOverAnother($event)"
                 [ERROR ->][uploader]="uploader"
                 class="well my-drop-zone">
                Another drop zone
"): ng:///AppModule/UploadComponent.html@25:17
    at syntaxError (compiler.js:466)
    at TemplateParser.parse (compiler.js:24312)
    at JitCompiler._parseTemplate (compiler.js:33699)
    at JitCompiler._compileTemplate (compiler.js:33674)
    at eval (compiler.js:33576)
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (compiler.js:33576)
    at eval (compiler.js:33446)
    at Object.then (compiler.js:455)
    at JitCompiler._compileModuleAndComponents (compiler.js:33445)

I imported and declared the directive into my app.module.ts and the error persisted. Has anyone had this issue with ng-file-upload and angular 5?

Body:
FileUploadModule needs to be imported and added to imports in the module declaring the component.

import { FileUploadModule } from "ng2-file-upload";   //Should import HERE

imports: [  ...FileUploadModule ... ]   //RIGHT PLACE

Angular 2: Can't bind to 'uploader' since it isn't a known property of 'input'


来源: stackexchange

问:
When calculating the space for each direction when the grid size is multiply by 1.5 the directions are wrong why?
If the grid is 10x10 or 23x7 it's working fine but when the grid have 1.5 spaces between the cubes the directions sometimes are wrong.

This is the grid script:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GridGenerator : MonoBehaviour
{
    public GameObject gridBlock;
    public int gridWidth = 10;
    public int gridHeight = 10;
    public GameObject[] allBlocks;

    private GameObject[] wallsParents = new GameObject[4];

    void Start()
    {
        wallsParents[0] = GameObject.Find("Top Wall");
        wallsParents[1] = GameObject.Find("Left Wall");
        wallsParents[2] = GameObject.Find("Right Wall");
        wallsParents[3] = GameObject.Find("Bottom Wall");

        GenerateGrid();
        allBlocks = GameObject.FindGameObjectsWithTag("Blocks");

        var findpath = GetComponent<PathFinder>();
        findpath.FindPath();
    }

    public void AutoGenerateGrid()
    {
        allBlocks = GameObject.FindGameObjectsWithTag("Blocks");

        for (int i = 0; i < allBlocks.Length; i++)
        {
            DestroyImmediate(allBlocks[i]);
        }

        var end = GameObject.FindGameObjectWithTag("End");
        DestroyImmediate(end);

        GenerateGrid();
        allBlocks = GameObject.FindGameObjectsWithTag("Blocks");

        var findpath = GetComponent<PathFinder>();
        findpath.FindPath();
    }

    public void GenerateGrid()
    {
        for (int x = 0; x < gridWidth; x++)
        {
            for (int z = 0; z < gridHeight; z++)
            {
                GameObject block = Instantiate(gridBlock, Vector3.zero, gridBlock.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.name = "Block";
                block.transform.tag = "Blocks";
                block.transform.localPosition = new Vector3(x * 1.5f, 0, z * 1.5f);
                block.GetComponent<Renderer>().material.color = new Color(241, 255, 0, 255);

                if (x == 0)//TOP
                {
                    block.transform.parent = wallsParents[0].transform;
                    block.transform.name = "TopWall";
                    block.transform.tag = "Blocks";
                }
                else if (z == 0)//LEFT
                {
                    block.transform.parent = wallsParents[1].transform;
                    block.transform.name = "LeftWall";
                    block.transform.tag = "Blocks";
                }
                else if (z == gridHeight - 1)//RIGHT
                {
                    block.transform.parent = wallsParents[2].transform;
                    block.transform.name = "RightWall";
                    block.transform.tag = "Blocks";
                }

                else if (x == gridWidth - 1)//BOTTOM
                {
                    block.transform.parent = wallsParents[3].transform;
                    block.transform.name = "BottomWall";
                    block.transform.tag = "Blocks";
                }
            }
        }
    }
}
</code>```

On this line i'm adding the spaces between the cubes:

```<code>block.transform.localPosition = new Vector3(x * 1.5f, 0, z * 1.5f);
</code>```

Then in another script i'm trying to find what directions next are possible to move to.

```<code>private void Directions()
    {
        GridGenerator gridgenerator = GetComponent<GridGenerator>();
        Vector3 playerPosition;
        playerPosition = player.localPosition;

        if (playerPosition.x > 0)
        {
            // can go left
            possibleDirections[0] = "Can go left";
        }
        else
        {
            possibleDirections[0] = "Can't go left";
        }

        if (playerPosition.x + 1 < gridgenerator.gridWidth * 1.5f)
        {
            // can go right
            possibleDirections[1] = "Can go right";
        }
        else
        {
            possibleDirections[1] = "Can't go right";
        }

        if (playerPosition.z > 0)
        {
            // can go backward
            possibleDirections[2] = "Can go backward";
        }
        else
        {
            possibleDirections[2] = "Can't go backward";
        }

        if (playerPosition.z + 1 < gridgenerator.gridHeight * 1.5f)
        {
            // can go backward
            possibleDirections[3] = "Can go forward";
        }
        else
        {
            possibleDirections[3] = "Can't go forward";
        }
    }
</code>```

possibleDirections is array string type

When the grid size is 10x10 without spaces between cubes this two lines:

```<code>if (playerPosition.x + 1 < gridgenerator.gridWidth * 1.5f)
if (playerPosition.z + 1 < gridgenerator.gridHeight * 1.5f)
</code>```

Was:

```<code>if (playerPosition.x + 1 < gridgenerator.gridWidth)
if (playerPosition.z + 1 < gridgenerator.gridHeight)
</code>```

But when i added the spaces between the cubes i tried to add to the gridgenerator.gridWidth and gridgenerator.gridHeight the * 1.5

But it didn't work so i tried also:

```<code>if (playerPosition.x + 1 < gridgenerator.gridWidth * (1 + 1.5))
if (playerPosition.z + 1 < gridgenerator.gridHeight * (1 + 1.5))
</code>```

1 is the cube width and 1.5 is the space. But this is not working good either.

In the screenshot the player is in the top left corner facing up(forward)
He can't move forward but in the inspector it says "Can go forward" And should be "Can't go forward"

It only happens when there are spaces between the cubes.

答:
This line is wrong:

if (playerPosition.x + 1 < gridgenerator.gridWidth * 1.5f)

Your gridWidth variable stores the number of cubes, not their collective spacing.  You have 10 cubes representing move spaces, determining the out-of-bounds this value should remain constant (it's still only 10 cubes, even if they're spaced with a half-block worth of space between them).

You need to convert from the player's scene location (transform.position.x) to a board space location (likely dividing by the same multiplier used to space the cubes out).

Alternatively, the "this makes my soul cry" solution of doing this:

if (playerPosition.x + 1.5f < gridgenerator.gridWidth * 1.5f)

Because the next cube is 1.5 scene units away, not 1.  And this makes my soul cry because it makes your code full of hard-coded 1.5f multipliers and offsets rather than keeping such things to a single, fixed, constant value stored Elsewhere and used sparingly.

Related:

possibleDirections[0] = "Can go left";

Why are you using stringly typed things? There are values called booleans for a reason...

ContentLicense: CC BY-SA 3.0

Body:
If the grid is 10x10 or 23x7 it's working fine but when the grid have 1.5 spaces between the cubes the directions sometimes are wrong.

This is the grid script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GridGenerator : MonoBehaviour
{
    public GameObject gridBlock;
    public int gridWidth = 10;
    public int gridHeight = 10;
    public GameObject[] allBlocks;

    private GameObject[] wallsParents = new GameObject[4];

    void Start()
    {
        wallsParents[0] = GameObject.Find("Top Wall");
        wallsParents[1] = GameObject.Find("Left Wall");
        wallsParents[2] = GameObject.Find("Right Wall");
        wallsParents[3] = GameObject.Find("Bottom Wall");

        GenerateGrid();
        allBlocks = GameObject.FindGameObjectsWithTag("Blocks");

        var findpath = GetComponent<PathFinder>();
        findpath.FindPath();
    }

    public void AutoGenerateGrid()
    {
        allBlocks = GameObject.FindGameObjectsWithTag("Blocks");

        for (int i = 0; i < allBlocks.Length; i++)
        {
            DestroyImmediate(allBlocks[i]);
        }

        var end = GameObject.FindGameObjectWithTag("End");
        DestroyImmediate(end);

        GenerateGrid();
        allBlocks = GameObject.FindGameObjectsWithTag("Blocks");

        var findpath = GetComponent<PathFinder>();
        findpath.FindPath();
    }

    public void GenerateGrid()
    {
        for (int x = 0; x < gridWidth; x++)
        {
            for (int z = 0; z < gridHeight; z++)
            {
                GameObject block = Instantiate(gridBlock, Vector3.zero, gridBlock.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.name = "Block";
                block.transform.tag = "Blocks";
                block.transform.localPosition = new Vector3(x * 1.5f, 0, z * 1.5f);
                block.GetComponent<Renderer>().material.color = new Color(241, 255, 0, 255);

                if (x == 0)//TOP
                {
                    block.transform.parent = wallsParents[0].transform;
                    block.transform.name = "TopWall";
                    block.transform.tag = "Blocks";
                }
                else if (z == 0)//LEFT
                {
                    block.transform.parent = wallsParents[1].transform;
                    block.transform.name = "LeftWall";
                    block.transform.tag = "Blocks";
                }
                else if (z == gridHeight - 1)//RIGHT
                {
                    block.transform.parent = wallsParents[2].transform;
                    block.transform.name = "RightWall";
                    block.transform.tag = "Blocks";
                }

                else if (x == gridWidth - 1)//BOTTOM
                {
                    block.transform.parent = wallsParents[3].transform;
                    block.transform.name = "BottomWall";
                    block.transform.tag = "Blocks";
                }
            }
        }
    }
}

On this line i'm adding the spaces between the cubes:

block.transform.localPosition = new Vector3(x * 1.5f, 0, z * 1.5f);

Then in another script i'm trying to find what directions next are possible to move to.

private void Directions()
    {
        GridGenerator gridgenerator = GetComponent<GridGenerator>();
        Vector3 playerPosition;
        playerPosition = player.localPosition;

        if (playerPosition.x > 0)
        {
            // can go left
            possibleDirections[0] = "Can go left";
        }
        else
        {
            possibleDirections[0] = "Can't go left";
        }

        if (playerPosition.x + 1 < gridgenerator.gridWidth * 1.5f)
        {
            // can go right
            possibleDirections[1] = "Can go right";
        }
        else
        {
            possibleDirections[1] = "Can't go right";
        }

        if (playerPosition.z > 0)
        {
            // can go backward
            possibleDirections[2] = "Can go backward";
        }
        else
        {
            possibleDirections[2] = "Can't go backward";
        }

        if (playerPosition.z + 1 < gridgenerator.gridHeight * 1.5f)
        {
            // can go backward
            possibleDirections[3] = "Can go forward";
        }
        else
        {
            possibleDirections[3] = "Can't go forward";
        }
    }

possibleDirections is array string type

When the grid size is 10x10 without spaces between cubes this two lines:

if (playerPosition.x + 1 < gridgenerator.gridWidth * 1.5f)
if (playerPosition.z + 1 < gridgenerator.gridHeight * 1.5f)

Was:

if (playerPosition.x + 1 < gridgenerator.gridWidth)
if (playerPosition.z + 1 < gridgenerator.gridHeight)

But when i added the spaces between the cubes i tried to add to the gridgenerator.gridWidth and gridgenerator.gridHeight the * 1.5

But it didn't work so i tried also:

if (playerPosition.x + 1 < gridgenerator.gridWidth * (1 + 1.5))
if (playerPosition.z + 1 < gridgenerator.gridHeight * (1 + 1.5))

1 is the cube width and 1.5 is the space. But this is not working good either.

In the screenshot the player is in the top left corner facing up(forward)
He can't move forward but in the inspector it says "Can go forward" And should be "Can't go forward"

It only happens when there are spaces between the cubes.


问:
Calculate the estimated page load time
Is it possible using jQuery/Javascript to calculate the estimated load time of a page?

I've tried the following which I found somewhere online but the time increments on each reload by 200 and when it gets to 6000 it resets back to 0

```<code>var perfData = window.performance.timing,
    EstimatedTime = -(perfData.loadEventEnd - perfData.navigationStart),
    time = parseInt((EstimatedTime/1000)%60)*100;

if (time >= 700) {
    $(window).load(function() {
        // Do something
    });
} else {
    // Do something else
}
</code>```

I wanted it to use a preloader if the estimated page load time was 700ms or more.

答:
The performance Interface will work if well used. It is browser compatible.

Now, the behavior you describe make me confident you just do not use it well.

The «time increments on each reload by 200» just indicates that perfData.loadEventEnd equals zero. Then your calculation just means nothing. You only have the perfData.navigationStart, which is the time in Unix integer.

Now, I would completely remove the maths you have for time. The EstimatedTime already is in milliseconds.

Then, the script should read the timing attribute once the page has fully loaded. Else, the perfData.loadEventEnd will be zero for sure.

So in the load event handler, use setTimeout() to make sure the script will execute AFTER the load event has ended.

```<code>var loadTime = function(){
  setTimeout(function(){
    var perfData = window.performance.timing;
    var EstimatedTime = (perfData.loadEventEnd - perfData.navigationStart);

    if(EstimatedTime>700){
      // Something for load time more than 700 ms
    }else{
      // Something for faster load time
    }
  },10);  // Executes 10 ms after load has ended
};
</code>```

And in the markup:

```<code><body onload="loadTime();">
</code>```

Try to play with it in CodePen.

Your issue reproduced is in this other CodePen.

Title: Calculate the estimated page load time

Body:
Is it possible using jQuery/Javascript to calculate the estimated load time of a page?

I've tried the following which I found somewhere online but the time increments on each reload by 200 and when it gets to 6000 it resets back to 0

var perfData = window.performance.timing,
    EstimatedTime = -(perfData.loadEventEnd - perfData.navigationStart),
    time = parseInt((EstimatedTime/1000)%60)*100;

if (time >= 700) {
    $(window).load(function() {
        // Do something
    });
} else {
    // Do something else
}

I wanted it to use a preloader if the estimated page load time was 700ms or more.

Body:
The performance Interface will work if well used. It is browser compatible.

Now, the behavior you describe make me confident you just do not use it well.

The «time increments on each reload by 200» just indicates that perfData.loadEventEnd equals zero. Then your calculation just means nothing. You only have the perfData.navigationStart, which is the time in Unix integer.

Now, I would completely remove the maths you have for time. The EstimatedTime already is in milliseconds.

Then, the script should read the timing attribute once the page has fully loaded. Else, the perfData.loadEventEnd will be zero for sure.

So in the load event handler, use setTimeout() to make sure the script will execute AFTER the load event has ended.

var loadTime = function(){
  setTimeout(function(){
    var perfData = window.performance.timing;
    var EstimatedTime = (perfData.loadEventEnd - perfData.navigationStart);

    if(EstimatedTime>700){
      // Something for load time more than 700 ms
    }else{
      // Something for faster load time
    }
  },10);  // Executes 10 ms after load has ended
};

And in the markup:

<body onload="loadTime();">

Try to play with it in CodePen.

Your issue reproduced is in this other CodePen.


问:
how to say 60 seconds with currentTimeMilis()
I'm trying to type out a code that outputs random words from a list, the user must type back as many words as possible before 60 seconds has elapsed I am using currentTimeMillis() to keep track of time so this is difficult for me to figure out I tried the code below and it said 6000000000000 is too large of a number but when I output the current/start time, it output 1512409897444 so this doesn't make sense to me.

```<code>long currentTime = System.currentTimeMillis();
long startTime = System.currentTimeMillis();
System.out.println(currentTime);
System.out.println(startTime);
while (startTime <= 6000000000000)
{
    (etc.  ect.)
}
</code>```

答:
What you want to do is compare the current time against the time you started and check if their difference is below 60 seconds, aka 60000 milli seconds:</p>

```<code>long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) <= 60000) {
    // still under 60 seconds...
}
</code>```

Body:
I'm trying to type out a code that outputs random words from a list, the user must type back as many words as possible before 60 seconds has elapsed I am using currentTimeMillis() to keep track of time so this is difficult for me to figure out I tried the code below and it said 6000000000000 is too large of a number but when I output the current/start time, it output 1512409897444 so this doesn't make sense to me.

long currentTime = System.currentTimeMillis();
long startTime = System.currentTimeMillis();
System.out.println(currentTime);
System.out.println(startTime);
while (startTime <= 6000000000000)
{
    (etc.  ect.)
}

Body:
What you want to do is compare the current time against the time you started and check if their difference is below 60 seconds, aka 60000 milli seconds:

long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) <= 60000) {
    // still under 60 seconds...
}


问:
Why C++ does not move to a 'unversioned model' like HTML/HTML5?
First, i must say that i write this from the bottom of my dark, envious heart:

After reading this: http://blog.whatwg.org/html-is-the-new-html5

i wonder, what is up that C++ has become so fosilized that they will take 10 years to get a new standard.

I mean, embedded/ancient platforms don't even notice when a new release of the C++ standard come up because guess what? they are constrained by the platform and compiler vendors, so they for the most part, won't be able to take advantage of the new features anyway. So all this weight dragging seems more self-immolation than desire or respect for backward compatibility and such and such

答:
i wonder, what is up that C++ has become so fosilized that they will take 10 years to get a new standard.

Wait. How long did it take for HTML to get a new standard, again?

The cases of HTML5 and C++0x are very near parallels. Both take ages to get formalized (both not there, yet), as a consequence both could legally be qualified as vaporware.

But in both cases, nobody cares: the upcoming standards are already mostly implemented in modern browsers/compilers.

So what exactly are you complaining about?

ContentLicense: CC BY-SA 2.5


答:
System.currentTimeMillis() returns a value that increases from an "epoch".  You must subtract two time values to determine the amount of time that has elapsed.

```<code>long startTime = System.currentTimeMillis();

long elapsedTime = 0;
while (elapsedTime <= 60000) {
    // etc, etc, etc
    elapsedTime = System.currentTimeMillis() - startTime;
}
</code>```

Title: how to say 60 seconds with currentTimeMilis()

Body:
System.currentTimeMillis() returns a value that increases from an "epoch".  You must subtract two time values to determine the amount of time that has elapsed.

long startTime = System.currentTimeMillis();

long elapsedTime = 0;
while (elapsedTime <= 60000) {
    // etc, etc, etc
    elapsedTime = System.currentTimeMillis() - startTime;
}


问:
Jinja2 templating options not working in test, but are fine when running server
I receive the following error...

```<code>ERRORS:
?: (templates.E001) You have 'APP_DIRS': True in your TEMPLATES but also specify 'loaders' in OPTIONS. Either remove APP_DIRS or remove the 'loaders' option.
</code>```

...when attempting to run any test suite, with Django 1.11 and its standard test runner.

manage.py runserver, however, works just fine.

I tracked the error back to the jinja2 templates. My django TEMPLATES setting looks like:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [os.path.join(BASE_DIR, 'jinja2')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'environment': 'mysite.jinja2.environment',
        },
    },
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, 'templates')],
        "APP_DIRS": True,
        'OPTIONS': {
            'debug': DEBUG,
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'mysite.context_processors.app_rendering_ctx',
            ],
        },
    },
]
</code>```

You'll see there's no loaders key in either of the OPTIONS dicts, so the error is seriously confusing.

Stripping out, it's nothing to do with the context processors or environments. It's related to the jinja2 templating...

Removing the APP_DIRS key from the first entry lets the tests run:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [os.path.join(BASE_DIR, 'jinja2')],
        'OPTIONS': {
            #stuff
        },
    },
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, 'templates')],
        "APP_DIRS": True,
        'OPTIONS': {
            #stuff
        },
    },
]
</code>```

But now I can't find the jinja2 templates in my app directories, so visiting the site gives TemplateNotFound errors (of course!).

Does the jinja2 templating engine dynamically attach a loaders key to its own options dict? And why does the test runner fail with this when the server runs happily?

答:
I'm not going to tick this as selected answer, since it's a workaround not a solution... but others can get over this by manually adding the APP_DIRS they want to search into the DIRS key:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [os.path.join(BASE_DIR, 'jinja2'),
                 os.path.join(BASE_DIR, '..', 'myapp', 'jinja2'),
                 os.path.join(BASE_DIR, '..', 'myotherapp', 'jinja2')],
        'OPTIONS': {
            #stuff
        },
    },
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, 'templates')],
        "APP_DIRS": True,
        'OPTIONS': {
            #stuff
        },
    },
]
</code>```

Of course, this is neither a generic solution nor easily replicated if you have many apps. For just a few its fine.

Body:
I receive the following error...

ERRORS:
?: (templates.E001) You have 'APP_DIRS': True in your TEMPLATES but also specify 'loaders' in OPTIONS. Either remove APP_DIRS or remove the 'loaders' option.

...when attempting to run any test suite, with Django 1.11 and its standard test runner.

manage.py runserver, however, works just fine.

I tracked the error back to the jinja2 templates. My django TEMPLATES setting looks like:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [os.path.join(BASE_DIR, 'jinja2')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'environment': 'mysite.jinja2.environment',
        },
    },
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, 'templates')],
        "APP_DIRS": True,
        'OPTIONS': {
            'debug': DEBUG,
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'mysite.context_processors.app_rendering_ctx',
            ],
        },
    },
]

You'll see there's no loaders key in either of the OPTIONS dicts, so the error is seriously confusing.

Stripping out, it's nothing to do with the context processors or environments. It's related to the jinja2 templating...

Removing the APP_DIRS key from the first entry lets the tests run:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [os.path.join(BASE_DIR, 'jinja2')],
        'OPTIONS': {
            #stuff
        },
    },
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, 'templates')],
        "APP_DIRS": True,
        'OPTIONS': {
            #stuff
        },
    },
]

But now I can't find the jinja2 templates in my app directories, so visiting the site gives TemplateNotFound errors (of course!).

Does the jinja2 templating engine dynamically attach a loaders key to its own options dict? And why does the test runner fail with this when the server runs happily?

Body:
I'm not going to tick this as selected answer, since it's a workaround not a solution... but others can get over this by manually adding the APP_DIRS they want to search into the DIRS key:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [os.path.join(BASE_DIR, 'jinja2'),
                 os.path.join(BASE_DIR, '..', 'myapp', 'jinja2'),
                 os.path.join(BASE_DIR, '..', 'myotherapp', 'jinja2')],
        'OPTIONS': {
            #stuff
        },
    },
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, 'templates')],
        "APP_DIRS": True,
        'OPTIONS': {
            #stuff
        },
    },
]

Of course, this is neither a generic solution nor easily replicated if you have many apps. For just a few its fine.


问:
how to create new build tool sdk in windows
I have the API version 26 of Android sdk on my windows directory:C:\Program Files (x86)\Android\android-sdk\platforms and some other versions like:

```<code>android-23
android-25
android-26
</code>```

but in build-tools folder, i only have a folder named 23.0.3. it means i don't have build tool of another versions. so how can i have 26.0.2 or 26.0.2 in this folder. because now i can just targeting 23 build version for my react-native apps. but i need to target higher versions.

答:
You have to install them with the SDK Manager (more info at https://developer.android.com/studio/intro/update.html#sdk-manager) or with the sdkmanager command line tool (more info at https://developer.android.com/studio/command-line/sdkmanager.html).

For example, with sdkmanager use:

```<code>sdkmanager --list
</code>```

To get available packages and then for example:

```<code>sdkmanager build-tools;26.0.2
</code>```

To install build-tools 26.0.2.

Body:
I have the API version 26 of Android sdk on my windows directory:C:\Program Files (x86)\Android\android-sdk\platforms and some other versions like:

android-23
android-25
android-26

but in build-tools folder, i only have a folder named 23.0.3. it means i don't have build tool of another versions. so how can i have 26.0.2 or 26.0.2 in this folder. because now i can just targeting 23 build version for my react-native apps. but i need to target higher versions.

Body:
You have to install them with the SDK Manager (more info at https://developer.android.com/studio/intro/update.html#sdk-manager) or with the sdkmanager command line tool (more info at https://developer.android.com/studio/command-line/sdkmanager.html).

For example, with sdkmanager use:

sdkmanager --list

To get available packages and then for example:

sdkmanager build-tools;26.0.2

To install build-tools 26.0.2.


问:
Running Angular 2/4 Route instead of .net Core route
in my Angular Module I have the following Route:

```<code> { path: "something/:id", component: SomeComponent }
</code>```

which runs fine when using "routerLinks" frontend, but as soon as I manually write the ID in the URL and press Enter, It runs the C# backend method instead and ignores the angular route.

```<code>[HttpGet("{myid:guid}")]
</code>```

The backend method returns Json as it should but I cant get my Angular route to display my component, seeing I go straight to the Controller.

So my question is: How do I tell my application to run my frontend route instead of my backend route, or work my way around this problem when manually writing the id in the url?

Any help would be greatly appreciated.

答:
I realise this isnt strictly answering your question, but unless you have a specific requirement to handle them on similar routes, isnt it simpler to serve your API on a clearly distinct route using a subdomain or specific base url fragment?

E.g. front end routes go on:
www.example.com

API routes go on:
www.api.example.com or www.example.com/api/

Note that if you cant use the subdomain option, you'll need to configure URL rewrites in your web.config to route between your API and front end.

Body:
in my Angular Module I have the following Route:

 { path: "something/:id", component: SomeComponent }

which runs fine when using "routerLinks" frontend, but as soon as I manually write the ID in the URL and press Enter, It runs the C# backend method instead and ignores the angular route.

[HttpGet("{myid:guid}")]

The backend method returns Json as it should but I cant get my Angular route to display my component, seeing I go straight to the Controller.

So my question is: How do I tell my application to run my frontend route instead of my backend route, or work my way around this problem when manually writing the id in the url?

Any help would be greatly appreciated.


问:
Is border-style mandatory or optional? Discrepant behaviour seen
In CSS I have found that omitting border-style did not matter when coding as:

```<code>input{
/*here border style is not mentioned*/
border-width:  3px;
border-color: red;

}
</code>```

The border was still appearing in this case. However border would not appear if coded as below:

```<code>input{
border: 3px red; /*here border style is not mentioned*/

}
</code>```

I also tested on w3school editors please see the screen shots with border style removed. Why is border appearing in the 3rd screenshot?
What am I missing?

```<code>https://www.w3schools.com/css/tryit.asp?filename=trycss_border-color1
https://imgur.com/xgTVpmN

https://www.w3schools.com/css/tryit.asp?filename=trycss_border
https://imgur.com/b7blLMH

https://www.w3schools.com/css/tryit.asp?filename=trycss_form_focus2
https://imgur.com/1wxD5OG
</code>```

答:
The input elements have a default border definition so when you overwrite each property like in the first example you still see it because you aren't changing the style but with the shorthand you are overwriting the entire default value, and if you don't set any value for style on the shorthand it will take the initial value of the property that in this case is none.

The border CSS property is a shorthand property for setting all individual border property values at once: border-width, border-style, and border-color. As with all shorthand properties, any individual value that is not specified is set to its corresponding initial value.

&

Note: The default value of border-style is none.

From MDN Source

Body:
In CSS I have found that omitting border-style did not matter when coding as:

input{
/*here border style is not mentioned*/
border-width:  3px;
border-color: red;

}

The border was still appearing in this case. However border would not appear if coded as below:

input{
border: 3px red; /*here border style is not mentioned*/

}

I also tested on w3school editors please see the screen shots with border style removed. Why is border appearing in the 3rd screenshot?
What am I missing?

https://www.w3schools.com/css/tryit.asp?filename=trycss_border-color1
https://imgur.com/xgTVpmN

https://www.w3schools.com/css/tryit.asp?filename=trycss_border
https://imgur.com/b7blLMH

https://www.w3schools.com/css/tryit.asp?filename=trycss_form_focus2
https://imgur.com/1wxD5OG


问:
Left weighted fast search on large text dataset - Mysql
I have a large dataset that I would like to use for autocomplete (>1M records) on mysql.

As an example I am typing "Methanol" and wanting typeahead suggestions..

Currently I have

```<code>select AgentReferenceName as name
from tblAgentReference
where AgentReferenceName like '%methan%'
order by instr(AgentReferenceName,'methan'), char_length(AgentReferenceName)
limit 10;
</code>```

This does the job nicely, but is a bit slow

```<code>+-------------+
| name        |
+-------------+
| Methan      |
| Methane     |
| Methane     |
| Methane     |
| Methanal    |
| Methanol    |
| Methanol    |
| Methanide   |
| Methanamine |
| Methanamine |
+-------------+
10 rows in set (3.52 sec)
</code>```

I have a fulltext index on the field but when I run the usual fulltext weighted search - it bumps up the larger words so I get

```<code>select AgentReferenceName as name  from tblAgentReference  where match(AgentReferenceName) against ('methano*' in boolean mode)   order by match(AgentReferenceName) against ('methano*') limit 10;
+----------------------------------------------------------------------------------------------------------+
| name                                                                                |
+----------------------------------------------------------------------------------------------------------+
| 2,4-Methanoacridin-9-amine, 8-fluoro-1,2,3,4-tetrahydro-, 2-hydroxy-1,2,3-propanetricarboxylate (3:2)    |
| 9-Amino-8-fluoro-1,2,3,4-tetrahydro-2,4-methanoacridine                                                  |
| 9-Amino-8-fluoro-1,2,3,4-tetrahydro-2,4-methanoacridine                                                  |
| 2,4-Methanoadamantane                                                                                |
| 2,4-Methanoadamantane                                                                                |
| 2-Amino-4,5-methanoadipate                                                                               |
| 1,4-Methanoanthra(2,3-c)oxepin-7,12-dione, 1,3,4,5-tetrahydro-4,6,13-trihydroxy-3,11-dimethoxy-3-methyl- |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4-tetrahydro-                                                    |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4-tetrahydro-                                                    |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4,4a,9a-hexahydro-                                               |
+----------------------------------------------------------------------------------------------------------+
10 rows in set (0.13 sec)
</code>```

So speed is good, but results are terrible

My question - how to do a fast search that returns similar to the like query, but nearer to the speed of the fulltext one?

答:
(Some random thoughts...)

```<code>WHERE MATCH(...) AGAINST(...)
  AND ... LIKE ...
</code>```

It should filter using FULLTEXT first, then further filter via LIKE.

But... I am puzzled by your current code.  The first example (using instr) tends to pick data starting with "Methan".  That can be much more efficiently performed with

```<code>AgentReferenceName LIKE 'Methan%'
</code>```

assuming you have INDEX(AgentReferenceName).  IfAgentReferenceNameisTEXTand notVARCHAR`, then consider an extra column with just short names indexed.

Then consider

```<code>( SELECT ... WHERE ... LIKE 'Methan%' ... LIMIT 10 )
UNION DISTINCT
( SELECT ... WHERE MATCH ... LIMIT 10 )
</code>```

This will give you up to 20 rows for further sorting (and whittling down to 10) -- possibly in app code.

Body:
I have a large dataset that I would like to use for autocomplete (>1M records) on mysql.

As an example I am typing "Methanol" and wanting typeahead suggestions..

Currently I have

select AgentReferenceName as name
from tblAgentReference
where AgentReferenceName like '%methan%'
order by instr(AgentReferenceName,'methan'), char_length(AgentReferenceName)
limit 10;

This does the job nicely, but is a bit slow

+-------------+
| name        |
+-------------+
| Methan      |
| Methane     |
| Methane     |
| Methane     |
| Methanal    |
| Methanol    |
| Methanol    |
| Methanide   |
| Methanamine |
| Methanamine |
+-------------+
10 rows in set (3.52 sec)

I have a fulltext index on the field but when I run the usual fulltext weighted search - it bumps up the larger words so I get

select AgentReferenceName as name  from tblAgentReference  where match(AgentReferenceName) against ('methano*' in boolean mode)   order by match(AgentReferenceName) against ('methano*') limit 10;
+----------------------------------------------------------------------------------------------------------+
| name                                                                                |
+----------------------------------------------------------------------------------------------------------+
| 2,4-Methanoacridin-9-amine, 8-fluoro-1,2,3,4-tetrahydro-, 2-hydroxy-1,2,3-propanetricarboxylate (3:2)    |
| 9-Amino-8-fluoro-1,2,3,4-tetrahydro-2,4-methanoacridine                                                  |
| 9-Amino-8-fluoro-1,2,3,4-tetrahydro-2,4-methanoacridine                                                  |
| 2,4-Methanoadamantane                                                                                |
| 2,4-Methanoadamantane                                                                                |
| 2-Amino-4,5-methanoadipate                                                                               |
| 1,4-Methanoanthra(2,3-c)oxepin-7,12-dione, 1,3,4,5-tetrahydro-4,6,13-trihydroxy-3,11-dimethoxy-3-methyl- |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4-tetrahydro-                                                    |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4-tetrahydro-                                                    |
| 1,4-Methanoanthracene-9,10-dione, 1,2,3,4,4a,9a-hexahydro-                                               |
+----------------------------------------------------------------------------------------------------------+
10 rows in set (0.13 sec)

So speed is good, but results are terrible

My question - how to do a fast search that returns similar to the like query, but nearer to the speed of the fulltext one?

Body:
(Some random thoughts...)

WHERE MATCH(...) AGAINST(...)
  AND ... LIKE ...

It should filter using FULLTEXT first, then further filter via LIKE.

But... I am puzzled by your current code.  The first example (using instr) tends to pick data starting with "Methan".  That can be much more efficiently performed with

AgentReferenceName LIKE 'Methan%'

assuming you have INDEX(AgentReferenceName).  IfAgentReferenceNameisTEXTand notVARCHAR`, then consider an extra column with just short names indexed.

Then consider

( SELECT ... WHERE ... LIKE 'Methan%' ... LIMIT 10 )
UNION DISTINCT
( SELECT ... WHERE MATCH ... LIMIT 10 )

This will give you up to 20 rows for further sorting (and whittling down to 10) -- possibly in app code.


问:
How can i simplify these if-statements?
How can I simplify this and make it still do the same thing?

```<code>package test;

import java.util.Scanner;

public class HI {public static void main(String[] args) {
    String Welcome1 = "Welcome";
    String specialWelcome1 = "Welcome Parzival";
    String joinLogin1 = "What would you like to do?";
    System.out.println(Welcome1);
    System.out.println("Insert your name below");
    Scanner scan = new Scanner(System.in);
    String Person = scan.nextLine();
    if (Person.equals("Parzival")) {
        System.out.println(specialWelcome1);
        System.out.println(joinLogin1);
        String doing1 = scan.nextLine();
        if(doing1.equals("Kill")) {
            System.out.println("What is the password?");
            String killCode = scan.nextLine();
            if(killCode.equals("OASIS kill")){
                System.out.println("Shutting down...");
            }
        if(doing1.equals("Join Game")) {
            System.out.println("Joining...");
        }
        }
}else {
            System.out.println(Welcome1 + " " + Person);
}}}
</code>```

The code looks messy and it is hard to read. I don't know how to fix that.

答:
I have not tried to optimize, but just organized with switch to understand easily.

```<code>package test;

import java.util.Scanner;

public class HI {public static void main(String[] args) {
    String Welcome1 = "Welcome", specialWelcome1 = "Welcome Parzival", joinLogin1 = "What would you like to do?";

    System.out.println(Welcome1);
    System.out.println("Insert your name below");

    Scanner scan = new Scanner(System.in);
    String Person = scan.nextLine();

    switch(Person) {
        case "Parzival":
            System.out.println(specialWelcome1);
            System.out.println(joinLogin1);
            switch(scan.nextLine()) {
                case "Kill":
                    System.out.println("What is the password?");
                    if(scan.nextLine().equals("OASIS kill"))
                        System.out.println("Shutting down...");
                    break;
                case "Join Game":
                    System.out.println("Joining..."); break;
            }
            break;
        default:
            System.out.println(Welcome1 + " " + Person);
    }

}
}
</code>```

Title: How can i simplify these if-statements?

Body:
How can I simplify this and make it still do the same thing?

package test;

import java.util.Scanner;

public class HI {public static void main(String[] args) {
    String Welcome1 = "Welcome";
    String specialWelcome1 = "Welcome Parzival";
    String joinLogin1 = "What would you like to do?";
    System.out.println(Welcome1);
    System.out.println("Insert your name below");
    Scanner scan = new Scanner(System.in);
    String Person = scan.nextLine();
    if (Person.equals("Parzival")) {
        System.out.println(specialWelcome1);
        System.out.println(joinLogin1);
        String doing1 = scan.nextLine();
        if(doing1.equals("Kill")) {
            System.out.println("What is the password?");
            String killCode = scan.nextLine();
            if(killCode.equals("OASIS kill")){
                System.out.println("Shutting down...");
            }
        if(doing1.equals("Join Game")) {
            System.out.println("Joining...");
        }
        }
}else {
            System.out.println(Welcome1 + " " + Person);
}}}

The code looks messy and it is hard to read. I don't know how to fix that.

Body:
I have not tried to optimize, but just organized with switch to understand easily.

package test;

import java.util.Scanner;

public class HI {public static void main(String[] args) {
    String Welcome1 = "Welcome", specialWelcome1 = "Welcome Parzival", joinLogin1 = "What would you like to do?";

    System.out.println(Welcome1);
    System.out.println("Insert your name below");

    Scanner scan = new Scanner(System.in);
    String Person = scan.nextLine();

    switch(Person) {
        case "Parzival":
            System.out.println(specialWelcome1);
            System.out.println(joinLogin1);
            switch(scan.nextLine()) {
                case "Kill":
                    System.out.println("What is the password?");
                    if(scan.nextLine().equals("OASIS kill"))
                        System.out.println("Shutting down...");
                    break;
                case "Join Game":
                    System.out.println("Joining..."); break;
            }
            break;
        default:
            System.out.println(Welcome1 + " " + Person);
    }

}
}


问:
Jquery - Store Ajax jSON response as variable
I'm trying to get the result of an ajax request to set in a variable which I can access outside that request. I've tried this JQuery - Storing ajax response into global variable but my variable beer remains undefined outside the $.getJSON and $.ajax functions (I tried both).

Here is my code and where I am able to see the results from the console.log(beer).

```<code>var beer;
$.getJSON(jsonUrl, function (json) {
    beer = json;
    console.log(beer); // returns beer
});
console.log(beer); // returns undefined

var beer = (function () {
    var result;

    $.ajax({
        url: jsonUrl,
        success: function (data) {
            result = data;
            console.log(beer); // returns beer

        }
    });
    console.log(result); // returns undefined
    if (result) return result;
})();
console.log(beer); // returns undefined
</code>```

答:
That's an asynchronous request, so it gets fired off, but your script doesn't wait around for a response before it moves on.  If you need to wait on a ajax request to finish, try something like this:</p>

```<code>var beer;
$.getJSON(jsonUrl,function(json){
    beer = json;
    checkDrink();
});

function checkDrink() {
    console.log(beer);
}
</code>```

Body:
I'm trying to get the result of an ajax request to set in a variable which I can access outside that request. I've tried this JQuery - Storing ajax response into global variable but my variable beer remains undefined outside the $.getJSON and $.ajax functions (I tried both).

Here is my code and where I am able to see the results from the console.log(beer).

var beer;
$.getJSON(jsonUrl, function (json) {
    beer = json;
    console.log(beer); // returns beer
});
console.log(beer); // returns undefined

var beer = (function () {
    var result;

    $.ajax({
        url: jsonUrl,
        success: function (data) {
            result = data;
            console.log(beer); // returns beer

        }
    });
    console.log(result); // returns undefined
    if (result) return result;
})();
console.log(beer); // returns undefined

Body:
That's an asynchronous request, so it gets fired off, but your script doesn't wait around for a response before it moves on.  If you need to wait on a ajax request to finish, try something like this:

var beer;
$.getJSON(jsonUrl,function(json){
    beer = json;
    checkDrink();
});

function checkDrink() {
    console.log(beer);
}


问:
iPython does not read ~/.inputrc
I am using iPython. The docs says that I should be able to remap the readline library's keys using inputrc. Here is what I have in my inputrc:

```<code>set editing-mode emacs
set keymap emacs
Meta-h: backward-word
Meta-s: forward-word
Control-h: backward-char
Control-s: forward-char
Control-n: previous-history
Control-t: next-history
Control-p: yank
Meta-p: yank-pop
</code>```

These mappings simply do not work when I load iPython. I'm on OS X 10.9 Mavericks. I do not see any warnings that libedit is being used instead of readline. Any ideas?

答:
The method I found was to create a new IPython profile with the
vi-keys option enabled.

Source: Options Reference

Source: Managing Profiles

Set your keybinding mode to vi:

Generate blank config file:

```<code>ipython profile create [profile-name]
</code>```

Running the command should show the path of the generated profiles,
which are python (.py) files.

From: Source: Options Reference

Starting with 5.0, IPython uses prompt_toolkit in place of readline,
it thus can recognize lines ending in ‘:’ and indent the next line,
while also un-indenting automatically after ‘raise’ or ‘return’, and
support real multi-line editing as well as syntactic coloration
during edition.

This feature does not use the readline library anymore, so it will
not honor your ~/.inputrc configuration (or whatever file your
INPUTRC environment variable points to).

In particular if you want to change the input mode to vi, you will
need to set the TerminalInteractiveShell.editing_mode configuration
option of IPython.

(emphasis mine)

So, navigate to the ipython_config.py file, and make sure the
following lines are in it:

```<code>c = get_config()
c.TerminalInteractiveShell.editing_mode = 'vi'
</code>```

Start IPython with a particular profile:

Source: Managing Profiles

At a terminal, type in the following command (don't type the braces
literally, they're just a placeholder for the actual name of the
profile).

$> ipython --profile={profile-name}

Title: iPython does not read ~/.inputrc

Body:
I am using iPython. The docs says that I should be able to remap the readline library's keys using inputrc. Here is what I have in my inputrc:

set editing-mode emacs
set keymap emacs
Meta-h: backward-word
Meta-s: forward-word
Control-h: backward-char
Control-s: forward-char
Control-n: previous-history
Control-t: next-history
Control-p: yank
Meta-p: yank-pop

These mappings simply do not work when I load iPython. I'm on OS X 10.9 Mavericks. I do not see any warnings that libedit is being used instead of readline. Any ideas?

Body:
The method I found was to create a new IPython profile with the
vi-keys option enabled.

Source: Options Reference

Source: Managing Profiles

Set your keybinding mode to vi:

Generate blank config file:

ipython profile create [profile-name]

Running the command should show the path of the generated profiles,
which are python (.py) files.

From: Source: Options Reference

Starting with 5.0, IPython uses prompt_toolkit in place of readline,
it thus can recognize lines ending in ‘:’ and indent the next line,
while also un-indenting automatically after ‘raise’ or ‘return’, and
support real multi-line editing as well as syntactic coloration
during edition.

This feature does not use the readline library anymore, so it will
not honor your ~/.inputrc configuration (or whatever file your
INPUTRC environment variable points to).

In particular if you want to change the input mode to vi, you will
need to set the TerminalInteractiveShell.editing_mode configuration
option of IPython.

(emphasis mine)

So, navigate to the ipython_config.py file, and make sure the
following lines are in it:

c = get_config()
c.TerminalInteractiveShell.editing_mode = 'vi'

Start IPython with a particular profile:

Source: Managing Profiles

At a terminal, type in the following command (don't type the braces
literally, they're just a placeholder for the actual name of the
profile).

$> ipython --profile={profile-name}

ContentLicense: CC BY-SA 4.0


问:
How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
I have some code that uses JAXB API classes which have been provided as a part of the JDK in Java 6/7/8.  When I run the same code with Java 9, at runtime I get errors indicating that JAXB classes can not be found.

The JAXB classes have been provided as a part of the JDK since Java 6, so why can Java 9 no longer find these classes?

答:
This worked for me. Adding only jaxb-api wasn't enough.</p>

```<code>        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>${jaxb-api.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>${jaxb-api.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>${jaxb-api.version}</version>
        </dependency>
</code>```

Body:
This worked for me. Adding only jaxb-api wasn't enough.

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>${jaxb-api.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>${jaxb-api.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>${jaxb-api.version}</version>
        </dependency>


问:
How to vertically align elements with horizontal overflow
I want to be able to create a div with a set size (in this example 100x100).

Then i want to be able to add x number of elements inside the div, in this example we can say 10 buttons with the size of 10x10 and align them vertically.

This means all buttons should be in a single column.

Then if i resize and make the new size 80x80 i should have 2 columns, the first with the first 8 buttons and then a new columns with the last 2 buttons.

I have tried with

```<code>flex-wrap: wrap;
display: flex;
flex-direction: column;
align-content: flex-start;
</code>```

It aligns vertically but then when i resize the buttons keeps going over the bottom.

How can i align all elements so they are aligned vertically but if the height are not enought it should overflow into a new column. So no set number of columns since it could be x number of columns depending on the size.

Is this possible using css?

答:
I think it only works when you give the container a maximum height. Is this what you need?

.container {
  flex-wrap: wrap;
  display: flex;
  flex-direction: column;
  align-content: flex-start;
  max-height: 100px;
}

.button {
  width: 100px;
  height: 10px;
  border: solid thin black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
</div></code>```

Body:
I want to be able to create a div with a set size (in this example 100x100).

Then i want to be able to add x number of elements inside the div, in this example we can say 10 buttons with the size of 10x10 and align them vertically.

This means all buttons should be in a single column.

Then if i resize and make the new size 80x80 i should have 2 columns, the first with the first 8 buttons and then a new columns with the last 2 buttons.

I have tried with

flex-wrap: wrap;
display: flex;
flex-direction: column;
align-content: flex-start;

It aligns vertically but then when i resize the buttons keeps going over the bottom.

How can i align all elements so they are aligned vertically but if the height are not enought it should overflow into a new column. So no set number of columns since it could be x number of columns depending on the size.

Is this possible using css?

Body:
I think it only works when you give the container a maximum height. Is this what you need?

.container {
  flex-wrap: wrap;
  display: flex;
  flex-direction: column;
  align-content: flex-start;
  max-height: 100px;
}

.button {
  width: 100px;
  height: 10px;
  border: solid thin black;
}

<div class="container">
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
  <div class="button"></div>
</div>


问:
Odoo 10 - Disable default "My opportunities" filter in CRM
When user checks sales flow (opportunities) in Odoo 10 CRM module, the "My opportunities" filter is enabled by default.

Is it possible to configure behaviour so user has no such filter and he/she sees all opportunities?

Thanks

答:
You are overwriting the context of the crm_lead_opportunities_tree_view action to remove the default search filter. So we still are using that particular action to land on the crm opportunity tree view, but with our customized context.

And, actually, I forgot to add 'default_user_id' and 'default_type'.
This should work.

<record model="ir.actions.act_window" id="crm.crm_lead_opportunities_tree_view">
    <field name="context">{
        'search_default_assigned_to_me': 0,
        'default_type': 'opportunity',
        'default_user_id': uid
    }</field>
</record>


问:
Calling method in generic class through reflection
I am attempting to setup a function taking in a generic class that in turn calls a method within that class through reflection. Below code compiles, however when I run it I get this error:

```<code>java.lang.IllegalArgumentException: Callable expects 2 arguments, but 1 were provided.
</code>```

Why does Kotlin claim there should be 2 arguments, when the method only takes one? What should the arguments be?

```<code>import kotlin.reflect.full.memberFunctions

class myClass {
    fun test(d: String) : String {
        return d
    }
}

class test {

    fun <T: Any>ProcessStuff(
        d : T
    ) {
        val myClass  = d.let { it::class }

        var f3 = myClass.memberFunctions.find { it.name == "test"}!!
        println (f3.call ("Hello World"))
    }
}

fun main(args : Array<String>) {
    val c = myClass()
    val t = test()
    t.ProcessStuff(c)
}
</code>```

答:
You're not calling the method on an instance (first argument). It works like this:</p>

```<code>val myClassInstance = myClass()
println(f3.call(myClassInstance, "Hello World"))
</code>```

Body:
I am attempting to setup a function taking in a generic class that in turn calls a method within that class through reflection. Below code compiles, however when I run it I get this error:

java.lang.IllegalArgumentException: Callable expects 2 arguments, but 1 were provided.

Why does Kotlin claim there should be 2 arguments, when the method only takes one? What should the arguments be?

import kotlin.reflect.full.memberFunctions

class myClass {
    fun test(d: String) : String {
        return d
    }
}

class test {

    fun <T: Any>ProcessStuff(
        d : T
    ) {
        val myClass  = d.let { it::class }

        var f3 = myClass.memberFunctions.find { it.name == "test"}!!
        println (f3.call ("Hello World"))
    }
}

fun main(args : Array<String>) {
    val c = myClass()
    val t = test()
    t.ProcessStuff(c)
}

Body:
You're not calling the method on an instance (first argument). It works like this:

val myClassInstance = myClass()
println(f3.call(myClassInstance, "Hello World"))


问:
Best way to copy multi module project in maven
I have a maven project in which I would like to unpack all the child modules of a mutli module project. Does anyone know if the best way to approach this? There are over 100 modules in this project and I'm trying to avoid having to copy all this information somewhere else.</p>

答:
First you will need to create a pom.xml file that has all the projects as dependencies.

If there is one submodule that has
all other submodules as
dependencies, then you are in luck, just add a dependency to that submodule.

If not, you will have to write a script or program that gathers the groupIds, artifactIds, versions (and packagings) of all the submodules. And creates a pom.xml with all of them as dependencies.

Then, in this project, you can use dependency:unpack-dependencies to unpack the projects:

```<code><plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <executions>
     <execution>
        <id>unpack-projects</id>
        <phase>generate-sources</phase>
        <goals>
          <goal>unpack-dependencies</goal>
        </goals>
        <configuration>
          <includeGroupIds>com.basegroupId*</includeGroupIds>
        </configuration>
     </execution>
  </executions>
</plugin>
</code>```

(Set includeGroupIds to a pattern that matches all submodule groupIds)

Now you just have to call

```<code>mvn generate-sources
</code>```

(or any other phase you configure in the execution)

Body:
First you will need to create a pom.xml file that has all the projects as dependencies.

If there is one submodule that has
all other submodules as
dependencies, then you are in luck, just add a dependency to that submodule.

If not, you will have to write a script or program that gathers the groupIds, artifactIds, versions (and packagings) of all the submodules. And creates a pom.xml with all of them as dependencies.

Then, in this project, you can use dependency:unpack-dependencies to unpack the projects:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <executions>
     <execution>
        <id>unpack-projects</id>
        <phase>generate-sources</phase>
        <goals>
          <goal>unpack-dependencies</goal>
        </goals>
        <configuration>
          <includeGroupIds>com.basegroupId*</includeGroupIds>
        </configuration>
     </execution>
  </executions>
</plugin>

(Set includeGroupIds to a pattern that matches all submodule groupIds)

Now you just have to call

mvn generate-sources

(or any other phase you configure in the execution)


问:
How to import all databases at a time in wamp
I export whole databases sql file from localhost wamp. Now I want to import all databases and table by importing that one sql file. But I get sql error...database error with name...and following error. Plz give me solution for this.

MySQL said:

```<code>#1046 - No database was selected
</code>```

答:
1046 - No database was selected

This error suggests that when you dumped all these database the resulting .sql file does not contain the required use databasename; between each database restore.

You will have to edit the .sql file and add a use databasename; statement for each database, just before the restore changes the database it is restoring.

Body:
I export whole databases sql file from localhost wamp. Now I want to import all databases and table by importing that one sql file. But I get sql error...database error with name...and following error. Plz give me solution for this.

MySQL said:

#1046 - No database was selected


问:
Understanding Generics and Reflection in Java to Make Array Generic
I am trying to model a train with a Java program.

Currently I have four classes:

Train,

BoxCar,

Cargo,

Person.

The BoxCar class has an array of Person and an array of Cargo. A BoxCar can only hold one type so when that type is given from the constructor,

I decide which array to use (either the people array or the cargo array). The thing is, I'd like to make that array inside BoxCar "generic" so that if there is another "kind" of type the user wants to use, it can be easily set.
They wouldn't need to declare another array inside the BoxCar class for that type and change the rest of the code.

How would I do this? I looked up Generic and Reflection but the examples I saw weren't exactly for my scenario and I'm learning this for the first time.
Can someone map out the right approach to take?

BoxCar:

```<code>class BoxCar {
    String boxType;
    int boxID;
    int count;
    boolean isEmpty;
    Cargo cargo[];
    Person people[];
    int capacity;

    BoxCar(String box_type, int ID, int cap) {
        boxType = box_type;
        boxID = ID;
        isEmpty = true;
        count = 0;
        capacity = cap;
    }
}
</code>```

Person:

```<code>class Person {
    String government_ID, name;
    int age;

    Person(String gov_ID, String Name, int Age) {
        government_ID = gov_ID;
        name = Name;
        age = Age;
    }
}
</code>```

Cargo:

```<code>class Cargo {
    String cargo_ID;
    int height, weight;

    Cargo(String c_id, int w, int h) {
        cargo_ID = c_id;
        height = h;
        weight = w;
    }
}
</code>```

答:
The best way to accomplish that is using generics.

Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow “a type or method to operate on objects of various types while providing compile-time type safety”

https://en.wikipedia.org/wiki/Generics_in_Java

The generic E allows passing a type according to your needs.

```<code>class BoxCar<E> {
    private int boxID;
    private int count;
    private boolean isEmpty;
    private E target[];
    private int capacity;

    public BoxCar(int ID, int cap) {
        boxID = ID;
        isEmpty = true;
        count = 0;
        capacity = cap;
    }

    public setTarget(E target[]) {
        thid.target = target;
    }
}
</code>```

Another approach is to use interfaces, for example this could be a solution:

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

https://docs.oracle.com/javase/tutorial/java/concepts/interface.html

```<code>import java.util.HashMap;
import java.util.Map;

public class A {
    public static void main(String[] args) {
        BoxCar<String, String> boxCar_1 = new BoxCar<>(new Person("gov_id", "name", 35), 1, 1);
        BoxCar<String, String> boxCar_2 = new BoxCar<>(new Cargo("c_id", 1, 1), 1, 1);
    }
}

/**
 * This interface declares the
 * methods for box targets.
 *
 * @param <T> for jey
 * @param <E> for value
 */
interface BoxCarTarget<T, E> {
    /**
     * This method returns the data regarding to
     * a specific BoxCar target.
     *
     * @return Map with specific data.
     */
    Map<T, E> getPayload();
}

class BoxCar<T, E> {
    private BoxCarTarget<T, E> target;
    private int boxID;
    private int count;
    private boolean isEmpty;
    private int capacity;

    BoxCar(BoxCarTarget<T, E> target, int ID, int cap) {
        this.target = target;
        boxID = ID;
        isEmpty = true;
        count = 0;
        capacity = cap;

        /*
         * Here you can handle the payload.
         * I think we can use reflection for
         * extracting data.
         */
        Map<T, E> payload = this.target.getPayload();
    }
}

/**
 * Class person
 */
class Person implements BoxCarTarget<String, String> {
    private String government_ID, name;
    private int age;

    Person(String gov_ID, String Name, int Age) {
        government_ID = gov_ID;
        name = Name;
        age = Age;
    }

   /**
    * This method returns the data regarding to
    * a specific BoxCar target.
    *
    * @return Map with specific data.
    */
    @Override
    public Map<String, String> getPayload() {
        Map<String, String> payload = new HashMap<>();
        payload.put("government_ID", government_ID);
        payload.put("name", name);
        payload.put("age", String.valueOf(age));

        return payload;
    }
}

/**
 * Class Cargo
 */
class Cargo implements BoxCarTarget<String, String> {
    private String cargo_ID;
    private int height, weight;

    Cargo(String c_id, int w, int h) {
        cargo_ID = c_id;
        height = h;
        weight = w;
    }

   /**
    * This method returns the data regarding to
    * a specific BoxCar target.
    *
    * @return Map with specific data.
    */
    @Override
    public Map<String, String> getPayload() {
        Map<String, String> payload = new HashMap<>();
        payload.put("cargo_ID", String.valueOf(cargo_ID));
        payload.put("height", String.valueOf(height));
        payload.put("weight", String.valueOf(weight));

        return payload;
    }
}
</code>```

Hope this helps!

Body:
I am trying to model a train with a Java program.

Currently I have four classes:

Train,

BoxCar,

Cargo,

Person.

The BoxCar class has an array of Person and an array of Cargo. A BoxCar can only hold one type so when that type is given from the constructor,

I decide which array to use (either the people array or the cargo array). The thing is, I'd like to make that array inside BoxCar "generic" so that if there is another "kind" of type the user wants to use, it can be easily set.
They wouldn't need to declare another array inside the BoxCar class for that type and change the rest of the code.

How would I do this? I looked up Generic and Reflection but the examples I saw weren't exactly for my scenario and I'm learning this for the first time.
Can someone map out the right approach to take?

BoxCar:

class BoxCar {
    String boxType;
    int boxID;
    int count;
    boolean isEmpty;
    Cargo cargo[];
    Person people[];
    int capacity;

    BoxCar(String box_type, int ID, int cap) {
        boxType = box_type;
        boxID = ID;
        isEmpty = true;
        count = 0;
        capacity = cap;
    }
}

Person:

class Person {
    String government_ID, name;
    int age;

    Person(String gov_ID, String Name, int Age) {
        government_ID = gov_ID;
        name = Name;
        age = Age;
    }
}

Cargo:

class Cargo {
    String cargo_ID;
    int height, weight;

    Cargo(String c_id, int w, int h) {
        cargo_ID = c_id;
        height = h;
        weight = w;
    }
}

Body:
The best way to accomplish that is using generics.

Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow “a type or method to operate on objects of various types while providing compile-time type safety”

https://en.wikipedia.org/wiki/Generics_in_Java

The generic E allows passing a type according to your needs.

class BoxCar<E> {
    private int boxID;
    private int count;
    private boolean isEmpty;
    private E target[];
    private int capacity;

    public BoxCar(int ID, int cap) {
        boxID = ID;
        isEmpty = true;
        count = 0;
        capacity = cap;
    }

    public setTarget(E target[]) {
        thid.target = target;
    }
}

Another approach is to use interfaces, for example this could be a solution:

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

https://docs.oracle.com/javase/tutorial/java/concepts/interface.html

import java.util.HashMap;
import java.util.Map;

public class A {
    public static void main(String[] args) {
        BoxCar<String, String> boxCar_1 = new BoxCar<>(new Person("gov_id", "name", 35), 1, 1);
        BoxCar<String, String> boxCar_2 = new BoxCar<>(new Cargo("c_id", 1, 1), 1, 1);
    }
}

/**
 * This interface declares the
 * methods for box targets.
 *
 * @param <T> for jey
 * @param <E> for value
 */
interface BoxCarTarget<T, E> {
    /**
     * This method returns the data regarding to
     * a specific BoxCar target.
     *
     * @return Map with specific data.
     */
    Map<T, E> getPayload();
}

class BoxCar<T, E> {
    private BoxCarTarget<T, E> target;
    private int boxID;
    private int count;
    private boolean isEmpty;
    private int capacity;

    BoxCar(BoxCarTarget<T, E> target, int ID, int cap) {
        this.target = target;
        boxID = ID;
        isEmpty = true;
        count = 0;
        capacity = cap;

        /*
         * Here you can handle the payload.
         * I think we can use reflection for
         * extracting data.
         */
        Map<T, E> payload = this.target.getPayload();
    }
}

/**
 * Class person
 */
class Person implements BoxCarTarget<String, String> {
    private String government_ID, name;
    private int age;

    Person(String gov_ID, String Name, int Age) {
        government_ID = gov_ID;
        name = Name;
        age = Age;
    }

   /**
    * This method returns the data regarding to
    * a specific BoxCar target.
    *
    * @return Map with specific data.
    */
    @Override
    public Map<String, String> getPayload() {
        Map<String, String> payload = new HashMap<>();
        payload.put("government_ID", government_ID);
        payload.put("name", name);
        payload.put("age", String.valueOf(age));

        return payload;
    }
}

/**
 * Class Cargo
 */
class Cargo implements BoxCarTarget<String, String> {
    private String cargo_ID;
    private int height, weight;

    Cargo(String c_id, int w, int h) {
        cargo_ID = c_id;
        height = h;
        weight = w;
    }

   /**
    * This method returns the data regarding to
    * a specific BoxCar target.
    *
    * @return Map with specific data.
    */
    @Override
    public Map<String, String> getPayload() {
        Map<String, String> payload = new HashMap<>();
        payload.put("cargo_ID", String.valueOf(cargo_ID));
        payload.put("height", String.valueOf(height));
        payload.put("weight", String.valueOf(weight));

        return payload;
    }
}

Hope this helps!


问:
Tick marks misaligned with panel in ggplot2 [R]
There always seems to be some small but noticeable offset between where tick marks end and where the panel starts.

This is more evident when axis limits are specified so that the axis ends on a tick (see above). e.g., On the y-axis, the highest tick is too high and the lowest tick is too low.

Code to reproduce:

```<code>library(ggplot2)
p <-
  ggplot(mtcars,aes(mpg, wt)) +
    geom_point() +
    scale_y_continuous(limits=c(1,5), expand=c(0,0))

p <- p + theme_few()
p <- p + theme(axis.ticks=element_line(size=0.5),axis.ticks.length = unit(0.5, "cm")) # enlarged for clarity, although this happens regardless
</code>```

How can I fix this?

Edit:

In using the accepted answer on my own data, I noticed this also changes how points at the axis extrema are clipped. Is there any way to correctly align ticks and the panel, but not change this behavior? I don't want to remove the points, just still hide the portions outside the panel.

答:
it's not the position that's off, but the panel border that is being clipped,

```<code>library(ggplot2)
p <- ggplot(mtcars,aes(mpg, wt)) + geom_point() + scale_y_continuous(limits=c(1,5),expand=c(0,0))
p <- p + theme_bw()
p <- p + theme(axis.ticks=element_line(size=3),
               panel.border = element_rect(size = 3),
               axis.ticks.length = unit(0.5, "cm"))

g <- ggplotGrob(p)

g$layout$clip <- "off"
library(gridExtra)
grid.arrange(p, g, ncol=2)
</code>```

Edit: The above observation wasn't meant to be a solution; as noted in the comments turning off the clipping for the whole panel is problematic for the points that leak out of the panel area. A possible workaround is to add a new grob to the gtable, e.g. by extracting it from panel and adding it on top without clipping.

```<code>library(ggplot2)
p <- ggplot(mtcars,aes(mpg, wt)) + geom_point(size=20) + scale_y_continuous(limits=c(1,5),expand=c(0,0))
p <- p + theme_bw()
p <- p + theme(axis.ticks=element_line(size=2),
               panel.border = element_rect(size = 2),
               axis.ticks.length = unit(0.5, "cm"))

g <- ggplotGrob(p)
panel_id <- g$layout$name == "panel"
border <- tail(g$grobs[panel_id][[1]][["children"]], 1)
g <- gtable::gtable_add_grob(g, border,
                             t = min(g$layout$t[panel_id]),
                             l = min(g$layout$l[panel_id]),
                             name = "border",
                             clip = "off")

library(gridExtra)
grid.arrange(p, g, ncol=2)
</code>```

Body:
There always seems to be some small but noticeable offset between where tick marks end and where the panel starts.

This is more evident when axis limits are specified so that the axis ends on a tick (see above). e.g., On the y-axis, the highest tick is too high and the lowest tick is too low.

Code to reproduce:

library(ggplot2)
p <-
  ggplot(mtcars,aes(mpg, wt)) +
    geom_point() +
    scale_y_continuous(limits=c(1,5), expand=c(0,0))

p <- p + theme_few()
p <- p + theme(axis.ticks=element_line(size=0.5),axis.ticks.length = unit(0.5, "cm")) # enlarged for clarity, although this happens regardless

How can I fix this?

Edit:

In using the accepted answer on my own data, I noticed this also changes how points at the axis extrema are clipped. Is there any way to correctly align ticks and the panel, but not change this behavior? I don't want to remove the points, just still hide the portions outside the panel.

Body:
it's not the position that's off, but the panel border that is being clipped,

library(ggplot2)
p <- ggplot(mtcars,aes(mpg, wt)) + geom_point() + scale_y_continuous(limits=c(1,5),expand=c(0,0))
p <- p + theme_bw()
p <- p + theme(axis.ticks=element_line(size=3),
               panel.border = element_rect(size = 3),
               axis.ticks.length = unit(0.5, "cm"))

g <- ggplotGrob(p)

g$layout$clip <- "off"
library(gridExtra)
grid.arrange(p, g, ncol=2)

Edit: The above observation wasn't meant to be a solution; as noted in the comments turning off the clipping for the whole panel is problematic for the points that leak out of the panel area. A possible workaround is to add a new grob to the gtable, e.g. by extracting it from panel and adding it on top without clipping.

library(ggplot2)
p <- ggplot(mtcars,aes(mpg, wt)) + geom_point(size=20) + scale_y_continuous(limits=c(1,5),expand=c(0,0))
p <- p + theme_bw()
p <- p + theme(axis.ticks=element_line(size=2),
               panel.border = element_rect(size = 2),
               axis.ticks.length = unit(0.5, "cm"))

g <- ggplotGrob(p)
panel_id <- g$layout$name == "panel"
border <- tail(g$grobs[panel_id][[1]][["children"]], 1)
g <- gtable::gtable_add_grob(g, border,
                             t = min(g$layout$t[panel_id]),
                             l = min(g$layout$l[panel_id]),
                             name = "border",
                             clip = "off")

library(gridExtra)
grid.arrange(p, g, ncol=2)


问:
How do I wrap till a predefined parent for multiple elements in cheerio or jquery?
I've got a similar xml:

```<code><document>
   <paragraph>
      <a>
         <b>
            <c>
               <d>text1</d>
            </c>
         </b>
      </a>
   </paragraph>
   <paragraph>
      <a>
         <b>
            <c>
               <d>text2</d>
            </c>
         </b>
      </a>
   </paragraph>
</document>
</code>```

There's obviously more paragraphs, etc.

Using cheerio (jquery's syntax applies too) I want to wrap the d element till it has only paragraph as parent.

```<code><document>
   <paragraph>
       <d>text1</d>
   </paragraph>
   <paragraph>
       <d>text2</d>
   </paragraph>
</document>
</code>```

I thought about using the .unwrap() command 3 times on the element. But I have no guarantee that in some xml between d and paragraph I may have a smaller or bigger number of parents.

答:
Here is my solution DEMO. I used for loop to clone the <d> element and then rewrite it into the paragraph element.

JS

```<code>$(document).ready(function(){
  var i = $('d').length;
  for(x=i--;x>=0;x--){
    var c = $('d').eq(x).clone();
    $('d').eq(x).parents('paragraph').html(c);
  }
});
</code>```

Body:
I've got a similar xml:

<document>
   <paragraph>

            <c>
               <d>text1</d>
            </c>

   </paragraph>
   <paragraph>

            <c>
               <d>text2</d>
            </c>

   </paragraph>
</document>

There's obviously more paragraphs, etc.

Using cheerio (jquery's syntax applies too) I want to wrap the d element till it has only paragraph as parent.

<document>
   <paragraph>
       <d>text1</d>
   </paragraph>
   <paragraph>
       <d>text2</d>
   </paragraph>
</document>

I thought about using the .unwrap() command 3 times on the element. But I have no guarantee that in some xml between d and paragraph I may have a smaller or bigger number of parents.

Body:
Here is my solution DEMO. I used for loop to clone the <d> element and then rewrite it into the paragraph element.

JS

$(document).ready(function(){
  var i = $('d').length;
  for(x=i--;x>=0;x--){
    var c = $('d').eq(x).clone();
    $('d').eq(x).parents('paragraph').html(c);
  }
});


答:
Not sure if this will work in your environment, but, i think you could use idea:

```<code>$('d').each(function() {
cloned=$(this).clone();

$(this).closest('paragraph').append(cloned);
$(this).parentsUntil($('paragraph')).remove();

});
</code>```

So, clone element, place it inside paragraph, remove all parentsUntil() paragraph...

Demo:

$('d').each(function() {
cloned=$(this).clone();

$(this).closest('paragraph').append(cloned);
$(this).parentsUntil($('paragraph')).remove();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<document>
   <paragraph>
      <a>
         <b>
            <c>
               <d>text1</d>
            </c>
         </b>
      </a>
   </paragraph>
   <paragraph>
      <a>
         <b>
            <c>
               <d>text2</d>
            </c>
         </b>
      </a>
   </paragraph>
</document></code>```

Title: How do I wrap till a predefined parent for multiple elements in cheerio or jquery?

Body:
Not sure if this will work in your environment, but, i think you could use idea:

$('d').each(function() {
cloned=$(this).clone();

$(this).closest('paragraph').append(cloned);
$(this).parentsUntil($('paragraph')).remove();

});

So, clone element, place it inside paragraph, remove all parentsUntil() paragraph...

Demo:

$('d').each(function() {
cloned=$(this).clone();

$(this).closest('paragraph').append(cloned);
$(this).parentsUntil($('paragraph')).remove();

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<document>
   <paragraph>
      <a>
         <b>
            <c>
               <d>text1</d>
            </c>
         </b>
      </a>
   </paragraph>
   <paragraph>
      <a>
         <b>
            <c>
               <d>text2</d>
            </c>
         </b>
      </a>
   </paragraph>
</document>


问:
Making John, john and JOHN mean the same variable in python lists?
My question is this.

How do I make it so users can not make a new user_name John if JOHN or john are already in use.

Can I make user_name.upper() = user_name.lower() or something like that.

These names are been iterated through a loop of current_users. I want the loop to detect current users and disallow the use of a name if it has already been used in its upper() or title() forms.

Edit: If possible could I get the most 'pythonic' way of doing this. Thanks.

答:
You can use a list comprehension if you do not need to loop through the current_users for anything else:

```<code>if user_name.lower() in [user.lower() for user in current_users]:
    # user_name already taken
</code>```

This would be the same as doing:

```<code>lower_current_users = list()
for user in current_users:
    lower_current_users.append(user.lower())

if user_name.lower() in lower_current_users:
    # user_name already taken
</code>```

As you can see, a list comprehension requires fewer lines of code and is very useful for this type of thing.

Alternatively, a normal for loop can be used if you need to check more than one thing:

```<code>for user in current_users:
    if user_name.lower() == user.lower():
        # user_name already taken
</code>```

Body:
You can use a list comprehension if you do not need to loop through the current_users for anything else:

if user_name.lower() in [user.lower() for user in current_users]:
    # user_name already taken

This would be the same as doing:

lower_current_users = list()
for user in current_users:
    lower_current_users.append(user.lower())

if user_name.lower() in lower_current_users:
    # user_name already taken

As you can see, a list comprehension requires fewer lines of code and is very useful for this type of thing.

Alternatively, a normal for loop can be used if you need to check more than one thing:

for user in current_users:
    if user_name.lower() == user.lower():
        # user_name already taken


问:
Upgrade from Spring Boot 1.3 to Spring Boot 1.4 and Pageable is not working as expected.
I am converting an existing Spring Boot application from 1.3.6 to 1.4.1. I would like to have a default page size for repository and controller responses of 25.  I am not getting the expected behavior in either case. For repository methods I am getting a page size of 20.  For controllers I am getting 0 for the page size.

I added a new configuration class to define the default page size.  I found this code snippet in another article.  The debug message does get printed out.

```<code>@Configuration
public class RestConfigurationAdapter extends WebMvcConfigurerAdapter {

    private static final int DEFAULT_PAGE_SIZE = 25;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        System.out.println("DEBUG: AddArguments----");
        PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
        resolver.setFallbackPageable(new PageRequest(0, DEFAULT_PAGE_SIZE));
        argumentResolvers.add(resolver);
        super.addArgumentResolvers(argumentResolvers);
    }

}
</code>```

In a custom controller I would like to have a default pageable populated with a size of 25.  However the pageable object is null in this controller.  In 1.3.x the pageable object worked as expected.

```<code>public class BatchManagerController
{
    @Autowired
    private BatchRepository batchRepository;

    @Autowired
    private PagedResourcesAssembler pagedResourcesAssembler;

    @Transactional(readOnly = true)
    @RequestMapping(value = "/search/managerBatchView", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("hasRole(T(com.nextgearcapital.tms.api.util.AuthorityEnum).MANAGER)")
    public ResponseEntity<?> getManagerBatchListView(BatchListSearchRequest requestDTO, Pageable pageable, PersistentEntityResourceAssembler myAssembler)
    {
        System.out.println("DEBUG1:---------- " + pageable);
        Page<Batch> batchPage = batchRepository.findBatchesForManager(requestDTO, pageable);
        PagedResources<VaultResource> pagedResources = pagedResourcesAssembler.toResource(batchPage, myAssembler);
        return new ResponseEntity<>(pagedResources, HttpStatus.OK);
    }
}
</code>```

When calling SDR Repository methods with a pageable parameter, the parameter works correctly, but it has a default page size of 20, rather than 25.

I would appreciate any help and advise in getting the correct configuration for pagination.

答:
Starting in spring-data-commons version 2.0, there is are 2 new classes that might make this kind of thing easier:

SortHandlerMethodArgumentResolverCustomizer

PageableHandlerMethodArgumentResolverCustomizer

Unfortunately that's not the version that ships with the current version (1.5.9) of Spring Boot, so replace at your own risk.

```<code>@Bean
PageableHandlerMethodArgumentResolverCustomizer pagingCustomizer() {
    // p is PageableHandlerMethodArgumentResolver
    return p -> p.setMaxPageSize(25);
}
</code>```

In this case, one would probably call resolveArgument to manipulate it.

That said, I'm not sure spring-data-rest would use that config. There is a HateoasPageableHandlerMethodArgumentResolver which seems more likely that source of what I would think SDR would use. If that's the case, the BeanPostProcessor @M. Deinum suggested is probably your best option.

Spring Data Web Support

Body:
I am converting an existing Spring Boot application from 1.3.6 to 1.4.1. I would like to have a default page size for repository and controller responses of 25.  I am not getting the expected behavior in either case. For repository methods I am getting a page size of 20.  For controllers I am getting 0 for the page size.

I added a new configuration class to define the default page size.  I found this code snippet in another article.  The debug message does get printed out.

@Configuration
public class RestConfigurationAdapter extends WebMvcConfigurerAdapter {

    private static final int DEFAULT_PAGE_SIZE = 25;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        System.out.println("DEBUG: AddArguments----");
        PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
        resolver.setFallbackPageable(new PageRequest(0, DEFAULT_PAGE_SIZE));
        argumentResolvers.add(resolver);
        super.addArgumentResolvers(argumentResolvers);
    }

}

In a custom controller I would like to have a default pageable populated with a size of 25.  However the pageable object is null in this controller.  In 1.3.x the pageable object worked as expected.

public class BatchManagerController
{
    @Autowired
    private BatchRepository batchRepository;

    @Autowired
    private PagedResourcesAssembler pagedResourcesAssembler;

    @Transactional(readOnly = true)
    @RequestMapping(value = "/search/managerBatchView", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("hasRole(T(com.nextgearcapital.tms.api.util.AuthorityEnum).MANAGER)")
    public ResponseEntity<?> getManagerBatchListView(BatchListSearchRequest requestDTO, Pageable pageable, PersistentEntityResourceAssembler myAssembler)
    {
        System.out.println("DEBUG1:---------- " + pageable);
        Page<Batch> batchPage = batchRepository.findBatchesForManager(requestDTO, pageable);
        PagedResources<VaultResource> pagedResources = pagedResourcesAssembler.toResource(batchPage, myAssembler);
        return new ResponseEntity<>(pagedResources, HttpStatus.OK);
    }
}

When calling SDR Repository methods with a pageable parameter, the parameter works correctly, but it has a default page size of 20, rather than 25.

I would appreciate any help and advise in getting the correct configuration for pagination.

Body:
Starting in spring-data-commons version 2.0, there is are 2 new classes that might make this kind of thing easier:

SortHandlerMethodArgumentResolverCustomizer

PageableHandlerMethodArgumentResolverCustomizer

Unfortunately that's not the version that ships with the current version (1.5.9) of Spring Boot, so replace at your own risk.

@Bean
PageableHandlerMethodArgumentResolverCustomizer pagingCustomizer() {
    // p is PageableHandlerMethodArgumentResolver
    return p -> p.setMaxPageSize(25);
}

In this case, one would probably call resolveArgument to manipulate it.

That said, I'm not sure spring-data-rest would use that config. There is a HateoasPageableHandlerMethodArgumentResolver which seems more likely that source of what I would think SDR would use. If that's the case, the BeanPostProcessor @M. Deinum suggested is probably your best option.

Spring Data Web Support


问:
Is it possible to align a menu to the right of the menu bar using wxPython?
I'm trying to create a menu bar in wxPython 2.8.11.0 and Python 2.7 where most of the menus are left aligned (as normal) but one is - ideally - right aligned, or at least separated in some way from the rest.

Is this possible?

EDIT: This needs to be a cross-platform solution.

答: If the native menubar doesn't support it, then wxPython probably won't either. There is a pure Python implementation of the menubar though. It's called FlatMenu. I would try that. If it doesn't work, at least you can hack it or submit a patch in Python code rather than trying to figure out the C++ for fixing wxWidgets.</p>