问:
order by one column, But put a specific content at the end
I have multiple columns. Two of them are:

Group (numeric, not unique)
Name (string, not unique)

I would need to order by Group descending, BUT, if the value "Name" equals "Empty" i should be displayed at the end of the Group...

```<code>Group    Name

1020    test1
1020    test2
1020    test3
1020    EMPTY  <-- end of Group 1020
1020    EMPTY  <-- end of Group 1020
3040    test6
3040    test7
3540    test8
3540    EMPTY  <-- end of Group 3540
15060   test9
15060   EMPTY  <-- end of Group 15060
</code>```

How can this be done with a mysql query?

答:
In MySQL, expressions like Name = 'EMPTY' have the value 1 if true and 0 if false.

So you can use

```<code>          ORDER BY Group, Name = 'EMPTY', Name
</code>```

to get all the not-EMPTY values first, then all the EMPTY ones.

Body:
I have multiple columns. Two of them are:

Group (numeric, not unique)
Name (string, not unique)

I would need to order by Group descending, BUT, if the value "Name" equals "Empty" i should be displayed at the end of the Group...

Group    Name

1020    test1
1020    test2
1020    test3
1020    EMPTY  <-- end of Group 1020
1020    EMPTY  <-- end of Group 1020
3040    test6
3040    test7
3540    test8
3540    EMPTY  <-- end of Group 3540
15060   test9
15060   EMPTY  <-- end of Group 15060

How can this be done with a mysql query?

Body:
In MySQL, expressions like Name = 'EMPTY' have the value 1 if true and 0 if false.

So you can use

          ORDER BY Group, Name = 'EMPTY', Name

to get all the not-EMPTY values first, then all the EMPTY ones.


来源: stackexchange

问:
For Each loop ending early and I can't figure out why
I am looking for some help regarding my For Each loop in Excel VBA.

```<code>Set ListofCells = Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!"))

For Each SingleCell In ListofCells

   If ActiveCell.Value = "!!End Measures!!" Then
        ActiveCell.Offset(1, 0).Select
        Exit For
    ElseIf ActiveCell.Value = "" Then
        ActiveCell.EntireRow.Delete
    End If
Next SingleCell
</code>```

For some reason this likes to exit the loop early for, as far as I can tell, absolutely no reason.  In my spreadsheet I'm looking to delete any unused rows from the ActiveCell down to where the entry-area ends, which I have denoted as "!!End Measures!!".  I have also tried:

```<code>Set ListofCells = Range(ActiveCell, ActiveCell.End(xlDown))
</code>```

and it as the same behavior.  Ending the loops many rows earlier than expected.

If I put 4 of these loops in a row then it works as intended....but I'm hoping to find out why this might be exiting early instead of having to do something weird like looping this 4 or 5 times.

Any help is greatly appreciated and if I can answer any questions or provide any more information I'd be happy to.

答:
A couple things catch my attention.

One. It would be good to define what you're looping through.

Two. You're using Activecell in your loop, but I don't think that's what you want to be doing, I think you want SingleCell

Three. Your range is probably getting changed when you delete the row. Since you want no members, it would probably just be easier to restart the loop unless this is taking minutes to run. Consider this:

```<code>Dim ListofCells As Range, SingleCell as Range
StartItUp:
Set ListofCells = Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!"))

For Each SingleCell In ListofCells.Cells

   If SingleCell.Value = "!!End Measures!!" Then
        SingleCell.Offset(1, 0).Select
        Exit For
    ElseIf SingleCell.Value = "" Then
        SingleCell.EntireRow.Delete
        GoTo StartItUp
    End If
Next SingleCell
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am looking for some help regarding my For Each loop in Excel VBA.

Set ListofCells = Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!"))

For Each SingleCell In ListofCells

   If ActiveCell.Value = "!!End Measures!!" Then
        ActiveCell.Offset(1, 0).Select
        Exit For
    ElseIf ActiveCell.Value = "" Then
        ActiveCell.EntireRow.Delete
    End If
Next SingleCell

For some reason this likes to exit the loop early for, as far as I can tell, absolutely no reason.  In my spreadsheet I'm looking to delete any unused rows from the ActiveCell down to where the entry-area ends, which I have denoted as "!!End Measures!!".  I have also tried:

Set ListofCells = Range(ActiveCell, ActiveCell.End(xlDown))

and it as the same behavior.  Ending the loops many rows earlier than expected.

If I put 4 of these loops in a row then it works as intended....but I'm hoping to find out why this might be exiting early instead of having to do something weird like looping this 4 or 5 times.

Any help is greatly appreciated and if I can answer any questions or provide any more information I'd be happy to.

Body:
A couple things catch my attention.

One. It would be good to define what you're looping through.

Two. You're using Activecell in your loop, but I don't think that's what you want to be doing, I think you want SingleCell

Three. Your range is probably getting changed when you delete the row. Since you want no members, it would probably just be easier to restart the loop unless this is taking minutes to run. Consider this:

Dim ListofCells As Range, SingleCell as Range
StartItUp:
Set ListofCells = Range(ActiveCell, Range("C12:C9999").Find("!!End Measures!!"))

For Each SingleCell In ListofCells.Cells

   If SingleCell.Value = "!!End Measures!!" Then
        SingleCell.Offset(1, 0).Select
        Exit For
    ElseIf SingleCell.Value = "" Then
        SingleCell.EntireRow.Delete
        GoTo StartItUp
    End If
Next SingleCell


问:
Get type from property with Roslyn
Using Roslyn I'm trying to interpret some code that looks something like this:

```<code>public class Foo
{
    public override Type BarType
    {
        get { return typeof(MyBar); }
    }
}
</code>```

What I would like to do is get MyBar and then get that type as a symbol, but I'm not sure if this is even something that is possible or practical to do. I'm going to have several classes that look like this and all derive from a base class.

Given the ClassDeclarationSyntax for Foo, I can do this:

```<code>var prop = syntax.DescendantNodes().OfType<PropertyDeclarationSyntax>()
              .FirstOrDefault(p => p.Identifier.ToString() == "BarType");
</code>```

Or given the INamedTypeSymbol for Foo, I can do this:

```<code>var member = symbol.GetMembers("BarType").FirstOrDefault();
</code>```

But I don't know where to go from there.

Ultimately I want to be able to get the symbol for MyBar for further analysis, so maybe even getting the string "MyBar" isn't going to help because it's not fully qualified.

Any suggestions?

EDIT:

I'm getting a project and a compilation like this:

```<code>var workspace = MSBuildWorkspace.Create();
var project = workspace.OpenProjectAsync(projectPath).Result;
var compilation = project.GetCompilationAsync().Result;
</code>```

compilation is a CSharpCompilation here. From there I do something like this:

```<code>foreach (var doc in project.Documents)
{
    Console.WriteLine($"Analyzing {doc.Name}");

    //var model = doc.GetSemanticModelAsync().Result;
    var tree = doc.GetSyntaxTreeAsync().Result;
    var root = tree.GetRoot();
    var model = compilation.GetSemanticModel(tree);
    var classes = root.DescendantNodes().OfType<ClassDeclarationSyntax>();

    foreach (var syntax in classes)
    {
        var symbol = model.GetDeclaredSymbol(syntax);
        //... need to analyze properties in the class here...
    }
}
</code>```

Either way I get model I end up with a SyntaxTreeSemanticModel which doesn't seem to have a GetTypeSymbol method.

答:
You should look for the ReturnStatementSyntax and TypeOfExpressionSyntax. This contains the type MyBar. With the SemanticModel you can get the SymbolInfo like this:

```<code>var classDeclarationSyntaxs = root.DescendantNodes().OfType<ClassDeclarationSyntax>();
foreach ( var classDeclarationSyntax in classDeclarationSyntaxs )
{
    var propertyDeclarationSyntaxs = classDeclarationSyntax.Members.OfType<PropertyDeclarationSyntax>();
    var barTypePropertyDeclarationSyntax = propertyDeclarationSyntaxs.FirstOrDefault( p => p.Identifier.Text == "BarType" );
    if ( barTypePropertyDeclarationSyntax != null )
    {
        var returnStatementSyntax = barTypePropertyDeclarationSyntax.DescendantNodes().OfType<ReturnStatementSyntax>().FirstOrDefault();
        if ( returnStatementSyntax != null )
        {
            var typeOfExpressionSyntax = returnStatementSyntax.ChildNodes().OfType<TypeOfExpressionSyntax>().FirstOrDefault();
            if ( typeOfExpressionSyntax != null )
            {
                var symbolInfo = semanticModel.GetSymbolInfo( typeOfExpressionSyntax.Type );
                var symbolInfoSymbol = symbolInfo.Symbol;
            }
        }
    }
}
</code>```

You can also use a SyntaxWalker for this:

```<code>public class TypeOfSyntaxWalker : CSharpSyntaxWalker
{
    private readonly SemanticModel _semanticModel;

    public ISymbol SymbolInfoSymbol { get; private set; }

    public TypeOfSyntaxWalker( SemanticModel semanticModel )
    {
        _semanticModel = semanticModel;
    }

    public override void VisitTypeOfExpression( TypeOfExpressionSyntax typeOfExpressionSyntax )
    {
        var parent = typeOfExpressionSyntax.Parent;
        if ( parent.Kind() == SyntaxKind.ReturnStatement )
        {
            var propertyDeclarationSyntax = parent.FirstAncestorOrSelf<PropertyDeclarationSyntax>();
            if ( propertyDeclarationSyntax != null &&
                    propertyDeclarationSyntax.Identifier.ValueText == "BarType" )
            {
                var symbolInfo = _semanticModel.GetSymbolInfo( typeOfExpressionSyntax.Type );
                SymbolInfoSymbol = symbolInfo.Symbol;
            }
        }
        base.VisitTypeOfExpression( typeOfExpressionSyntax );
    }
}
</code>```

Usage:

```<code>var classDeclarationSyntaxs = root.DescendantNodes().OfType<ClassDeclarationSyntax>();
foreach ( var classDeclarationSyntax in classDeclarationSyntaxs )
{
    var typeOfSyntaxWalker = new TypeOfSyntaxWalker( semanticModel );
    typeOfSyntaxWalker.VisitClassDeclaration( classDeclarationSyntax );
    var symbolInfoSymbol = typeOfSyntaxWalker.SymbolInfoSymbol;
}
</code>```

Title: Get type from property with Roslyn

Body:
Using Roslyn I'm trying to interpret some code that looks something like this:

public class Foo
{
    public override Type BarType
    {
        get { return typeof(MyBar); }
    }
}

What I would like to do is get MyBar and then get that type as a symbol, but I'm not sure if this is even something that is possible or practical to do. I'm going to have several classes that look like this and all derive from a base class.

Given the ClassDeclarationSyntax for Foo, I can do this:

var prop = syntax.DescendantNodes().OfType<PropertyDeclarationSyntax>()
              .FirstOrDefault(p => p.Identifier.ToString() == "BarType");

Or given the INamedTypeSymbol for Foo, I can do this:

var member = symbol.GetMembers("BarType").FirstOrDefault();

But I don't know where to go from there.

Ultimately I want to be able to get the symbol for MyBar for further analysis, so maybe even getting the string "MyBar" isn't going to help because it's not fully qualified.

Any suggestions?

EDIT:

I'm getting a project and a compilation like this:

var workspace = MSBuildWorkspace.Create();
var project = workspace.OpenProjectAsync(projectPath).Result;
var compilation = project.GetCompilationAsync().Result;

compilation is a CSharpCompilation here. From there I do something like this:

foreach (var doc in project.Documents)
{
    Console.WriteLine($"Analyzing {doc.Name}");

    //var model = doc.GetSemanticModelAsync().Result;
    var tree = doc.GetSyntaxTreeAsync().Result;
    var root = tree.GetRoot();
    var model = compilation.GetSemanticModel(tree);
    var classes = root.DescendantNodes().OfType<ClassDeclarationSyntax>();

    foreach (var syntax in classes)
    {
        var symbol = model.GetDeclaredSymbol(syntax);
        //... need to analyze properties in the class here...
    }
}

Either way I get model I end up with a SyntaxTreeSemanticModel which doesn't seem to have a GetTypeSymbol method.

Body:
You should look for the ReturnStatementSyntax and TypeOfExpressionSyntax. This contains the type MyBar. With the SemanticModel you can get the SymbolInfo like this:

var classDeclarationSyntaxs = root.DescendantNodes().OfType<ClassDeclarationSyntax>();
foreach ( var classDeclarationSyntax in classDeclarationSyntaxs )
{
    var propertyDeclarationSyntaxs = classDeclarationSyntax.Members.OfType<PropertyDeclarationSyntax>();
    var barTypePropertyDeclarationSyntax = propertyDeclarationSyntaxs.FirstOrDefault( p => p.Identifier.Text == "BarType" );
    if ( barTypePropertyDeclarationSyntax != null )
    {
        var returnStatementSyntax = barTypePropertyDeclarationSyntax.DescendantNodes().OfType<ReturnStatementSyntax>().FirstOrDefault();
        if ( returnStatementSyntax != null )
        {
            var typeOfExpressionSyntax = returnStatementSyntax.ChildNodes().OfType<TypeOfExpressionSyntax>().FirstOrDefault();
            if ( typeOfExpressionSyntax != null )
            {
                var symbolInfo = semanticModel.GetSymbolInfo( typeOfExpressionSyntax.Type );
                var symbolInfoSymbol = symbolInfo.Symbol;
            }
        }
    }
}

You can also use a SyntaxWalker for this:

public class TypeOfSyntaxWalker : CSharpSyntaxWalker
{
    private readonly SemanticModel _semanticModel;

    public ISymbol SymbolInfoSymbol { get; private set; }

    public TypeOfSyntaxWalker( SemanticModel semanticModel )
    {
        _semanticModel = semanticModel;
    }

    public override void VisitTypeOfExpression( TypeOfExpressionSyntax typeOfExpressionSyntax )
    {
        var parent = typeOfExpressionSyntax.Parent;
        if ( parent.Kind() == SyntaxKind.ReturnStatement )
        {
            var propertyDeclarationSyntax = parent.FirstAncestorOrSelf<PropertyDeclarationSyntax>();
            if ( propertyDeclarationSyntax != null &&
                    propertyDeclarationSyntax.Identifier.ValueText == "BarType" )
            {
                var symbolInfo = _semanticModel.GetSymbolInfo( typeOfExpressionSyntax.Type );
                SymbolInfoSymbol = symbolInfo.Symbol;
            }
        }
        base.VisitTypeOfExpression( typeOfExpressionSyntax );
    }
}

Usage:

var classDeclarationSyntaxs = root.DescendantNodes().OfType<ClassDeclarationSyntax>();
foreach ( var classDeclarationSyntax in classDeclarationSyntaxs )
{
    var typeOfSyntaxWalker = new TypeOfSyntaxWalker( semanticModel );
    typeOfSyntaxWalker.VisitClassDeclaration( classDeclarationSyntax );
    var symbolInfoSymbol = typeOfSyntaxWalker.SymbolInfoSymbol;
}


问:
Proper Redux usage general questions
Im a little uncertain as to how Redux ties in with React ( without using the ReactRedux library ). Assume the following component structure

```<code>App
--TodoListController
----SomeComponent1
----TodoList
------TodoItem
--ProfileController
</code>```

Question 1. Which components should listen for changes?:

Im assuming that the proper component to subscribe for state changes in the redux main (and only ) store should be the TodoListController and the ProfileController respectively ( essentially the non presentation components ).

Is this correct to assume or should all components listen to the state and render whatever is of interest to them? I essentially dont know which component should listen to state changes and am only guessing at this point

Question 2. Handling network calls:

I know this is to be examined per case but ill mention it anyway. Currently im handling network calls in the following manner:

A) When TodoListController mounts i get the state from the mainstore and also initiate a request to the server for the latest data. I also listen for changes in the store. So in practice:

```<code>class TodoListController extends React.Component{

componentWillMount(){
    mainStore.subscribe()
    getDataFromServer(function(data){
        mainStore.dispatch(data)
    })
}

getDataFromStoreAndUpdate(){
    this.state.datawecarefor = mainStore.todoReducer.data
    //set the state here to trigger a rerender
}

componentWillUnmount(){
    mainStore.unsubscribe()
}

render(){
 //render whatever component here that uses this.state.datawecarefor
}
}
</code>```

Do you see any obvious flaws with this approach? I dont know what i dont know at this point.

Question 3. Where should store related helper functions live?

I currently have a reducer that holds all todolists for various users. Currently, when the redux store state updates i retrieve all this data and iterate through it to find the user im interested in. This shouldnt be in the controller itself but as a hepler function. I thought of creating a wrapper around the Redux store and it's reducers to create functions like getTodoListForUser(userId) but i dont know if thats the right approach. How do you handle logic like that?

P.S: Many people will point out that i should use the ReactRedux library that comes with many optimisations and they re probably right. This however isnt a production project, only one im trying to put together to better udnerstanding the core of both these two libraries before moving to something more optimal.

答:
I know you don't want to use ReactRedux, but luckily enough there is a video of Dan Abramov explaining the source code. You should watch it, it will explain why they did what they did and how they did it. When I was first learning how redux and react worked together it made every so much more clear (and then I used ReactRedux anyway :)).

https://www.youtube.com/watch?v=VJ38wSFbM3A

There has been a lot of debate on where to connect React App's to the redux store. But it's mostly recommended that you want to connect where it makes logical sense. For example, if you have a container component that holds a bunch of comments, you don't need to connect all of the comments, you can just connect the container. In the same light you don't just want to connect your entire app at the top because then its more expensive to diff and update your app.

On another note you should probably try to handle network calls in redux middleware and dispatch an action your react component catches to cause a render.

Title: Proper Redux usage general questions

Body:
Im a little uncertain as to how Redux ties in with React ( without using the ReactRedux library ). Assume the following component structure

App
--TodoListController
----SomeComponent1
----TodoList
------TodoItem
--ProfileController

Question 1. Which components should listen for changes?:

Im assuming that the proper component to subscribe for state changes in the redux main (and only ) store should be the TodoListController and the ProfileController respectively ( essentially the non presentation components ).

Is this correct to assume or should all components listen to the state and render whatever is of interest to them? I essentially dont know which component should listen to state changes and am only guessing at this point

Question 2. Handling network calls:

I know this is to be examined per case but ill mention it anyway. Currently im handling network calls in the following manner:

A) When TodoListController mounts i get the state from the mainstore and also initiate a request to the server for the latest data. I also listen for changes in the store. So in practice:

class TodoListController extends React.Component{

componentWillMount(){
    mainStore.subscribe()
    getDataFromServer(function(data){
        mainStore.dispatch(data)
    })
}

getDataFromStoreAndUpdate(){
    this.state.datawecarefor = mainStore.todoReducer.data
    //set the state here to trigger a rerender
}

componentWillUnmount(){
    mainStore.unsubscribe()
}

render(){
 //render whatever component here that uses this.state.datawecarefor
}
}

Do you see any obvious flaws with this approach? I dont know what i dont know at this point.

Question 3. Where should store related helper functions live?

I currently have a reducer that holds all todolists for various users. Currently, when the redux store state updates i retrieve all this data and iterate through it to find the user im interested in. This shouldnt be in the controller itself but as a hepler function. I thought of creating a wrapper around the Redux store and it's reducers to create functions like getTodoListForUser(userId) but i dont know if thats the right approach. How do you handle logic like that?

P.S: Many people will point out that i should use the ReactRedux library that comes with many optimisations and they re probably right. This however isnt a production project, only one im trying to put together to better udnerstanding the core of both these two libraries before moving to something more optimal.


问:
What means something=something == number ? expression in Java
private int nColumns = 1;

public void onClick(View view) {

```<code>            nColumns = nColumns == 1 ? 2 : 1; //Cannot understand this line.
</code>```

Could anyone please explain?

答:
It is a ternary operator.
The part (nColumns == 1) ? 2 : 1; basically means if nColumns is equal to 1 then the first one, 2, is selected and else the latter, 1.
That value is then stored in the same variable nColumns.

So if it is equal to 1 then it gets 2 else it gets 1.

It does the same as the following:

```<code>if(nColumns == 1)
  nColumns = 2;
else
  nColumns = 1;
</code>```

Body:
private int nColumns = 1;

public void onClick(View view) {

            nColumns = nColumns == 1 ? 2 : 1; //Cannot understand this line.

Could anyone please explain?

Body:
It is a ternary operator.
The part (nColumns == 1) ? 2 : 1; basically means if nColumns is equal to 1 then the first one, 2, is selected and else the latter, 1.
That value is then stored in the same variable nColumns.

So if it is equal to 1 then it gets 2 else it gets 1.

It does the same as the following:

if(nColumns == 1)
  nColumns = 2;
else
  nColumns = 1;


问:
div:nth-child(0) doesn't work
I'm trying to change css attributes of a certain child div inside another div using nth-child index selector, but for some reason no changes occur.

```<code><div class="itemgrid">
    <div class="insideitem"></div>
    <div class="insideitem"></div>
    <div class="insideitem"></div>
    <div class="insideitem"></div>
</div>

.itemgrid{
    width:100%;
    display:block;
    font-style:inherit;
}

.itemgrid div:nth-child(2) :{
    border-width: 1px;
    border-color: #dedede;
    border-style: solid;
}
</code>```

Thank you in advance!

答:
It happens because index of the 1st child is 1 not 0. See w3Schools

Also you need to wrap your CSS code in
```

Title: div:nth-child(0) doesn't work

Body:
I'm trying to change css attributes of a certain child div inside another div using nth-child index selector, but for some reason no changes occur.

.itemgrid{
    width:100%;
    display:block;
    font-style:inherit;
}

.itemgrid div:nth-child(2) :{
    border-width: 1px;
    border-color: #dedede;
    border-style: solid;
}

Thank you in advance!

Body:
It happens because index of the 1st child is 1 not 0. See w3Schools

Also you need to wrap your CSS code in <style> tag.

Just change your CSS code to:

<style>
    .itemgrid{
        width:100%;
        display:block;
        font-style:inherit;
    }

    .itemgrid div:nth-child(1) {
        border-width: 1px;
        border-color: #dedede;
        border-style: solid;
    }
</style>


问:
Usage of * in Batch file?
I have a batch file that I acquired from a public forum, so unfortunately the original author is unknown to me. The batch file is called by a program running on a Windows server.

The purpose of the code is to copy .PDF files, move them to a different folder location on the server, and in the process, dynamically rename the files based upon values from a database.

The five variables declared within the code (%1 %2 %3 %4 %5) are command line arguments that are passed into the batch file. Variables %1 and %3 are basically 'hard-coded' values, while variables %2, %4, and %5 are variable.

The code is fully functional and I've modified it to suit my needs. However, I don't understand one of the statements in the code, so I'm hoping someone might be able to shed a little light on how or why it functions this way.

What I don't understand is the usage of the asterisk in line 23: IF %2==*

Functionally, I know that the end result of this bit of code is that if there is no value populated in the %2 variable, the code sets the file name prefix to nothing, otherwise it sets the prefix to whatever value is in the variable.

I understand the == comparison operator, I'm just not sure about the usage of the asterisk character in this context. I was expecting something like the following code instead: IF %2==""

I poked around on Google for awhile, looking for other examples or a possible explanation, but I couldn't find anything helpful. Can anyone shed any light on this? Thanks in advance!

Here's the code for the batch file:

```<code>@ECHO off

REM Set global variables
SET OutputFolder=D:\Temp
SET Prefix=

REM %1 Destination sub-folder name
REM %2 Prefix to add to file name (variable value, can be blank)
REM %3 File extension (set to pdf)
REM %4 Original output file location (full folder path on server)
REM %5 Original file name

ECHO %1 %2 %3 %4 %5 >> D:\Temp\CopyOutputLog.txt
cd %4

:FileExistTest
%~dp0\SLEEP.EXE 1
ECHO Does %5.%3 exist? ...
IF EXIST %4\%5.%3 (GOTO CopyFile) ELSE (GOTO FileExistTest)

:CopyFile
ECHO About to copy %5.%3 ...
IF %2==* (SET Prefix=) ELSE (SET PREFIX=%2)
COPY %4\%5.%3 "%OutputFolder%\%1\%Prefix%%5.%3"
GOTO end

:end
</code>```

答:
* is reserved character for file names, so to prevent errors if somebody pass it to script - original author discards it.

Unfortunately there are more special symbols, so this code is only partially correct.

Title: Usage of * in Batch file?

Body:
I have a batch file that I acquired from a public forum, so unfortunately the original author is unknown to me. The batch file is called by a program running on a Windows server.

The purpose of the code is to copy .PDF files, move them to a different folder location on the server, and in the process, dynamically rename the files based upon values from a database.

The five variables declared within the code (%1 %2 %3 %4 %5) are command line arguments that are passed into the batch file. Variables %1 and %3 are basically 'hard-coded' values, while variables %2, %4, and %5 are variable.

The code is fully functional and I've modified it to suit my needs. However, I don't understand one of the statements in the code, so I'm hoping someone might be able to shed a little light on how or why it functions this way.

What I don't understand is the usage of the asterisk in line 23: IF %2==*

Functionally, I know that the end result of this bit of code is that if there is no value populated in the %2 variable, the code sets the file name prefix to nothing, otherwise it sets the prefix to whatever value is in the variable.

I understand the == comparison operator, I'm just not sure about the usage of the asterisk character in this context. I was expecting something like the following code instead: IF %2==""

I poked around on Google for awhile, looking for other examples or a possible explanation, but I couldn't find anything helpful. Can anyone shed any light on this? Thanks in advance!

Here's the code for the batch file:

@ECHO off

REM Set global variables
SET OutputFolder=D:\Temp
SET Prefix=

REM %1 Destination sub-folder name
REM %2 Prefix to add to file name (variable value, can be blank)
REM %3 File extension (set to pdf)
REM %4 Original output file location (full folder path on server)
REM %5 Original file name

ECHO %1 %2 %3 %4 %5 >> D:\Temp\CopyOutputLog.txt
cd %4

:FileExistTest
%~dp0\SLEEP.EXE 1
ECHO Does %5.%3 exist? ...
IF EXIST %4\%5.%3 (GOTO CopyFile) ELSE (GOTO FileExistTest)

:CopyFile
ECHO About to copy %5.%3 ...
IF %2==* (SET Prefix=) ELSE (SET PREFIX=%2)
COPY %4\%5.%3 "%OutputFolder%\%1\%Prefix%%5.%3"
GOTO end

:end


答:
In css there is no 0th child, count starts from 1
if you are targeting to style the firstelement , use either first-child or nth-child(1)

.itemgrid{
    width:100vw;
    display:block;
    font-style:inherit;
    color:red;
}

.itemgrid div:nth-child(1) {
    border-width: 1px;
    border-color: #dedede;
    border-style: solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="itemgrid">
    <div class="insideitem">div-1</div>
    <div class="insideitem">dov=2</div>
    <div class="insideitem">div-3</div>
    <div class="insideitem">div-4</div>
</div></code>```

Title: div:nth-child(0) doesn't work

Body:
In css there is no 0th child, count starts from 1
if you are targeting to style the firstelement , use either first-child or nth-child(1)

.itemgrid{
    width:100vw;
    display:block;
    font-style:inherit;
    color:red;
}

.itemgrid div:nth-child(1) {
    border-width: 1px;
    border-color: #dedede;
    border-style: solid;
}

<div class="itemgrid">
    <div class="insideitem">div-1</div>
    <div class="insideitem">dov=2</div>
    <div class="insideitem">div-3</div>
    <div class="insideitem">div-4</div>
</div>


问:
Return sums even if no data exist in given day
I have a table with amounts only on some days, e.g.:

```<code>[DATE] [AMT]
11/1/2017 $123
11/1/2017 $50
11/3/2017 $123
</code>```

How can I query the data and get:

```<code>11/1/2017 $173
11/2/2017 $0
11/3/2017 $123
</code>```

I tried like:

```<code>SELECT Day([Date]) AS [Day], Nz(Sum(AMT),0) AS [Day Total]
FROM mytable
WHERE Month([Date])=11
GROUP BY Day([Date]);
</code>```

But still it doesn't return 0s for days without data, any ideas?

答:
In Access, you can create a series of dates between the first and the last date, and then create an outer join to your summed data.

Here is how to create the date series:

Create a date table between two dates

Body:
I have a table with amounts only on some days, e.g.:

[DATE] [AMT]
11/1/2017 $123
11/1/2017 $50
11/3/2017 $123

How can I query the data and get:

11/1/2017 $173
11/2/2017 $0
11/3/2017 $123

I tried like:

SELECT Day([Date]) AS [Day], Nz(Sum(AMT),0) AS [Day Total]
FROM mytable
WHERE Month([Date])=11
GROUP BY Day([Date]);

But still it doesn't return 0s for days without data, any ideas?


问:
hibernate updating entity attributes to null which are not in form submit
I am building a MVC application using thymeleaf and Spring and Hibernate. My question here is more about hibernate than spring.

This is what i have so far.

A UI

```<code><form role="form" th:action="@{/user/{userId}/official(userId=${userId})}" th:object="${user}" method="post">

            <!--  first form group  -->
            <div class="form-group">

                <label class="control-label col-xs-2">First Name</label>
                <div class="col-xs-2">
                    <input type="text" class="form-control" th:field="*{firstName}" placeholder="First Name" />
                </div>

                <label class="control-label col-xs-2">Last Name</label>
                <div class="col-xs-3">
                    <input type="text" class="form-control" th:field="*{lastName}" placeholder="Last Name" />

            <!--  first form group end  -->
            </div>
            <br/><br/>

            <!--  third form group  -->
                <div class="form-group">
                    <label class="control-label col-xs-2">Email Address</label>
                    <div class="col-xs-2">
                        <input type="text" class="form-control" th:field="*{emailAddress}" placeholder="Email Address" />
                    </div>

            </div>

            <div class="form-group">
                                    <div class="col-xs-2">
                                        <input type="submit" value="Update" class="btn btn-primary" />
    </form>
</code>```

Controller :

```<code>@Controller
public class UserController {

    @Autowired
    private IUserService userServiceImpl;

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.GET)
    public String getUserOfficialInfo(@PathVariable("userId") Integer userId, Model model) throws ServiceBusinessException {

                    UserBO userBO = userServiceImpl.findUserByUserId(userId);
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.POST)
    public String updateUserOfficialInfo(@PathVariable("userId") String userId, @ModelAttribute("user") UserBO user,BindingResult result, Model model) throws ServiceBusinessException {

                    userServiceImpl.updateUser(user);
                    UserBO userBO = userServiceImpl.findUserByUserId(Integer.parseInt(userId));
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }
}
</code>```

DAO :

```<code>@Override
    public void updateUser(UserEntity user) throws DaoException {
        entityManager.merge(user);
    }
</code>```

The GET method in the controller, gets the user object to the view. But on the VIew i am just displaying few of those attributes of a user object in the form.

On the form Submit, the POST method in the controller gets called, which calls the service layer and then the merge method in the DAO gets executed.

Now what I have observed is that this merge method on the entity manager is updating the attributes which are not there in the form to null.

I think this is the expected behaviour since the object is detached when its called from the POST method. So the right thing to do here is to first fetch the entity object from the database and then to that object set the fields which are changed in the form and then call the merge method.

Can some one let me know if the above what I said is correct ?

If yes, then my next question would be that isnt this quite tedious and kind of bit more effort. I mean there are going to be cases where in I would not want to display the entire object in the form. Also not in hidden fields. I am quite surprise that there is no way to handle this and I have to follow the approach I just described above each time.

Is there a better way to do this ? Wouldn't i just use JDBC template instead ? I know I would be writing boiler plate code there but I am kind of writing getters and setters here as well for each round trip to the UI.

答:
You will need to store the unnecessary bean properties in hidden fields so that they get remapped when the form is posted to the controller. For example, if you do not want to show the date of birth on the page (assuming that date of birth is already an attribute of the user), simply add the following tag inside the form.</p>

```<code><input type='hidden' th:field="*{dateOfBirth}" />
</code>```

Body:
I am building a MVC application using thymeleaf and Spring and Hibernate. My question here is more about hibernate than spring.

This is what i have so far.

A UI

<form role="form" th:action="@{/user/{userId}/official(userId=${userId})}" th:object="${user}" method="post">

                First Name

                    <input type="text" class="form-control" th:field="*{firstName}" placeholder="First Name" />

                Last Name

                    <input type="text" class="form-control" th:field="*{lastName}" placeholder="Last Name" />

                    Email Address

                        <input type="text" class="form-control" th:field="*{emailAddress}" placeholder="Email Address" />

                                        <input type="submit" value="Update" class="btn btn-primary" />
    </form>

Controller :

@Controller
public class UserController {

    @Autowired
    private IUserService userServiceImpl;

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.GET)
    public String getUserOfficialInfo(@PathVariable("userId") Integer userId, Model model) throws ServiceBusinessException {

                    UserBO userBO = userServiceImpl.findUserByUserId(userId);
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.POST)
    public String updateUserOfficialInfo(@PathVariable("userId") String userId, @ModelAttribute("user") UserBO user,BindingResult result, Model model) throws ServiceBusinessException {

                    userServiceImpl.updateUser(user);
                    UserBO userBO = userServiceImpl.findUserByUserId(Integer.parseInt(userId));
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }
}

DAO :

@Override
    public void updateUser(UserEntity user) throws DaoException {
        entityManager.merge(user);
    }

The GET method in the controller, gets the user object to the view. But on the VIew i am just displaying few of those attributes of a user object in the form.

On the form Submit, the POST method in the controller gets called, which calls the service layer and then the merge method in the DAO gets executed.

Now what I have observed is that this merge method on the entity manager is updating the attributes which are not there in the form to null.

I think this is the expected behaviour since the object is detached when its called from the POST method. So the right thing to do here is to first fetch the entity object from the database and then to that object set the fields which are changed in the form and then call the merge method.

Can some one let me know if the above what I said is correct ?

If yes, then my next question would be that isnt this quite tedious and kind of bit more effort. I mean there are going to be cases where in I would not want to display the entire object in the form. Also not in hidden fields. I am quite surprise that there is no way to handle this and I have to follow the approach I just described above each time.

Is there a better way to do this ? Wouldn't i just use JDBC template instead ? I know I would be writing boiler plate code there but I am kind of writing getters and setters here as well for each round trip to the UI.

Body:
You will need to store the unnecessary bean properties in hidden fields so that they get remapped when the form is posted to the controller. For example, if you do not want to show the date of birth on the page (assuming that date of birth is already an attribute of the user), simply add the following tag inside the form.

<input type='hidden' th:field="*{dateOfBirth}" />


问:
Batch file to copy a single folder - not just the contents
I am struggling to create a batch file that I can use in any folder, which will copy the current folder and all its contents to another location. The objective is to allow me to make very quick backups of any current folder by running the batch file. Batch files are new to me, but programming isn't. Here is my code.

```<code>@echo off
title Copy This Directory
:: get current directory
 set startdir=%cd%
 echo.startdir = %startdir%
:: copy the test folder
 xcopy "%startdir%" "F:\Temp Backup\" /s /y
 pause
</code>```

This copies the files and folders that are inside the source folder to the new destination, but I want to copy the folder itself together with its contents. ie if the batch file is in a folder called "FromFolder", I want "FromFolder" to appear as a folder in "F:\Temp Backup\" and all its contents in "F:\Temp Backup\FromFolder". I've found lots of info about copying files, but nothing about copying a single directory. I can copy a single file, but when I use the same code and change the file name to a folder name, it copies the folder's contents and not the folder itself. Could someone let me know what I have missed please.

答:
If you are running the batch file from the directory you want to backup you can literally do this in a handful of lines of code.</p>

```<code>@echo off
title Copy This Directory
for %%G in (".") do set folder=%%~nxG
md "F:\Temp Backup\%folder%" 2>nul
xcopy "*.*" "F:\Temp Backup\%folder%\" /s /y
</code>```

Body:
I am struggling to create a batch file that I can use in any folder, which will copy the current folder and all its contents to another location. The objective is to allow me to make very quick backups of any current folder by running the batch file. Batch files are new to me, but programming isn't. Here is my code.

@echo off
title Copy This Directory
:: get current directory
 set startdir=%cd%
 echo.startdir = %startdir%
:: copy the test folder
 xcopy "%startdir%" "F:\Temp Backup\" /s /y
 pause

This copies the files and folders that are inside the source folder to the new destination, but I want to copy the folder itself together with its contents. ie if the batch file is in a folder called "FromFolder", I want "FromFolder" to appear as a folder in "F:\Temp Backup\" and all its contents in "F:\Temp Backup\FromFolder". I've found lots of info about copying files, but nothing about copying a single directory. I can copy a single file, but when I use the same code and change the file name to a folder name, it copies the folder's contents and not the folder itself. Could someone let me know what I have missed please.

Body:
If you are running the batch file from the directory you want to backup you can literally do this in a handful of lines of code.

@echo off
title Copy This Directory
for %%G in (".") do set folder=%%~nxG
md "F:\Temp Backup\%folder%" 2>nul
xcopy "*.*" "F:\Temp Backup\%folder%\" /s /y


问:
Integer division algorithm
I was thinking about an algorithm in division of large numbers: dividing with remainder bigint C by bigint D, where we know the representation of C in base b, and D is of form b^k-1. It's probably the easiest to show it on an example. Let's try dividing C=21979182173 by D=999.

We write the number as sets of three digits: 21 979 182 173

We take sums (modulo 999) of consecutive sets, starting from the left: 21 001 183 356

We add 1 to those sets preceding the ones where we "went over 999": 22 001 183 356

Indeed, 21979182173/999=22001183 and remainder 356.

I've calculated the complexity and, if I'm not mistaken, the algorithm should work in O(n), n being the number of digits of C in base b representation. I've also done a very crude and unoptimized version of the algorithm (only for b=10) in C++, tested it against GMP's general integer division algorithm and it really does seem to fare better than GMP. I couldn't find anything like this implemented anywhere I looked, so I had to resort to testing it against general division.

I found several articles which discuss what seem to be quite similar matters, but none of them concentrate on actual implementations, especially in bases different than 2. I suppose that's because of the way numbers are internally stored, although the mentioned algorithm seems useful for, say, b=10, even taking that into account. I also tried contacting some other people, but, again, to no avail.

Thus, my question would be: is there an article or a book or something where the aforementioned algorithm is described, possibly discussing the implementations? If not, would it make sense for me to try and implement and test such an algorithm in, say, C/C++ or is this algorithm somehow inherently bad?

Also, I'm not a programmer and while I'm reasonably OK at programming, I admittedly don't have much knowledge of computer "internals". Thus, pardon my ignorance - it's highly possible there are one or more very stupid things in this post. Sorry once again.

Thanks a lot!

Further clarification of points raised in the comments/answers:

Thanks, everyone - as I didn't want to comment on all the great answers and advice with the same thing, I'd just like to address one point a lot of you touched on.

I am fully aware that working in bases 2^n is, generally speaking, clearly the most efficient way of doing things. Pretty much all bigint libraries use 2^32 or whatever. However, what if (and, I emphasize, it would be useful only for this particular algorithm!) we implement bigints as an array of digits in base b? Of course, we require b here to be "reasonable": b=10, the most natural case, seems reasonable enough. I know it's more or less inefficient both considering memory and time, taking into account how numbers are internally stored, but I have been able to, if my (basic and possibly somehow flawed) tests are correct, produce results faster than GMP's general division, which would give sense to implementing such an algorithm.

Ninefingers notices I'd have to use in that case an expensive modulo operation. I hope not: I can see if old+new crossed, say, 999, just by looking at the number of digits of old+new+1. If it has 4 digits, we're done. Even more, since old<999 and new<=999, we know that if old+new+1 has 4 digits (it can't have more), then, (old+new)%999 equals deleting the leftmost digit of (old+new+1), which I presume we can do cheaply.

Of course, I'm not disputing obvious limitations of this algorithm nor I claim it can't be improved - it can only divide with a certain class of numbers and we have to a priori know the representation of dividend in base b. However, for b=10, for instance, the latter seems natural.

Now, say we have implemented bignums as I outlined above. Say C=(a_1a_2...a_n) in base b and D=b^k-1. The algorithm (which could be probably much more optimized) would go like this. I hope there aren't many typos.

if k>n, we're obviously done

add a zero (i.e. a_0=0) at the beginning of C (just in case we try to divide, say, 9999 with 99)

l=n%k (mod for "regular" integers - shouldn't be too expensive)

old=(a_0...a_l) (the first set of digits, possibly with less than k digits)

for (i=l+1; i < n; i=i+k) (We will have floor(n/k) or so iterations)

new=(a_i...a_(i+k-1))

new=new+old (this is bigint addition, thus O(k))

aux=new+1 (again, bigint addition - O(k) - which I'm not happy about)

if aux has more than k digits

delete first digit of aux

old=old+1 (bigint addition once again)

fill old with zeroes at the beginning so it has as much digits as it should

(a_(i-k)...a_(i-1))=old (if i=l+1, (a _ 0...a _ l)=old)

new=aux

fill new with zeroes at the beginning so it has as much digits as it should

(a_i...a_(i+k-1)=new

quot=(a_0...a_(n-k+1))

rem=new

There, thanks for discussing this with me - as I said, this does seem to me to be an interesting "special case" algorithm to try to implement, test and discuss, if nobody sees any fatal flaws in it. If it's something not widely discussed so far, even better. Please, let me know what you think. Sorry about the long post.

Also, just a few more personal comments:

@Ninefingers: I actually have some (very basic!) knowledge of how GMP works, what it does and of general bigint division algorithms, so I was able to understand much of your argument. I'm also aware GMP is highly optimized and in a way customizes itself for different platforms, so I'm certainly not trying to "beat it" in general - that seems as much fruitful as attacking a tank with a pointed stick. However, that's not the idea of this algorithm - it works in very special cases (which GMP does not appear to cover). On an unrelated note, are you sure general divisions are done in O(n)? The most I've seen done is M(n). (And that can, if I understand correctly, in practice (Schönhage–Strassen etc.) not reach O(n). Fürer's algorithm, which still doesn't reach O(n), is, if I'm correct, almost purely theoretical.)

@Avi Berger: This doesn't actually seem to be exactly the same as "casting out nines", although the idea is similar. However, the aforementioned algorithm should work all the time, if I'm not mistaken.

答:
If you need to frequently divide by the same divisor, using it (or a power of it) as your base makes division as cheap as bit-shifting is for base 2 binary integers.

You could use base 999 if you want; there's nothing special about using a power-of-10 base except that it makes conversion to decimal integer very cheap.  (You can work one limb at a time instead of having to do a full division over the whole integer.  It's like the difference between converting a binary integer to decimal vs. turning every 4 bits into a hex digit.  Binary -> hex can start with the most significant bits, but converting to non-power-of-2 bases has to be LSB-first using division.)

For example, to compute the first 1000 decimal digits of Fibonacci(109) for a code-golf question with a performance requirement, my 105 bytes of x86 machine code answer used the same algorithm as this Python answer: the usual a+=b; b+=a Fibonacci iteration, but divide by (a power of) 10 every time a gets too large.

Fibonacci grows faster than carry propagates, so discarding the low decimal digits occasionally doesn't change the high digits long-term.  (You keep a few extra beyond the precision you want).

Dividing by a power of 2 doesn't work, unless you keep track of how many powers of 2 you've discarded, because the eventual binary -> decimal conversion at the end would depend on that.

So for this algorithm, you have to do extended-precision addition, and division by 10 (or whatever power of 10 you want).

I stored base-109 limbs in 32-bit integer elements.  Dividing by 109 is trivially cheap: just a pointer increment to skip the low limb.  Instead of actually doing a memmove, I just offset the pointer used by the next add iteration.

I think division by a power of 10 other than 10^9 would be somewhat cheap, but would require an actual division on each limb, and propagating the remainder to the next limb.

Extended-precision addition is somewhat more expensive this way than with binary limbs, because I have to generate the carry-out manually with a compare: sum[i] = a[i] + b[i]; carry = sum < a; (unsigned comparison).  And also manually wrap to 10^9 based on that compare, with a conditional-move instruction.  But I was able to use that carry-out as an input to adc (x86 add-with-carry instruction).

You don't need a full modulo to handle the wrapping on addition, because you know you've wrapped at most once.

This wastes a just over 2 bits of each 32-bit limb: 10^9 instead of 2^32 = 4.29... * 10^9.  Storing base-10 digits one per byte would be significantly less space efficient, and very much worse for performance, because an 8-bit binary addition costs the same as a 64-bit binary addition on a modern 64-bit CPU.

I was aiming for code-size: for pure performance I would have used 64-bit limbs holding base-10^19 "digits".  (2^64 = 1.84... * 10^19, so this wastes less than 1 bit per 64.)  This lets you get twice as much work done with each hardware add instruction.  Hmm, actually this might be a problem: the sum of two limbs might wrap the 64-bit integer, so just checking for > 10^19 isn't sufficient anymore.  You could work in base 5*10^18, or in base 10^18, or do more complicated carry-out detection that checks for binary carry as well as manual carry.

Storing packed BCD with one digit per 4 bit nibble would be even worse for performance, because there isn't hardware support for blocking carry from one nibble to the next within a byte.

Overall, my version ran about 10x faster than the Python extended-precision version on the same hardware (but it had room for significant optimization for speed, by dividing less often).  (70 seconds or 80 seconds vs. 12 minutes)

Still, I think for this particular implementation of that algorithm (where I only needed addition and division, and division happened after every few additions), the choice of base-10^9 limbs was very good.  There are much more efficient algorithms for the Nth Fibonacci number that don't need to do 1 billion extended-precision additions.

ContentLicense: CC BY-SA 2.5

Title: Integer division algorithm


问:
runtime error '1004': method 'range' of object '_global' failed

Can Anyone help with this error? It actually works in one computer but not in others

```<code>Dim Rango As Range, FilaFin As Long
Dim i As Long, x As Object
Application.ScreenUpdating = False
Sheet1.Select
FilaFin = Range("E6:E13").Offset(0, 4).End(xlDown).Row
Sheet1.Range("E6:E13").Copy
Sheet4.Select
FilaFin = Range("C1048576").End(xlUp).Row + 1
Range("C" & FilaFin).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks _
        :=False, Transpose:=True
FilaFin = Range("E18:E25").Offset(0, 4).End(xlDown).Row
</code>```

答:
1048576 rows are only available for Excel-2007 onward.

65536 rows are available for Excel-2003 and older version.

That's why

It actually works in one computer but not in others

Hard coding your number of rows is a bad practice. Just make it dynamic:

Range(Cells(Rows.Count, 3),Cells(Rows.Count, 3)).End(xlUp).Row

Rows.Count returns total no. of rows irrespective of the version.

Body:
Can Anyone help with this error? It actually works in one computer but not in others

Dim Rango As Range, FilaFin As Long
Dim i As Long, x As Object
Application.ScreenUpdating = False
Sheet1.Select
FilaFin = Range("E6:E13").Offset(0, 4).End(xlDown).Row
Sheet1.Range("E6:E13").Copy
Sheet4.Select
FilaFin = Range("C1048576").End(xlUp).Row + 1
Range("C" & FilaFin).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks _
        :=False, Transpose:=True
FilaFin = Range("E18:E25").Offset(0, 4).End(xlDown).Row


答:
if the number of nColumns is 1 return 2 else return 1 and assign it to it slef which is nColumns.</p>

```<code>if(nColumns==1)
   nColumns=2;
else
   nColumns=1;
</code>```

Title: What means something=something == number ? expression in Java

Body:
if the number of nColumns is 1 return 2 else return 1 and assign it to it slef which is nColumns.

if(nColumns==1)
   nColumns=2;
else
   nColumns=1;


问:
How do I update the global value of a global list inside an object through a function?
I am trying to make a text-based calendar with JavaScript. What I am stuck on now is when I search for the item after adding it to the calendar. Feel free to run it in firefox or whatever you dev's use to see what I mean. When I search for a value, there is a blank screen being outputted instead of the values that were scheduled for that day (more specifically, the items that were pushed to that specific list.) What should I do to update the Calendar list items in the simplest way possible?

var userInput; // user's choice of 'e', 's', or 'q'
var enterInfo; // item that is entered into calender from user
var searchInfo; // item that is used to search calendar for entered events

var Calendar = { // calender of scheduled events of user
  monday: {
    morning: [],
    afternoon: [],
    evening: []
  },
  tuesday: {
    morning: [],
    afternoon: [],
    evening: []
  },
  wednesday: {
    morning: [],
    afternoon: [],
    evening: []
  },
  thursday: {
    morning: [],
    afternoon: [],
    evening: []
  },
  friday: {
    morning: [],
    afternoon: [],
    evening: []
  },
};

var addEventToCalendar = function(day, time) { // adds event from user to calender
  switch (day) {
    case "monday": // if day is monday
      switch (time) {
        case "morning":
          Calendar.monday.morning.push(info[2]);
          break;
        case "afternoon":
          Calendar.monday.afternoon.push(info[2]);
          break;
        case "evening":
          Calendar.monday.evening.push(info[2]);
          break;
      }
      break;
    case "tuesday": // if day is monday
      switch (time) {
        case "morning":
          Calendar.tuesday.morning.push(info[2]);
          break;
        case "afternoon":
          Calendar.tuesday.afternoon.push(info[2]);
          break;
        case "evening":
          Calendar.tuesday.evening.push(info[2]);
          break;
      }
      break;
    case "wednesday": // if day is monday
      switch (time) {
        case "morning":
          Calendar.wednesday.morning.push(info[2]);
          break;
        case "afternoon":
          Calendar.wednesday.afternoon.push(info[2]);
          break;
        case "evening":
          Calendar.wednesday.evening.push(info[2]);
          break;
      }
      break;
  }
}

var outputEvents = function(day, time) { // adds event from user to calender
  switch (day) {
    case "monday": // if day is monday
      switch (time) {
        case "morning":
          alert(Calendar.monday.morning);
          break;
        case "afternoon":
          alert(Calendar.monday.afternoon);
          break;
        case "evening":
          alert(Calendar.monday.evening);
          break;
      }
      break;
    case "tuesday": // if day is monday
      switch (time) {
        case "morning":
          alert(Calendar.tuesday.morning);
          break;
        case "afternoon":
          alert(Calendar.tuesday.afternoon);
          break;
        case "evening":
          alert(Calendar.tuesday.evening);
          break;
      }
      break;
    case "wednesday": // if day is monday
      switch (time) {
        case "morning":
          alert(Calendar.wednesday.morning);
          break;
        case "afternoon":
          alert(Calendar.wednesday.afternoon);
          break;
        case "evening":
          alert(Calendar.wednesday.evening);
          break;
      }
      break;
  }
}

var checkEnterInfo = function(info) { // checks if 'enterInfo' is valid
  info = info.split(", "); // splits info up to check if valid
  if (info.length != 3) { // checks if input from user has only 3 input values
    alert("Enter your information correctly, please.\n\n" +
      "Time, Day, Name (ex: morning, Monday, write letter)");
    mainProgram();
  } else if (isNaN(info[0] == false) || isNaN(info[1] == false) || isNaN(info[2]) == false) { // checks if all input values are strings
    alert("Please enter only alphabetic characters as your information.");
    mainProgram();
  } else if (info[0] != "morning" && info[0] != "afternoon" && info[0] != "evening") { // checks if time of day is valid
    alert("Please enter only one of the following for the time of day:\n\n" +
      "'Morning', 'Afternoon', or 'Evening'");
    mainProgram();
  } else if (info[1] != "monday" && info[1] != "tuesday" && info[1] != "wednesday" && info[1] != "thursday" && info[1] != "friday") { // checks if day from user is valid
    alert("Please enter only one of the following for the day of the event:\n\n" +
      "'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'");
    mainProgram();
  } else {
    addEventToCalendar(info[0], info[1]);
    mainProgram();
  }
}

var checkSearchInfo = function(info) {
  info = info.split(", "); // splits info to check if valid
  if (info.length != 2) { // checks if info does not have 2 input values to search for event
    alert("Please enter your information like so:\n\n" +
      "ex. Afternoon, Wednesday");
    mainProgram();
  } else if (isNaN(info[0]) == false || isNaN(info[1]) == false) { // checks if input values are strings
    alert("Please enter only alphabetic characters as your information.");
    mainProgram();
  } else if (info[0] != "morning" && info[0] != "afternoon" && info[0] != "evening") { // checks if time of day is valid
    alert("Please enter only one of the following for the time of day:\n\n" +
      "'Morning', 'Afternoon', or 'Evening'");
    mainProgram();
  } else if (info[1] != "monday" && info[1] != "tuesday" && info[1] != "wednesday" && info[1] != "thursday" && info[1] != "friday") { // checks if day from user is valid
    alert("Please enter only one of the following for the day of the event:\n\n" +
      "'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'");
    mainProgram();
  } else {
    outputEvents(info[1], info[0]);
  }
}
var mainProgram = function() { // main program function
  userInput = prompt("(E)nter an event, (S)earch, or (Q)uit: ").toLowerCase();

  if (userInput == 'q') { // user wants to quit
    alert("You have chosen to end the program.");
    return userInput;
    mainProgram();
  } else if (userInput == 's') { // search for event in calendar
    searchInfo = prompt("Enter time and day: ");
    checkSearchInfo(searchInfo);
  } else if (userInput == 'e') { // add event to calendar
    enterInfo = prompt("Enter time, day, and name: ");
    checkEnterInfo(enterInfo);
  } else { // user did not enter an available option
    alert("Choose from one of the options shown:" +
      "\n\n(E)nter an event, (S)earch, or (Q)uit: ");
    mainProgram();
  }
}

mainProgram();```

答:
Your function addEventToCalendar has no access to info[2], you don't pass it as paramater and it is not in the upper scope. </p>

<p>You should add a thrid parameter and pass info[2] when you call your function addEventToCalendar. Or pass only one paramater info, and access it by info[0] , info[1] et info[2] in function declaration. </p>

Body:
Your function addEventToCalendar has no access to info[2], you don't pass it as paramater and it is not in the upper scope.

You should add a thrid parameter and pass info[2] when you call your function addEventToCalendar. Or pass only one paramater info, and access it by info[0] , info[1] et info[2] in function declaration.


问:
Helm upgrade times out and fails to get configmaps
After months of using Helm (version 2.6.2) to deploy services in kubernetes, we've started experiencing random errors while performing the --upgrade command.

Most of the time the upgrade times out, in other situations instead it looks like a network issue occurs, with errors like getsockopt: connection refused or TLS handshake timeout.

Sometimes we've also seen the server cannot complete the requested operation at this time, try again later (get configmaps).

We're using Helm to deploy several versions a day of our services to our CI environment, and the instability of the deployment process that started to creep in is affecting our productivity.

Any idea what I should look for to restore the --upgrade command to a reliable state?

答:
Upgrading to Helm 2.7.0 and using --history-max solved the issue for me, so the problem must have been related to the fact that old config maps were not cleared up by tiller, and over time they piled up until tiller started to struggle to make sense of them.

More information about it here.


问:
Accessing "neighbor" classes created from 1 class possible?
Here's my problem:

I have 1 class that creates two new instances of a two other classes, and now I would need to either have a direct availability from one of the instances to the other, is this possible and if so, how?

so:

in Class A:

```<code>b = new B(5); // where 5 is an int data member of B
c = new C();
</code>```

and let B::bee() be a function I would need to access from C() BUT, I would need to access members of B (not a new instance of B) created by A.

```<code>So C::getIntfromB(){
  b->getInt();
}
</code>```

Or something.

I've tried going for:

```<code>b = new B(5);
c = new C(*b);
</code>```

having a B b; private member for C

However for some reason I simply cannot get it to work properly, what is the obvious error I am making?

答: The main reason your object C can't access correct data from object B is because C has its own copy of object B' instead of reference to existing peer object B.

Body:
Here's my problem:

I have 1 class that creates two new instances of a two other classes, and now I would need to either have a direct availability from one of the instances to the other, is this possible and if so, how?

so:

in Class A:

b = new B(5); // where 5 is an int data member of B
c = new C();

and let B::bee() be a function I would need to access from C() BUT, I would need to access members of B (not a new instance of B) created by A.

So C::getIntfromB(){
  b->getInt();
}

Or something.

I've tried going for:

b = new B(5);
c = new C(*b);

having a B b; private member for C

However for some reason I simply cannot get it to work properly, what is the obvious error I am making?


问:
How to Pass a String or Variable with HTTP Redirect in Laravel
I'm developing a quiz and want to check if a question is answered already. Then I'd like to print something and/or disable the form after submitting. The page will be redirected back to show the new option if the user has any observation or reservation. If the form redirects back how can I check or disable the form so a user can't submit the form again? I am using the following method to redirect back.

```<code><?php

return redirect()->back();
</code>```

If I pass a variable using the with() method I get no success. The system doesn't recognize my variable. I also tried...

```<code><?php

return redirect()->back()->withDisable('disable');
</code>```

答:
you can use flash data in laravel for this kind of task.

What is Flash Data?

Flash data helps you to store items in the session only for the next request.Data stored in the session using this method will only be available during the subsequent HTTP request, and then will be deleted.

```<code>$request->session()->flash('disabled', 'true');
</code>```

However, If you need to keep your flash data around for several requests

```<code>$request->session()->keep(['disabled', 'true']);
</code>```

to access your session/flash data you can simply do

```<code>$request->session()->all() //all flash session data

$request->session()->get('disabled') // for specific
</code>```

hope that helps

ContentLicense: CC BY-SA 4.0

Body:
I'm developing a quiz and want to check if a question is answered already. Then I'd like to print something and/or disable the form after submitting. The page will be redirected back to show the new option if the user has any observation or reservation. If the form redirects back how can I check or disable the form so a user can't submit the form again? I am using the following method to redirect back.

<?php

return redirect()->back();

If I pass a variable using the with() method I get no success. The system doesn't recognize my variable. I also tried...

<?php

return redirect()->back()->withDisable('disable');

Body:
you can use flash data in laravel for this kind of task.

What is Flash Data?

Flash data helps you to store items in the session only for the next request.Data stored in the session using this method will only be available during the subsequent HTTP request, and then will be deleted.

$request->session()->flash('disabled', 'true');

However, If you need to keep your flash data around for several requests

$request->session()->keep(['disabled', 'true']);

to access your session/flash data you can simply do

$request->session()->all() //all flash session data

$request->session()->get('disabled') // for specific

hope that helps


问:
Publishing to npm, file defined in `main` is not published
I'm trying to publish a package to npm and for some reason the .js I've defined in the package.json isn't included with the package. My project is written in typescript and I transpile via the following npm script...

```<code>"prepublishOnly": "tsc -p ./ --outDir dist/"
</code>```

Which correctly outputs the file I expect to dist/app.js locally. I then do an npm publish and the readme.md and some other files are published, but not the app.js I expect to be. The package.json has the main set as dist/app.js so what am I missing here?

This is my first npm package publish, so it's probably something stupid, happy to try any ideas.

答:
The issue is most likely because you have a .gitignore file, which npm will respect as a fallback if no .npmignore file is found. I am guessing you are running into the above, perhaps ignoring /dist in source control?

If there's no .npmignore file, but there is a .gitignore file, then
  npm will ignore the stuff matched by the .gitignore file

main will not actually dictate what content is packed...

The main field is a module ID that is the primary entry point to your
  program. That is, if your package is named foo, and a user installs
  it, and then does require("foo"), then your main module's exports
  object will be returned.

Additionally, packaged files can explicitly included via files

```<code>"files": ["dist/app.js", "/and/others/"]
</code>```

And lastly, if you take a peek at npm/issues/3571, you can workaround this by simply adding an empty .npmignore file.

If you want to include something that is excluded by your .gitignore
  file, you can create an empty .npmignore file to override it.

pro tip - you can run npm pack locally, which will execute all the lifecycle hooks of a publish and provide you the .tgz package as if it were fetched from npm. You can unzip this to inspect the contents. I've found this super useful on many occasions to emulate publishing without actually doing so.

Body:
I'm trying to publish a package to npm and for some reason the .js I've defined in the package.json isn't included with the package. My project is written in typescript and I transpile via the following npm script...

"prepublishOnly": "tsc -p ./ --outDir dist/"

Which correctly outputs the file I expect to dist/app.js locally. I then do an npm publish and the readme.md and some other files are published, but not the app.js I expect to be. The package.json has the main set as dist/app.js so what am I missing here?

This is my first npm package publish, so it's probably something stupid, happy to try any ideas.

Body:
The issue is most likely because you have a .gitignore file, which npm will respect as a fallback if no .npmignore file is found. I am guessing you are running into the above, perhaps ignoring /dist in source control?

If there's no .npmignore file, but there is a .gitignore file, then
  npm will ignore the stuff matched by the .gitignore file

main will not actually dictate what content is packed...

The main field is a module ID that is the primary entry point to your
  program. That is, if your package is named foo, and a user installs
  it, and then does require("foo"), then your main module's exports
  object will be returned.

Additionally, packaged files can explicitly included via files

"files": ["dist/app.js", "/and/others/"]

And lastly, if you take a peek at npm/issues/3571, you can workaround this by simply adding an empty .npmignore file.

If you want to include something that is excluded by your .gitignore
  file, you can create an empty .npmignore file to override it.

pro tip - you can run npm pack locally, which will execute all the lifecycle hooks of a publish and provide you the .tgz package as if it were fetched from npm. You can unzip this to inspect the contents. I've found this super useful on many occasions to emulate publishing without actually doing so.


问:
Cloudera - Sqoop codegen custom ORM class on import
I am new to Cloudera environment, I am trying to import data from RDBMS using Sqoop and I need to apply some transformations to data during the import. Specifically I need to encrypt some fields before storing them on the Hadoop DFS. To accomplish this I am trying to use the codegen command, which generates an ORM java class that I can modify.

Let's say I have a table 'products' on MySQL database and I want to import it on HDFS using Sqoop and encrypt the 'brand' field.
First I've run this command:

```<code>sqoop codegen \
--connect jdbc:mysql://localhost/test \
--username username --password password \
--table products
</code>```

This generates the files products.java, products.jar and products.class in the folder /tmp/sqoop-training/compile/fc8868dda33ef703ad126583cf77477f.

Now I've modified the method readFields in products.java like so:

```<code>// WARNING: This class is AUTO-GENERATED. Modify at your own risk.
//
// Debug information:
// Generated date: Thu Nov 16 06:55:13 PST 2017
// For connector: org.apache.sqoop.manager.MySQLManager
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapred.lib.db.DBWritable;
import com.cloudera.sqoop.lib.JdbcWritableBridge;
import com.cloudera.sqoop.lib.DelimiterSet;
import com.cloudera.sqoop.lib.FieldFormatter;
import com.cloudera.sqoop.lib.RecordParser;
import com.cloudera.sqoop.lib.BooleanParser;
import com.cloudera.sqoop.lib.BlobRef;
import com.cloudera.sqoop.lib.ClobRef;
import com.cloudera.sqoop.lib.LargeObjectLoader;
import com.cloudera.sqoop.lib.SqoopRecord;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class products extends SqoopRecord  implements DBWritable, Writable {

    // [...]

    public void readFields(ResultSet __dbResults) throws SQLException {
        this.__cur_result_set = __dbResults;
        this.prod_id = JdbcWritableBridge.readInteger(1, __dbResults);
        this.brand = encrypt(JdbcWritableBridge.readString(2, __dbResults));
        this.name = JdbcWritableBridge.readString(3, __dbResults);
        this.price = JdbcWritableBridge.readInteger(4, __dbResults);
        this.cost = JdbcWritableBridge.readInteger(5, __dbResults);
        this.shipping_wt = JdbcWritableBridge.readInteger(6, __dbResults);
    }

    // [...]

}
</code>```

I have two questions:

1) How can I recompile the products.java to obtain updated versions of products.class and products.jar? I've tried with

```<code>javac products.java
</code>```

but JVM gives 82 errors, it seems it cannot find packages from hadoop and cloudera namespace:

```<code>error: package org.apache.hadoop.io does not exist
import org.apache.hadoop.io.BytesWritable;
                           ^
products.java:8: error: package org.apache.hadoop.io does not exist
import org.apache.hadoop.io.Text;
                           ^
products.java:9: error: package org.apache.hadoop.io does not exist
import org.apache.hadoop.io.Writable;
                           ^
products.java:10: error: package org.apache.hadoop.mapred.lib.db does not exist
import org.apache.hadoop.mapred.lib.db.DBWritable;
                                      ^
products.java:11: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.JdbcWritableBridge;
                             ^
products.java:12: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.DelimiterSet;
                             ^
products.java:13: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.FieldFormatter;
                             ^
products.java:14: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.RecordParser;
                             ^
products.java:15: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.BooleanParser;
                             ^
products.java:16: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.BlobRef;
                             ^
products.java:17: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.ClobRef;
                             ^
products.java:18: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.LargeObjectLoader;
                             ^
products.java:19: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.SqoopRecord;
</code>```

2) Once I have successfully compiled products.java, how can I use Sqoop to import data on HDFS using my custom ORM class?

Thanks in advance!

答:
On first question:

Add

```<code>export CLASSPATH=`hadoop classpath`:/opt/cloudera/parcels/CDH/lib/sqoop/lib
</code>```

and then try again.

ps. Generally on architecture, minor comment on "Specifically I need to encrypt some fields before storing them on the Hadoop DFS" - why don't you use HDFS Transparent Encryption? https://www.cloudera.com/documentation/enterprise/latest/topics/cdh_sg_hdfs_encryption.html You can achieve the same without any coding.

Body:
I am new to Cloudera environment, I am trying to import data from RDBMS using Sqoop and I need to apply some transformations to data during the import. Specifically I need to encrypt some fields before storing them on the Hadoop DFS. To accomplish this I am trying to use the codegen command, which generates an ORM java class that I can modify.

Let's say I have a table 'products' on MySQL database and I want to import it on HDFS using Sqoop and encrypt the 'brand' field.
First I've run this command:

sqoop codegen \
--connect jdbc:mysql://localhost/test \
--username username --password password \
--table products

This generates the files products.java, products.jar and products.class in the folder /tmp/sqoop-training/compile/fc8868dda33ef703ad126583cf77477f.

Now I've modified the method readFields in products.java like so:

// WARNING: This class is AUTO-GENERATED. Modify at your own risk.
//
// Debug information:
// Generated date: Thu Nov 16 06:55:13 PST 2017
// For connector: org.apache.sqoop.manager.MySQLManager
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapred.lib.db.DBWritable;
import com.cloudera.sqoop.lib.JdbcWritableBridge;
import com.cloudera.sqoop.lib.DelimiterSet;
import com.cloudera.sqoop.lib.FieldFormatter;
import com.cloudera.sqoop.lib.RecordParser;
import com.cloudera.sqoop.lib.BooleanParser;
import com.cloudera.sqoop.lib.BlobRef;
import com.cloudera.sqoop.lib.ClobRef;
import com.cloudera.sqoop.lib.LargeObjectLoader;
import com.cloudera.sqoop.lib.SqoopRecord;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class products extends SqoopRecord  implements DBWritable, Writable {

    // [...]

    public void readFields(ResultSet __dbResults) throws SQLException {
        this.__cur_result_set = __dbResults;
        this.prod_id = JdbcWritableBridge.readInteger(1, __dbResults);
        this.brand = encrypt(JdbcWritableBridge.readString(2, __dbResults));
        this.name = JdbcWritableBridge.readString(3, __dbResults);
        this.price = JdbcWritableBridge.readInteger(4, __dbResults);
        this.cost = JdbcWritableBridge.readInteger(5, __dbResults);
        this.shipping_wt = JdbcWritableBridge.readInteger(6, __dbResults);
    }

    // [...]

}

I have two questions:

1) How can I recompile the products.java to obtain updated versions of products.class and products.jar? I've tried with

javac products.java

but JVM gives 82 errors, it seems it cannot find packages from hadoop and cloudera namespace:

error: package org.apache.hadoop.io does not exist
import org.apache.hadoop.io.BytesWritable;
                           ^
products.java:8: error: package org.apache.hadoop.io does not exist
import org.apache.hadoop.io.Text;
                           ^
products.java:9: error: package org.apache.hadoop.io does not exist
import org.apache.hadoop.io.Writable;
                           ^
products.java:10: error: package org.apache.hadoop.mapred.lib.db does not exist
import org.apache.hadoop.mapred.lib.db.DBWritable;
                                      ^
products.java:11: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.JdbcWritableBridge;
                             ^
products.java:12: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.DelimiterSet;
                             ^
products.java:13: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.FieldFormatter;
                             ^
products.java:14: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.RecordParser;
                             ^
products.java:15: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.BooleanParser;
                             ^
products.java:16: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.BlobRef;
                             ^
products.java:17: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.ClobRef;
                             ^
products.java:18: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.LargeObjectLoader;
                             ^
products.java:19: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.SqoopRecord;

2) Once I have successfully compiled products.java, how can I use Sqoop to import data on HDFS using my custom ORM class?

Thanks in advance!

Body:
On first question:

Add

export CLASSPATH=`hadoop classpath`:/opt/cloudera/parcels/CDH/lib/sqoop/lib

and then try again.

ps. Generally on architecture, minor comment on "Specifically I need to encrypt some fields before storing them on the Hadoop DFS" - why don't you use HDFS Transparent Encryption? https://www.cloudera.com/documentation/enterprise/latest/topics/cdh_sg_hdfs_encryption.html You can achieve the same without any coding.


问:
SQL Delphi "Parameter 'Subject' not found"
I have recently started to learn how to code in Delphi since moving from Python to do a project. I can't seem to find a fix to this issue. I have searched online for a couple of hours now and none of the 'fixes' seem to be working. I have tried using 'Query.ExecSQL', I have tried breaking the code up into segments, I have tried to assign edtSubject.Text to a variable and doing it that way, among a handful of other 'solutions' that haven't fixed the issue. I am really struggling with this and need a way to fix it that works quick, here is my code:

```<code>Query := TADOQuery.Create(Self);
Query.Connection := ADOConnection;
Query.SQL.Add('INSERT INTO tbl_RFI (Subject) VALUES (:Subject)');
Query.Parameters.ParamByName('Subject').Value := edtSubject.Text;
Query.ExecSQL;
</code>```

I really hope that someone can help me with this,
Thanks.

答: Just add Query.ParamCheck := true  before setting the SQl Text and it should be fine</p>

Body:
I have recently started to learn how to code in Delphi since moving from Python to do a project. I can't seem to find a fix to this issue. I have searched online for a couple of hours now and none of the 'fixes' seem to be working. I have tried using 'Query.ExecSQL', I have tried breaking the code up into segments, I have tried to assign edtSubject.Text to a variable and doing it that way, among a handful of other 'solutions' that haven't fixed the issue. I am really struggling with this and need a way to fix it that works quick, here is my code:

Query := TADOQuery.Create(Self);
Query.Connection := ADOConnection;
Query.SQL.Add('INSERT INTO tbl_RFI (Subject) VALUES (:Subject)');
Query.Parameters.ParamByName('Subject').Value := edtSubject.Text;
Query.ExecSQL;

I really hope that someone can help me with this,
Thanks.


问:
Parsing optional recursive parser runs in infinite recursion
I'm currently writing a parser for ECMAScript 5 (as a toy). The standard dictates how logical or expressions should be parsed:

```<code><LogicalORExpression> :
    <LogicalANDExpression>
    <LogicalORExpression> || <LogicalANDExpression>
</code>```

basicly this is equivalent to

<logicalOrExpression> = [<logicalOrExpression> ||] <LogicalAndExpression>

but how should I parse this without running into an infite loop? My current parser obviously does:

```<code>logicalOrExpression :: Parser LogicalOrExpression
logicalOrExpression = do
    orExpr <- optional $ do
        e <- logicalOrExpression
        _ <- symbol "||"
        return e
    andExpr <- logicalAndExpression
    case orExpr of
        Just e -> return $ LogicalOrExpression (e, andExpr)
        Nothing -> return $ AndExpression andExpr
</code>```

Thanks

答:
That grammar looks equivalent to

```<code><LogicalORExpression> :
    <LogicalANDExpression>
    <LogicalANDExpression> || <LogicalORExpression>
</code>```

which becomes

```<code><LogicalORExpression> :
    <LogicalANDExpression> [|| <LogicalORExpression>]
</code>```

In general, you need to rewrite the grammar in (roughly) LL(1) form, if possible.

Body:
I'm currently writing a parser for ECMAScript 5 (as a toy). The standard dictates how logical or expressions should be parsed:

<LogicalORExpression> :
    <LogicalANDExpression>
    <LogicalORExpression> || <LogicalANDExpression>

basicly this is equivalent to

<logicalOrExpression> = [<logicalOrExpression> ||] <LogicalAndExpression>

but how should I parse this without running into an infite loop? My current parser obviously does:

logicalOrExpression :: Parser LogicalOrExpression
logicalOrExpression = do
    orExpr <- optional $ do
        e <- logicalOrExpression
        _ <- symbol "||"
        return e
    andExpr <- logicalAndExpression
    case orExpr of
        Just e -> return $ LogicalOrExpression (e, andExpr)
        Nothing -> return $ AndExpression andExpr

Thanks

Body:
That grammar looks equivalent to

<LogicalORExpression> :
    <LogicalANDExpression>
    <LogicalANDExpression> || <LogicalORExpression>

which becomes

<LogicalORExpression> :
    <LogicalANDExpression> [|| <LogicalORExpression>]

In general, you need to rewrite the grammar in (roughly) LL(1) form, if possible.