问:
GWT override GSS style in another GSS file
Since my application got larger, I decided that each "module" of my application, will have its own resource file, style file and GSS file. Also styling of for example buttons will be in a different, global GSS file as it is more of an application style, used through the application.

This is not a problem, but when I wanted to do something like this:

```<code>.buttonGroup>.button.active{ background-color: red}
</code>```

in one of the modules, it does not match anything.

Since the button style(buttonGroup, button, active) and behavior (add "active" class on click) is specified in different (global) GSS file, I am not able to change the style of the "active" class.

Here is a simplified example:

```<code>public interface AppResources extends ClientBundle {

    public static AppResources INSTANCE = GWT.create(AppResources.class);

    @Source({"style.gss"})
    AppStyle appStyle();
}
</code>```

Style file:

```<code>public interface AppStyle extends CssResource {

    String buttonGroup();
    String button();
    String active();
}
</code>```

Module:

```<code>public interface ModuleResources extends AppResources{

    public static ModuleResources INSTANCE = GWT.create(ModuleResources.class);

    @Source({"style.gss","module.gss"})
    ModuleStyle moduleStyle();
}
</code>```

Style file:

```<code>public interface ModuleStyle extends AppStyle {
}
</code>```

In GSS files I tried to use @provide and @require (it would not compile without it as it would have missing identifiers or classes).

It then compiles fine, but the buttonGroup, button and even the active class is treated as it belongs to the AppStyle, therefore style.gss styles are used and the rule:

```<code>.buttonGroup>.button.active{ background-color: red}
</code>```

in module.gss is not matching anything as it is probably looking for .hash-ModuleStyle-buttonGroup, .hash-ModuleStyle-button and .hash-ModuleStyle-active classes, whereas the actual styles on the button are .hash-AppStyle-buttonGroup etc.

答:
In the end I solved it by using @external on the classes I wanted to use in different GSS stylesheets.

By using @external all the classes from widgets, which had their own stylesheets, keep their class names unobfuscated, so that they can be overridden in any module stylesheet.

I didn't want to do it before, but that was the only solution that I could think off.

Body:
Since my application got larger, I decided that each "module" of my application, will have its own resource file, style file and GSS file. Also styling of for example buttons will be in a different, global GSS file as it is more of an application style, used through the application.

This is not a problem, but when I wanted to do something like this:

.buttonGroup>.button.active{ background-color: red}

in one of the modules, it does not match anything.

Since the button style(buttonGroup, button, active) and behavior (add "active" class on click) is specified in different (global) GSS file, I am not able to change the style of the "active" class.

Here is a simplified example:

public interface AppResources extends ClientBundle {

    public static AppResources INSTANCE = GWT.create(AppResources.class);

    @Source({"style.gss"})
    AppStyle appStyle();
}

Style file:

public interface AppStyle extends CssResource {

    String buttonGroup();
    String button();
    String active();
}

Module:

public interface ModuleResources extends AppResources{

    public static ModuleResources INSTANCE = GWT.create(ModuleResources.class);

    @Source({"style.gss","module.gss"})
    ModuleStyle moduleStyle();
}

Style file:

public interface ModuleStyle extends AppStyle {
}

In GSS files I tried to use @provide and @require (it would not compile without it as it would have missing identifiers or classes).

It then compiles fine, but the buttonGroup, button and even the active class is treated as it belongs to the AppStyle, therefore style.gss styles are used and the rule:

.buttonGroup>.button.active{ background-color: red}

in module.gss is not matching anything as it is probably looking for .hash-ModuleStyle-buttonGroup, .hash-ModuleStyle-button and .hash-ModuleStyle-active classes, whereas the actual styles on the button are .hash-AppStyle-buttonGroup etc.


来源: stackexchange

问:
How to replace string pattern using sed
I have string pattern like following

abcd(100 efgh)

I would like to change string pattern above into following using sed.

ab(100)

abcd and efgh is fixed string but the number(here is 100) is not fixed, can be any number.
Does anyone have some idea about it and could you give some advice?
I am always thankful for sharing.

答:
Use a capture group to remember the number, use a character class to match it:

```<code>echo 'abcd(100 efgh)' | sed 's/abcd(\([0-9]\+\) efgh)/ab(\1)/'
</code>```

(non-gnu seds might not have +, use [0-9][0-9]* instead.

ContentLicense: CC BY-SA 3.0

Title: How to replace string pattern using sed

Body:
Use a capture group to remember the number, use a character class to match it:

echo 'abcd(100 efgh)' | sed 's/abcd(\([0-9]\+\) efgh)/ab(\1)/'

(non-gnu seds might not have +, use [0-9][0-9]* instead.


问:
Injecting entity manager into managed bean
It is possible to inject entity manager (or its factory) into jsf managed bean using @PersistenceContext (or @PersistenceUnit)?

I Tried it but nothing, I obtain a NullPointerException.

答:
Yes it is possible.  This is the syntax.

```<code>@PersistenceContext
EntityManager em;
</code>```

You need to have a persistence.xml in your project.  Btw:  I'm running Glassfish 3.

After this you can then use methods like em.createNamedQuery.

Also remember the injection takes place after the constructor so if your trying to do database functions in the constructor this will not work.  You will have to add the @PostConstruct annotation to a method.  This is probably the problem your having.

Body:
Yes it is possible.  This is the syntax.

@PersistenceContext
EntityManager em;

You need to have a persistence.xml in your project.  Btw:  I'm running Glassfish 3.

After this you can then use methods like em.createNamedQuery.

Also remember the injection takes place after the constructor so if your trying to do database functions in the constructor this will not work.  You will have to add the @PostConstruct annotation to a method.  This is probably the problem your having.

ContentLicense: CC BY-SA 2.5


问:
Revoking permissions for Azure AD applications
I have an issue similar to this one. After revoking the following permissions from my app (Sign in and read user profile & Read all groups), and reassigning completly different permissions (Read user mail + waiting 20 mins for the new permissions to take effect), my app is still able to query/read the domain's group. I have also tried revoking all permissions => the resulting requiredResourceAccess array in the Manifest file for the application is empty; waited 20 mins for the changes to take effect. => result my application is still able to query the domain's group.
Any explanation is appreciated.</p>

答:
As that case's answer said, after change the permissions in Application registrations, you need to click the Grant Permissions button.

Go to Azure portal> Azure Active Directory> Application registrations > Select your application > Required permissions > Choose the API > Revoke the permissions > Save > Grant permissions

You can go to Enterprise applications to check if it has revoked.

Enterprise Applications > Select your applications > Permissions

If you want to revoke all permissions of the Application, you can just delete it in Enterprise applications.


问:
C++ code without having to declare temporary at the outer scope
Is there any way to write following code without using the temporary "result"?</p>

```<code>result = func();
if(result == -1)
        return func2();
else
    return result;
</code>```

答:
FYI, if your goal is to avoid polluting the outer scope with the temporary name (and you don't want to enclose everything in a {} block), in c++17 we have the if statement with initializer:

```<code>if( auto result = func(); result == -1 )
    return func2();
else
    return result;
</code>```

and, almost(*) just for fun, yet another one-liner could be

```<code>[result=func()]{ return (result == -1) ? func2() : result; }(); // requires c++14, or
[](auto result){ return (result == -1) ? func2() : result; }(func());
</code>```

(*) IMO, such a thing may be useful when you want to focus readability on the logic in the lambda without pollution from initialization statements...

Body:
Is there any way to write following code without using the temporary "result"?

result = func();
if(result == -1)
        return func2();
else
    return result;

Body:
FYI, if your goal is to avoid polluting the outer scope with the temporary name (and you don't want to enclose everything in a {} block), in c++17 we have the if statement with initializer:

if( auto result = func(); result == -1 )
    return func2();
else
    return result;

and, almost(*) just for fun, yet another one-liner could be

[result=func()]{ return (result == -1) ? func2() : result; }(); // requires c++14, or
[](auto result){ return (result == -1) ? func2() : result; }(func());

(*) IMO, such a thing may be useful when you want to focus readability on the logic in the lambda without pollution from initialization statements...


问:
How to deploy a Go web application in Beanstalk with custom project folder structure
I'm new to Go.
I am trying to deploy a simple web project to EB without success.
I would like to deploy a project with the following local structure to Amazon EB:

```<code>$GOPATH
├── bin
├── pkg
└── src
    ├── github.com
    │   ├── AstralinkIO
    │   │   └── api-server <-- project/repository root
    │   │       ├── bin
    │   │       ├── cmd <-- main package
    │   │       ├── pkg
    │   │       ├── static
    │   │       └── vendor
</code>```

But I'm not sure how to do that, when building the command, Amazon is treating api-server as the $GOPATH, and of course import paths are broken.

I read that most of the time it's best to keep all repos under the same workspace, but it makes deployment harder..

I'm using Procfile and Buildfile to customize output path, but I can't find a solution to dependencies.

What is the best way to deploy such project to EB?

答:
Long time has past since I used Beanstalk, so I'm a bit rusty on the details. But basic idea is as follows. AWS Beanstalk support for go is a bit odd by design. It basically extracts your source files into a folder on the server, declares that folder as GOPATH and tries to build your application assuming that your main package is at the root of your GOPATH. Which is not a standard layout for go projects. So your options are:

1) Package your whole GOPATH as "source bundle" for Beanstalk. Then you should be able to write build.sh script to change GOPATH and build it your way. Then call build.sh from your Buildfile.

2) Change your main package to be a regular package (e.g. github.com/AstralinkIO/api-server/cmd). Then create an application.go file at the root of your GOPATH (yes, outside of src, while all actual packages are in src as they should be). Your application.go will become your "package main" and will only contain a main function (which will call your current Main function from github.com/AstralinkIO/api-server/cmd). Should do the trick. Though your mileage might vary.

3) A bit easier option is to use Docker-based Go Platform instead. It still builds your go application on the server with mostly same issues as above, but it's better documented and possibility to test it locally helps a lot with getting configuration and build right. It will also give you some insights into how Beanstalk builds go applications thus helping with options 1 and 2. I used this option myself until I moved to plain EC2 instances. And I still use skills gained as a result of it to build my current app releases using docker.

4) Your best option though (in my humble opinion) is to build your app yourselves and package it as a ready to run binary file. See second bullet point paragraph here

Well, which ever option you choose - good luck!

Body:
I'm new to Go.
I am trying to deploy a simple web project to EB without success.
I would like to deploy a project with the following local structure to Amazon EB:

$GOPATH
├── bin
├── pkg
└── src
    ├── github.com
    │   ├── AstralinkIO
    │   │   └── api-server <-- project/repository root
    │   │       ├── bin
    │   │       ├── cmd <-- main package
    │   │       ├── pkg
    │   │       ├── static
    │   │       └── vendor

But I'm not sure how to do that, when building the command, Amazon is treating api-server as the $GOPATH, and of course import paths are broken.

I read that most of the time it's best to keep all repos under the same workspace, but it makes deployment harder..

I'm using Procfile and Buildfile to customize output path, but I can't find a solution to dependencies.

What is the best way to deploy such project to EB?


问:
How to Populate a dropdown using Enterprise Library 5.0
Is there a simple code to populate a dropdown box using Enterprise Library 5.0 DAAB?

I've tried this, but it is not working:

```<code>cmbOffice.DataSource = _db.ExecuteDataSet(
      CommandType.Text,
      "select office_id, office_name from office").Tables[0];
cmbOffice.DataBind();
</code>```

答:
```<code>DataSet ds = _db.ExecuteDataSet(
    CommandType.Text,
    "select office_id, office_name from office");

cmbOffice.DataSource = ds;
cmbOffice.DataValueField= "office_id";
cmbOffice.DataTextField = "office_name";

cmbOffice.DataBind();
</code>```

Body:
Is there a simple code to populate a dropdown box using Enterprise Library 5.0 DAAB?

I've tried this, but it is not working:

cmbOffice.DataSource = _db.ExecuteDataSet(
      CommandType.Text,
      "select office_id, office_name from office").Tables[0];
cmbOffice.DataBind();


问:
How to create shadow for UICollectionViewCell
I need to create a shadow for the cells inside a UICollectionView. I've subclassed the cells and inside the layoutSubviews I've added the following code:

```<code>-(void)layoutSubviews{

    [super layoutSubviews];

    self.layer.masksToBounds = NO;
    self.layer.shadowOpacity = 0.75f;
    self.layer.shadowRadius = 5.0f;
    self.layer.shadowOffset = CGSizeZero;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;

}
</code>```

But the cells gets higher and this is the result:

If I remove the:

```<code>self.layer.masksToBounds = NO;
</code>```

The cells are shown correctly (with a distance of 10px between them) but the shadow is not visible. What am I doing wrong? Also, is it correct to add the shadow inside the layoutSubviews method?

答:
```<code>    func dropShadow() {
    self.layer.masksToBounds = false
    self.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor
    self.layer.shadowOpacity = 0.5
    self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
    self.layer.shadowRadius = 4.0
    self.layer.cornerRadius = 5.0
}

//Direct Add Shadow to cell

Cell.dropShadow()
</code>```

Body:
I need to create a shadow for the cells inside a UICollectionView. I've subclassed the cells and inside the layoutSubviews I've added the following code:

-(void)layoutSubviews{

    [super layoutSubviews];

    self.layer.masksToBounds = NO;
    self.layer.shadowOpacity = 0.75f;
    self.layer.shadowRadius = 5.0f;
    self.layer.shadowOffset = CGSizeZero;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;

}

But the cells gets higher and this is the result:

If I remove the:

self.layer.masksToBounds = NO;

The cells are shown correctly (with a distance of 10px between them) but the shadow is not visible. What am I doing wrong? Also, is it correct to add the shadow inside the layoutSubviews method?


问:
Is there a way to cap the max size on a STL::map container?
My application can only process up to a certain number of entry in the map structure, how do I specify that limit in my code so that my code does not get overwhelmed (for lack of better term).  Is there a way to specify the max limit when defining the variable of type map?

Thanks

答:
There's no way to set a limit when instantiating the map, though I supposed you could have your own safe guard when accessing it. For example:

```<code>if (mymap.find(a) == mymap.end() and mymap.size() >= MAX_MAP_ALLOWED) {
    throw (runtime_error("map limit exceeded"));
} else {
    mymap[a] = b;
}
</code>```

You could possibly create your own map class that encapsulates these checks.

Body:
There's no way to set a limit when instantiating the map, though I supposed you could have your own safe guard when accessing it. For example:

if (mymap.find(a) == mymap.end() and mymap.size() >= MAX_MAP_ALLOWED) {
    throw (runtime_error("map limit exceeded"));
} else {
    mymap[a] = b;
}

You could possibly create your own map class that encapsulates these checks.


问:
Add item into array without push
Trying to do immutable way of pushing an array into existing array but somehow my code is not working.

```<code>function insertItem(array, action) {
  return [
    ...array.slice(0, action.index),
    action.item,
    ...array.slice(action.index)
  ]
}

const ori_arr = [{
  id: 1,
  name: 'james',
  age: 10
}, {
  id: 2,
  name: 'terrance',
  age: 20
}]

console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))
</code>```

possibly wrong at the index part.

答:
You're passing the parameters incorrectly:

```<code>console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))
</code>```

instead pass it without the action object:

```<code>console.log(insertItem(ori_arr, {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
}))
</code>```

If you tried logging it you'd see that inside your function insertItem you have a param called action, it's value (when you call it) is

action = { action: { index: 1, item: { id: 3, name: 'she', age: 44 }}}

so when you try to access action.item it doesn't exist.

Another solution would be to change your function to

```<code>function insertItem(array, action) {
  return [
    ...array.slice(0, action.action.index),
    action.action.item,
    ...array.slice(action.action.index)
  ]
}
</code>```

Title: Add item into array without push

Body:
Trying to do immutable way of pushing an array into existing array but somehow my code is not working.

function insertItem(array, action) {
  return [
    ...array.slice(0, action.index),
    action.item,
    ...array.slice(action.index)
  ]
}

const ori_arr = [{
  id: 1,
  name: 'james',
  age: 10
}, {
  id: 2,
  name: 'terrance',
  age: 20
}]

console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))

possibly wrong at the index part.

Body:
You're passing the parameters incorrectly:

console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))

instead pass it without the action object:

console.log(insertItem(ori_arr, {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
}))

If you tried logging it you'd see that inside your function insertItem you have a param called action, it's value (when you call it) is

action = { action: { index: 1, item: { id: 3, name: 'she', age: 44 }}}

so when you try to access action.item it doesn't exist.

Another solution would be to change your function to

function insertItem(array, action) {
  return [
    ...array.slice(0, action.action.index),
    action.action.item,
    ...array.slice(action.action.index)
  ]
}


问:
Spring - creating @Bean based on @Service with @Autowired field causes NullPointerException on @Autowired field
I have following Context:

```<code>@Configuration
@ComponentScan
public class MyContext {

    @Bean
    public Logger getLogger() {
        return LoggerFactory.getLogger(MyContext.class);
    }

    @Bean
    @Autowired
    public RequestSpecification getRequestSpecification(RestServiceImpl restService) {
        return restService.getService();
    }
}
</code>```

My inside my service I have @Autowired field (Logger):

```<code>@Service
public class RestServiceImpl {

      @Autowired
      Logger logger;
}
</code>```

And now the problem comes. When I am trying to reuse my RequestSpecification in other service:

```<code>@Service
public class RequestWrapperForMyEndpoint {
    @Value("${rest.service.url}")
    private String SERVICE_URL;

    @Autowired
    private RequestSpecification restService;
}
</code>```

I am running into NullPointerException. Because Logger is not injected into RestServiceImpl class.

What is the reason?

答:
This would rather be a comment, but since I do not have enough points I only can post answers. Here we go:

As such, this code should work, this is how autowiring should be done as such.

Although there is no point in autowiring loggers (as Mick explained), since every log entry will be linked to MyContext you won't be able to tell where it actually comes from (not helpful when debugging), ere are possible solutions for the autowiring issue:

Run the debugger and check if the return value of LoggerFactory.getLogger(MyContext.class) is not null in the first place.

Autowiring only works when the Spring application is actually run and the context is built. Ergo it does not work in unit tests (if this is when it occurs). For testing, you need to run integration tests.

Check if the bean is not overwritten somewhere else in the code.

You did not show what your restService.getService() method looks like. There is a chance, this is where your autowired logger gets lost, since you obviously are not "keeping" the entire autowired restService bean.

Body:
I have following Context:

@Configuration
@ComponentScan
public class MyContext {

    @Bean
    public Logger getLogger() {
        return LoggerFactory.getLogger(MyContext.class);
    }

    @Bean
    @Autowired
    public RequestSpecification getRequestSpecification(RestServiceImpl restService) {
        return restService.getService();
    }
}

My inside my service I have @Autowired field (Logger):

@Service
public class RestServiceImpl {

      @Autowired
      Logger logger;
}

And now the problem comes. When I am trying to reuse my RequestSpecification in other service:

@Service
public class RequestWrapperForMyEndpoint {
    @Value("${rest.service.url}")
    private String SERVICE_URL;

    @Autowired
    private RequestSpecification restService;
}

I am running into NullPointerException. Because Logger is not injected into RestServiceImpl class.

What is the reason?


问:
extracting a variable from the redux store
I need to extract the props from the store in the calculate component and pass the calculation results in the app. I just started using redux.

app.js

```<code>    import React, { Component } from 'react';
    import { connect } from 'react-redux';
    import principalChanged from './src/actions';
    import { Input, Card } from './src/components/common';
    import  { principal2, principal3 } from './src/components/calculate';

      class App extends Component {
        onPrincipalChange(text) {
          this.props.principalChanged(text);
        }
      render() {
        return (
            <Card>
               <Input
                 placeholder="Placeholder"
                 label="Label"
                 onChangeText={this.onPrincipalChange.bind(this)}
                 value={this.props.principal}
                />
              `Current state of the variable: ${this.props.principal}`{/n}
              `New variable: ${principal2}`
              `New variable: ${principal3}`
            </Card>
        );
       }
       }
const mapStateToProps = state => {
   return {
      principal: state.form.principal
   };
};
export default connect(mapStateToProps, {
    principalChanged
})(App);
</code>```

calculate.js

```<code>// call the { principal } variable from the store
// somehow
// maybe I should use mergeProps
export const principal2 = (principal) => {
     return ( { principal * 2 } ); // calculating
};

export const principal3 = () => {
     return ( { principal2 / 4 } ); // calculating
};
</code>```

I don't know how to connect state.principal.props to calculate.js. Maybe I should use mergeProps?

答:
What exactly are you trying to achieve?
Shall principal2 and principal3 be components, or just functions? They are imported from the directory "components", so I assume they are components? If so, you first need to return any kind or component, not only a number. Like:

```<code>export const principal2 = ({ value}) => {
   return <span>{ value * 2 }</span>; // calculating
};
</code>```

Then use the component like:

```<code>New variable: <principal value={anyNumber} />
</code>```

In case of "normal" function use principal like:

```<code>New variable: {principal(anyNumber)}
</code>```

Btw: you don´t need to put the strings in these little quotes "`". You can write

```<code>New variable: {principal3}
</code>```

within your return value of the component.

Body:
I need to extract the props from the store in the calculate component and pass the calculation results in the app. I just started using redux.

app.js

    import React, { Component } from 'react';
    import { connect } from 'react-redux';
    import principalChanged from './src/actions';
    import { Input, Card } from './src/components/common';
    import  { principal2, principal3 } from './src/components/calculate';

      class App extends Component {
        onPrincipalChange(text) {
          this.props.principalChanged(text);
        }
      render() {
        return (
            <Card>
               <Input
                 placeholder="Placeholder"
                 label="Label"
                 onChangeText={this.onPrincipalChange.bind(this)}
                 value={this.props.principal}
                />
              `Current state of the variable: ${this.props.principal}`{/n}
              `New variable: ${principal2}`
              `New variable: ${principal3}`
            </Card>
        );
       }
       }
const mapStateToProps = state => {
   return {
      principal: state.form.principal
   };
};
export default connect(mapStateToProps, {
    principalChanged
})(App);

calculate.js

// call the { principal } variable from the store
// somehow
// maybe I should use mergeProps
export const principal2 = (principal) => {
     return ( { principal * 2 } ); // calculating
};

export const principal3 = () => {
     return ( { principal2 / 4 } ); // calculating
};

I don't know how to connect state.principal.props to calculate.js. Maybe I should use mergeProps?

Body:
What exactly are you trying to achieve?
Shall principal2 and principal3 be components, or just functions? They are imported from the directory "components", so I assume they are components? If so, you first need to return any kind or component, not only a number. Like:

export const principal2 = ({ value}) => {
   return <span>{ value * 2 }</span>; // calculating
};

Then use the component like:

New variable: <principal value={anyNumber} />

In case of "normal" function use principal like:

New variable: {principal(anyNumber)}

Btw: you don´t need to put the strings in these little quotes "`". You can write

New variable: {principal3}

within your return value of the component.


问:
No IntelliSense for C++/CLI in Visual Studio 2010?
I just moved from Visual Studio 2008 to Visual Studio 2010 (final) and noticed one major flaw:

When I try to use AutoComplete in a C++ source file for managed C++, a small note in the footer appears:

IntelliSense for C++/CLI is not available

Uh, has IntelliSense for C++/CLI been dropped from Visual Studio 2010? Is there any way to get this back? It is rather useful...

答:
As mentioned you could install some paid software such as "Visual Assist X from Whole Tomato Software".

or

You could use open source tools that contain intellisense*, one such tool is Qt Creator 3.3.1 (opensource). You have two options, either setup your entire project with Qt to compile using VS2010 compiler, or use Qt to link to your source files and compile with VS2010. You write your code in Qt, save, flip windows to vs2010 and compile and debug.

When changes are saved in Qt, vs2010 will automatically reload the source file in the project and you can compile.


问:
Code Golf: Leibniz formula for Pi
I recently posted one of my favourite interview whiteboard coding questions in "What's your more controversial programming opinion", which is to write a function that computes Pi using the Leibniz formula.

It can be approached in a number of different ways, and the exit condition takes a bit of thought, so I thought it might make an interesting code golf question. Shortest code wins!

Given that Pi can be estimated using the function 4 * (1 - 1/3 + 1/5 - 1/7 + ...) with more terms giving greater accuracy, write a function that calculates Pi to within 0.00001.

Edit: 3 Jan 2008

As suggested in the comments I changed the exit condition to be within 0.00001 as that's what I really meant (an accuracy 5 decimal places is much harder due to rounding and so I wouldn't want to ask that in an interview, whereas within 0.00001 is an easier to understand and implement exit condition).

Also, to answer the comments, I guess my intention was that the solution should compute the number of iterations, or check when it had done enough, but there's nothing to prevent you from pre-computing the number of iterations and using that number. I really asked the question out of interest to see what people would come up with.

OwnerDisplayName: Greg Beech

Title: Code Golf: Leibniz formula for Pi

LastEditorDisplayName: dreeves

Body:
R - 27 chars

sum(4/seq(1,1e6,2)*c(1,-1))


问:
How to evaluate multiple expression in if--elif statement in python?
How to evaluate multiple expression in if--elif in below code snipet.

I am sure its basic syntax issue

```<code>n=5
if n%2 != 0:
    print ("weird")
elif n%2 == 0 && 2 < n && n <5:
    print "Not Weird"
elif n%2 == 0 && 6 < n && n < 20:
    print "Weird"
elif n%2 == 0 && n >20:
    print "NOt Weird"
</code>```

答:
Try this:</p>

```<code>n = 5

if n % 2:
    print("weird")
elif 2 < n < 5:
    print("Not Weird")
elif 6 < n < 20:
    print("Weird")
elif n > 20:
    print("NOt Weird")
</code>```

Body:
How to evaluate multiple expression in if--elif in below code snipet.

I am sure its basic syntax issue

n=5
if n%2 != 0:
    print ("weird")
elif n%2 == 0 && 2 < n && n <5:
    print "Not Weird"
elif n%2 == 0 && 6 < n && n < 20:
    print "Weird"
elif n%2 == 0 && n >20:
    print "NOt Weird"

Body:
Try this:

n = 5

if n % 2:
    print("weird")
elif 2 < n < 5:
    print("Not Weird")
elif 6 < n < 20:
    print("Weird")
elif n > 20:
    print("NOt Weird")


问:
How do I check if an object matches certain rules?
I have an array of similar objects. I need a generic template for writing filter rules for this array.
For example, I have an array of movies:

```<code>const movies = [{
    title: 'movie 1',
    type: 'tv',
    genres: ['comedy', 'romantic']
}, {
    title: 'movie 2',
    type: 'serial',
    genres: ['comedy', 'romantic']
}, {
    title: 'movie 3',
    type: 'tv',
    genres: ['romantic', 'horror']
}]
</code>```

And rule

```<code>// Is Comedy movie
const rule = {
    relation: 'AND',
    items: [{
        property: 'type',
        value: 'tv'
    }, {
        property: 'genres',
        value: 'comedy'
    }]
}
</code>```

Result of checking:

```<code>// An improvised example of checking an object by a rule
checkObjByRule(rule, movies[0]) // -> true
checkObjByRule(rule, movies[1]) // -> false
checkObjByRule(rule, movies[2]) // -> false
</code>```

In real work, the object Movie, is much more complicated, has a number of nested properties. I'm trying to find a ready solution, a library, so that I can create complex rules and check them

答:
You could use an object for relation and take either Array#every for AND or Array#some for OR relation.

var movies = [{ title: 'movie 1', type: 'tv', genres: ['comedy', 'romantic'] }, { title: 'movie 2', type: 'serial', genres: ['comedy', 'romantic'] }, { title: 'movie 3', type: 'tv', genres: ['romantic', 'horror'] }],
    rule = { relation: 'AND', items: [{ property: 'type', value: 'tv' }, { property: 'genres', value: 'comedy' }] },
    result = movies.filter(
        o => rule.items[{ AND: 'every', OR: 'some' }[rule.relation]](
            r => o[r.property].includes(r.value)
        )
    );

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array of similar objects. I need a generic template for writing filter rules for this array.
For example, I have an array of movies:

const movies = [{
    title: 'movie 1',
    type: 'tv',
    genres: ['comedy', 'romantic']
}, {
    title: 'movie 2',
    type: 'serial',
    genres: ['comedy', 'romantic']
}, {
    title: 'movie 3',
    type: 'tv',
    genres: ['romantic', 'horror']
}]

And rule

// Is Comedy movie
const rule = {
    relation: 'AND',
    items: [{
        property: 'type',
        value: 'tv'
    }, {
        property: 'genres',
        value: 'comedy'
    }]
}

Result of checking:

// An improvised example of checking an object by a rule
checkObjByRule(rule, movies[0]) // -> true
checkObjByRule(rule, movies[1]) // -> false
checkObjByRule(rule, movies[2]) // -> false

In real work, the object Movie, is much more complicated, has a number of nested properties. I'm trying to find a ready solution, a library, so that I can create complex rules and check them

Body:
You could use an object for relation and take either Array#every for AND or Array#some for OR relation.

var movies = [{ title: 'movie 1', type: 'tv', genres: ['comedy', 'romantic'] }, { title: 'movie 2', type: 'serial', genres: ['comedy', 'romantic'] }, { title: 'movie 3', type: 'tv', genres: ['romantic', 'horror'] }],
    rule = { relation: 'AND', items: [{ property: 'type', value: 'tv' }, { property: 'genres', value: 'comedy' }] },
    result = movies.filter(
        o => rule.items[{ AND: 'every', OR: 'some' }[rule.relation]](
            r => o[r.property].includes(r.value)
        )
    );

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
how to iterate throught an array of objects and concate the contents
I have the object (obj1) that is posted below. As shown  in it, it contains an array of objects called "favoritePlayers".

what I am trying to do is, to create a function or add an array prototype so that I can iterate through each element in the array separately and get the following output:

"messi plays in barcelona"
"totti plays in roma"

I tried to solve it as shown below but what I get is

```<code>[ 'undefinedplays in[object Object]',
'undefinedplays in[object Object]' ]
</code>```

obj1:

```<code>var obj1 = {
score: [10, 22, 30, 55, 70, 90],
lettersOfMyName: ["a", "m", "r"],
avgScore: null,
favoritePlayers: [
    {
        name: "messi",
        club: "barcelona"
    },

    {
        name: "totti",
        club: "roma"
    }
],

calcAvgScore: function () {
    var sumOfScores = this.score.reduce(function (prev, cur, index, array)
{

        return prev + cur;

    })

    return (sumOfScores / this.score.length);
},

myFavoritePlayersInfo: function () {
    console.log(this.favoritePlayers.join());
},

}
</code>```

my attempts:
    //this code was added outside the scope of obj1

```<code>Array.prototype.concat1 = ( (array) => {
var tempArray = [];

for (var i = 0; i < array.length; i++) {

tempArray[i] = array.slice(i, i+1).name + "plays in" + array.slice(i,
i+1);

}

return tempArray;

});
</code>```

update_1

I added the following lines to obj1:

```<code>getPlaysIn:function() {
    this.favoritePlayers.forEach( (favoritePlayer)=> {
        return favoritePlayer.name + " plays in " + favoritePlayer.club;
</code>```

and I call it as follows:

```<code>console.log(obj1.getPlaysIn());
</code>```

but the results i get is

```<code>undefined
</code>```

答:
var obj1 = {
  score: [10, 22, 30, 55, 70, 90],
  lettersOfMyName: ["a", "m", "r"],
  avgScore: null,
  favoritePlayers: [{
      name: "messi",
      club: "barcelona"
    },

    {
      name: "totti",
      club: "roma"
    }
  ]
}

var a = obj1.favoritePlayers;
for(var i = 0; i<a.length; i++){
console.log(a[i].name+ " " + "plays " +" "+ a[i].club)
};```

Body:
I have the object (obj1) that is posted below. As shown  in it, it contains an array of objects called "favoritePlayers".

what I am trying to do is, to create a function or add an array prototype so that I can iterate through each element in the array separately and get the following output:

"messi plays in barcelona"
"totti plays in roma"

I tried to solve it as shown below but what I get is

[ 'undefinedplays in[object Object]',
'undefinedplays in[object Object]' ]

obj1:

var obj1 = {
score: [10, 22, 30, 55, 70, 90],
lettersOfMyName: ["a", "m", "r"],
avgScore: null,
favoritePlayers: [
    {
        name: "messi",
        club: "barcelona"
    },

    {
        name: "totti",
        club: "roma"
    }
],

calcAvgScore: function () {
    var sumOfScores = this.score.reduce(function (prev, cur, index, array)
{

        return prev + cur;

    })

    return (sumOfScores / this.score.length);
},

myFavoritePlayersInfo: function () {
    console.log(this.favoritePlayers.join());
},

}

my attempts:
    //this code was added outside the scope of obj1

Array.prototype.concat1 = ( (array) => {
var tempArray = [];

for (var i = 0; i < array.length; i++) {

tempArray[i] = array.slice(i, i+1).name + "plays in" + array.slice(i,
i+1);

}

return tempArray;

});

update_1

I added the following lines to obj1:

getPlaysIn:function() {
    this.favoritePlayers.forEach( (favoritePlayer)=> {
        return favoritePlayer.name + " plays in " + favoritePlayer.club;

and I call it as follows:

console.log(obj1.getPlaysIn());

but the results i get is

undefined


问:
Adding Product Programmatically in woocommerce
```<code><?php
/**
* Template name: Create Product
* @package storefront
*/

 $post_id = wp_insert_post( array(
'post_title' => 'Adams Product',
'post_content' => 'Here is content of the post, so this is our great new products description',
'post_status' => 'publish',
'post_type' => "product",
) );
wp_set_object_terms( $post_id, 'simple', 'product_type' );
update_post_meta( $post_id, '_visibility', 'visible' );
update_post_meta( $post_id, '_stock_status', 'instock');
update_post_meta( $post_id, 'total_sales', '0' );
update_post_meta( $post_id, '_downloadable', 'no' );
update_post_meta( $post_id, '_virtual', 'yes' );
update_post_meta( $post_id, '_regular_price', '' );
update_post_meta( $post_id, '_sale_price', '' );
update_post_meta( $post_id, '_purchase_note', '' );
update_post_meta( $post_id, '_featured', 'no' );
update_post_meta( $post_id, '_weight', '' );
update_post_meta( $post_id, '_length', '' );
update_post_meta( $post_id, '_width', '' );
update_post_meta( $post_id, '_height', '' );
update_post_meta( $post_id, '_sku', '' );
update_post_meta( $post_id, '_product_attributes', array() );
update_post_meta( $post_id, '_sale_price_dates_from', '' );
update_post_meta( $post_id, '_sale_price_dates_to', '' );
update_post_meta( $post_id, '_price', '' );
update_post_meta( $post_id, '_sold_individually', '' );
update_post_meta( $post_id, '_manage_stock', 'no' );
update_post_meta( $post_id, '_backorders', 'no' );
update_post_meta( $post_id, '_stock', '' );
?>
</code>```

I am able to create product from front-end in woo-commerce but i need like when user creating their own product then price to be change as per their input data and save in database with respective prices as well as all input data into product,  suppose if user have dog who is approx. between 15-20kg(input by user) and his size(dropdown) is Overweight then according to the user input the price to be calculated. If product is successfully inserted then Add this product to his/her cart automatically and redirect to cart page.

I am attaching my code for inserting a product from a template in front-end.
How can i achieve that?
Thanks in advance.

答:
```<code>// Get informations by form
$weight = $_REQUEST['weight']; // your input
$size = $_REQUEST['size']; // your dropdown
//
// Calcul your price here with $weight and $size
// ...
</code>```

Adapte your metas with your calcul

```<code>$metas = array(
  '_visibility' => 'visible',
  '_stock_status' => 'instock',
  'total_sales' => '0',
  '_downloadable' => 'no',
  '_virtual' => 'yes',
  '_regular_price' => '',
  '_sale_price' => '',
  '_purchase_note' => '',
  '_featured' => 'no',
  '_weight' => '',
  '_length' => '',
  '_width' => '',
  '_height' => '',
  '_sku' => '',
  '_product_attributes' => array(),
  '_sale_price_dates_from' => '',
  '_sale_price_dates_to' => '',
  '_price' => '',
  '_sold_individually' => '',
  '_manage_stock' => 'no',
  '_backorders' => 'no',
  '_stock' => ''
);
foreach ($metas as $key => $value) {
  update_post_meta($post_id, $key, $value);
}

// Add product to cart
WC()->cart->add_to_cart( $post_id );

// redirect
wp_redirect(get_permalink($post_id));
exit();
</code>```

Body:
<?php
/**
* Template name: Create Product
* @package storefront
*/

 $post_id = wp_insert_post( array(
'post_title' => 'Adams Product',
'post_content' => 'Here is content of the post, so this is our great new products description',
'post_status' => 'publish',
'post_type' => "product",
) );
wp_set_object_terms( $post_id, 'simple', 'product_type' );
update_post_meta( $post_id, '_visibility', 'visible' );
update_post_meta( $post_id, '_stock_status', 'instock');
update_post_meta( $post_id, 'total_sales', '0' );
update_post_meta( $post_id, '_downloadable', 'no' );
update_post_meta( $post_id, '_virtual', 'yes' );
update_post_meta( $post_id, '_regular_price', '' );
update_post_meta( $post_id, '_sale_price', '' );
update_post_meta( $post_id, '_purchase_note', '' );
update_post_meta( $post_id, '_featured', 'no' );
update_post_meta( $post_id, '_weight', '' );
update_post_meta( $post_id, '_length', '' );
update_post_meta( $post_id, '_width', '' );
update_post_meta( $post_id, '_height', '' );
update_post_meta( $post_id, '_sku', '' );
update_post_meta( $post_id, '_product_attributes', array() );
update_post_meta( $post_id, '_sale_price_dates_from', '' );
update_post_meta( $post_id, '_sale_price_dates_to', '' );
update_post_meta( $post_id, '_price', '' );
update_post_meta( $post_id, '_sold_individually', '' );
update_post_meta( $post_id, '_manage_stock', 'no' );
update_post_meta( $post_id, '_backorders', 'no' );
update_post_meta( $post_id, '_stock', '' );
?>

I am able to create product from front-end in woo-commerce but i need like when user creating their own product then price to be change as per their input data and save in database with respective prices as well as all input data into product,  suppose if user have dog who is approx. between 15-20kg(input by user) and his size(dropdown) is Overweight then according to the user input the price to be calculated. If product is successfully inserted then Add this product to his/her cart automatically and redirect to cart page.

I am attaching my code for inserting a product from a template in front-end.
How can i achieve that?
Thanks in advance.

Body:
// Get informations by form
$weight = $_REQUEST['weight']; // your input
$size = $_REQUEST['size']; // your dropdown
//
// Calcul your price here with $weight and $size
// ...

Adapte your metas with your calcul

$metas = array(
  '_visibility' => 'visible',
  '_stock_status' => 'instock',
  'total_sales' => '0',
  '_downloadable' => 'no',
  '_virtual' => 'yes',
  '_regular_price' => '',
  '_sale_price' => '',
  '_purchase_note' => '',
  '_featured' => 'no',
  '_weight' => '',
  '_length' => '',
  '_width' => '',
  '_height' => '',
  '_sku' => '',
  '_product_attributes' => array(),
  '_sale_price_dates_from' => '',
  '_sale_price_dates_to' => '',
  '_price' => '',
  '_sold_individually' => '',
  '_manage_stock' => 'no',
  '_backorders' => 'no',
  '_stock' => ''
);
foreach ($metas as $key => $value) {
  update_post_meta($post_id, $key, $value);
}

// Add product to cart
WC()->cart->add_to_cart( $post_id );

// redirect
wp_redirect(get_permalink($post_id));
exit();


问:
Double null value union php
I have a question about the null value with union i have this code

```<code>SELECT NULL,NULL,username, omschrijving, datum, project ,opdrachtgever ,tijd_van,tijd_tot,TIME_FORMAT(TIMEDIFF(tijd_tot,tijd_van), '%H:%i') as nosearch_diff
        FROM uren ur
        JOIN projecten AS pr ON pr.project_id = ur.project_id
        JOIN user AS us ON us.userid = ur.userid
        JOIN opdrachtgever AS og ON pr.opdrachtgever_id = og.opdrachtgever_id
        UNION
        SELECT  materiaal,afdeling,username, omschrijving, datum, project  ,opdrachtgever ,tijd_van,tijd_tot,TIME_FORMAT(TIMEDIFF(tijd_tot,tijd_van), '%H:%i') as nosearch_diff
        FROM materiaal AS ma
        JOIN projecten AS pr ON pr.project_id = ma.project_id
        JOIN user AS us ON us.userid = ma.userid
        JOIN opdrachtgever AS op ON op.opdrachtgever_id = pr.opdrachtgever_id
        JOIN afdeling AS af ON af.afdeling_id = ma.afdeling_id
        JOIN materiaalnaam AS mt ON mt.materiaalnaam_id = ma.materiaalnaam_id
</code>```

the query is working fine but i have 1 problem. The first query has a double NULL value and it refers to the second query materiaal and afdeling
but if i want to display it it only shows the value from afdelingen in the first NULL and the second NULL for example:

lets say that afdeling = Shipping and materiaal Boat.

it display's like this:

```<code>NULL : Shipping

NULL : Shipping
</code>```

But i want it to display like:

```<code>NULL : Shipping

NULL : Boat
</code>```

does anybody know how to fix this issue

Thanks,
Kevin

答:
I fixed it i have just give them NULL value a name
example:

```<code>NULL AS materiaal ,NULL AS afdeling
</code>```

This is the way how you can fix it.

Thanks Guys!

Title: Double null value union php

Body:
I have a question about the null value with union i have this code

SELECT NULL,NULL,username, omschrijving, datum, project ,opdrachtgever ,tijd_van,tijd_tot,TIME_FORMAT(TIMEDIFF(tijd_tot,tijd_van), '%H:%i') as nosearch_diff
        FROM uren ur
        JOIN projecten AS pr ON pr.project_id = ur.project_id
        JOIN user AS us ON us.userid = ur.userid
        JOIN opdrachtgever AS og ON pr.opdrachtgever_id = og.opdrachtgever_id
        UNION
        SELECT  materiaal,afdeling,username, omschrijving, datum, project  ,opdrachtgever ,tijd_van,tijd_tot,TIME_FORMAT(TIMEDIFF(tijd_tot,tijd_van), '%H:%i') as nosearch_diff
        FROM materiaal AS ma
        JOIN projecten AS pr ON pr.project_id = ma.project_id
        JOIN user AS us ON us.userid = ma.userid
        JOIN opdrachtgever AS op ON op.opdrachtgever_id = pr.opdrachtgever_id
        JOIN afdeling AS af ON af.afdeling_id = ma.afdeling_id
        JOIN materiaalnaam AS mt ON mt.materiaalnaam_id = ma.materiaalnaam_id

the query is working fine but i have 1 problem. The first query has a double NULL value and it refers to the second query materiaal and afdeling
but if i want to display it it only shows the value from afdelingen in the first NULL and the second NULL for example:

lets say that afdeling = Shipping and materiaal Boat.

it display's like this:

NULL : Shipping

NULL : Shipping

But i want it to display like:

NULL : Shipping

NULL : Boat

does anybody know how to fix this issue

Thanks,
Kevin

Body:
I fixed it i have just give them NULL value a name
example:

NULL AS materiaal ,NULL AS afdeling

This is the way how you can fix it.

Thanks Guys!


问:
Ionic 2 Alert customization
I want to customize my alerts in Ionic 2. I know that I can do it globally in the variables.scss, but I want to modify a specific one, in a specific page.

I tried cssClass in the alert code, I tried other different things, that work, but globally, not for a specific one.

Is there any way to do it?

答:
Edit all your AlertController.create methods to look like this:

```<code>const alert = this.alertCtrl.create({
    title: title,
    subTitle: msg,
    buttons: ['OK'],
    cssClass: 'alertCustomCss' // <- added this
});
</code>```

And add this to app.scss:

```<code>.alertCustomCss {
    // text color for basic alerts
    color: white;

    // alert modal page bg color. Warning this will remove the alert transparency
    background-color: color($colors, dark, base);

    button {
        color: white !important; // button text color
        background-color: color($colors, secondary, base) !important;
            //button bg color
    }

    .alert-message {
        color: white; // text color for confirm alerts
    }

    .alert-wrapper {
        background-color: color($colors, dark, base); // bg color of alert content
    }
  }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Ionic 2 Alert customization

Body:
Edit all your AlertController.create methods to look like this:

const alert = this.alertCtrl.create({
    title: title,
    subTitle: msg,
    buttons: ['OK'],
    cssClass: 'alertCustomCss' // <- added this
});

And add this to app.scss:

.alertCustomCss {
    // text color for basic alerts
    color: white;

    // alert modal page bg color. Warning this will remove the alert transparency
    background-color: color($colors, dark, base);

    button {
        color: white !important; // button text color
        background-color: color($colors, secondary, base) !important;
            //button bg color
    }

    .alert-message {
        color: white; // text color for confirm alerts
    }

    .alert-wrapper {
        background-color: color($colors, dark, base); // bg color of alert content
    }
  }


问:
checking analytics setup for page I do not own
I'm a consumer data analyst who is not very familiar to coding other than occasional encounters with HTML and Python, and I'm just starting with the coding part of Web Analytics. In particular, I need to learn about checking websites I don't own (therefore I don't have access to their Analytics accounts) for tracking info, but it has been phenomenally hard to find information on which tracking function each component of code stand for, or to what extent it is visible from the page source.

For a project, here is a page I'm trying to check for Google Analytics/Tag Manager/alternative analytics setup, and see what is exactly being tracked on it. Other than the source code, I checked it with Ghostery, which gave me this Tag Manager code page. Is it possible to check tracking info from these two (events, pageviews, URI and how many custom dimensions there is, specifically), and which part of the code includes that info (particularly URI and dimension info - the first two, I have more idea about)?

This is a page I'm also looking into. I can see that this one has Google Analytics/Tag manager, but again, I can't make sure of what is being tracked, and whether the Analytics/Tag Manager setup is looking -potentially- problematic in any way. Here is the Tag Manager page for this one that I obtained through Ghostery.

Any help would be much appreciated...

答:
Looks like what you are looking for is Google Tag Assistant extension for google chrome: https://get.google.com/tagassistant/

you can download it from here: https://chrome.google.com/webstore/detail/tag-assistant-by-google/kejbdjndbnbjgmefkgdddjlbokphdefk?hl=en

When you install it it will appear as icon on any page you visit and it will show you all GA implementations on a page:

You can select tracking ID you are interested in and it will tell you how many Page Views/events were fired for that particular tracking ID only:

Then you can select individual tracking event/page view and see all data that are being sent with that tracking request. Just Click on URLs and click the icon to put the data in table:

Here "cd" stands for Custom Dimension, so here you can clearly see 2 custom dimensions that are being tracked:

Hope this helps, good luck!


问:
Null pointer exception while trying to upload a CSV file to the server
I am trying to upload a csv file to the server. Below is my code in html:

```<code><form method="post" id="uploadCSV" enctype="multipart/form-data">
    File to upload: <input type="file" id="uploadfile" name="file" accept="text/csv">

 <input type="submit" value="Upload" id="uploadcsv" ng-click="uploadCSV()"> Press here to upload the file!
</form>
</code>```

And my JS:-

```<code> $scope.uploadCSV  = function()

{

        var fileToLoad = document.getElementById("uploadfile").files[0];

        var csvreporturl = "/api/oel/csv";
        $http.post(csvreporturl, fileToLoad).then(function(response, status) {
           console.log("posted:",response);
        });

  }
</code>```

Finally the controller in Spring Boot:-

```<code>@RequestMapping(value = "/api/oel/csv", method = RequestMethod.POST)

 String uploadFileHandler(@RequestBody MultipartFile fileToLoad) throws FileNotFoundException, IOException

{

        String name = fileToLoad.getName();
        if (!fileToLoad.isEmpty()) {
            try {
                byte[] bytes = fileToLoad.getBytes();

                // Creating the directory to store file
                //String rootPath = System.getProperty("catalina.home");
                File dir = new File("../dashboard-0.0.12/oel");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath()
                        + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));

                stream.write(bytes);
                stream.close();

                return "You successfully uploaded file=" + name;
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name
                    + " because the file was empty.";
        }
    }
</code>```

I am facing below error:-

Failed to load resource: the server responded with a status of 500
  (HTTP/1.1 500)

Possibly unhandled rejection:
  {"data":{"timestamp":1510643953084,"status":500,"error":"Internal
  Server
  Error","exception":"java.lang.NullPointerException","message":"No
  message
  available","path":"/api/oel/csv"},"status":500,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/oel/csv","data":{},"headers":{"Accept":"application/json,
  text/plain,
  /","Content-Type":"application/json;charset=utf-8"}},"statusText":"HTTP/1.1
  500"}

Could someone please help?

Thanks

答:
I would recommend this : Apache Commons FileUpload</p>

```<code>if (ServletFileUpload.isMultipartContent(request)) {
    FileItemFactory factoryItem = new DiskFileItemFactory();
    ServletFileUpload uploadFile = new ServletFileUpload(factoryItem);

    try {
        List items = uploadFile.parseRequest(request);
        Iterator iterator = items.iterator();
        while (iterator.hasNext()) {
            FileItem item = (FileItem) iterator.next();

            if (!item.isFormField()) {
                String fileName = item.getName();

                String root = getServletContext().getRealPath("/");
                File path = new File(root + "/uploads");
                if (!path.exists()) {
                    boolean status = path.mkdirs();
                }

                File uploadedFile = new File(path + "/" + fileName);
                System.out.println(uploadedFile.getAbsolutePath());
                item.write(uploadedFile);
            }
        }
    } catch (FileUploadException ex) {
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
</code>```

Body:
I am trying to upload a csv file to the server. Below is my code in html:

<form method="post" id="uploadCSV" enctype="multipart/form-data">
    File to upload: <input type="file" id="uploadfile" name="file" accept="text/csv">

 <input type="submit" value="Upload" id="uploadcsv" ng-click="uploadCSV()"> Press here to upload the file!
</form>

And my JS:-

 $scope.uploadCSV  = function()

{

        var fileToLoad = document.getElementById("uploadfile").files[0];

        var csvreporturl = "/api/oel/csv";
        $http.post(csvreporturl, fileToLoad).then(function(response, status) {
           console.log("posted:",response);
        });

  }

Finally the controller in Spring Boot:-

@RequestMapping(value = "/api/oel/csv", method = RequestMethod.POST)

 String uploadFileHandler(@RequestBody MultipartFile fileToLoad) throws FileNotFoundException, IOException

{

        String name = fileToLoad.getName();
        if (!fileToLoad.isEmpty()) {
            try {
                byte[] bytes = fileToLoad.getBytes();

                // Creating the directory to store file
                //String rootPath = System.getProperty("catalina.home");
                File dir = new File("../dashboard-0.0.12/oel");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath()
                        + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));

                stream.write(bytes);
                stream.close();

                return "You successfully uploaded file=" + name;
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name
                    + " because the file was empty.";
        }
    }

I am facing below error:-

Failed to load resource: the server responded with a status of 500
  (HTTP/1.1 500)

Possibly unhandled rejection:
  {"data":{"timestamp":1510643953084,"status":500,"error":"Internal
  Server
  Error","exception":"java.lang.NullPointerException","message":"No
  message
  available","path":"/api/oel/csv"},"status":500,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/oel/csv","data":{},"headers":{"Accept":"application/json,
  text/plain,
  /","Content-Type":"application/json;charset=utf-8"}},"statusText":"HTTP/1.1
  500"}

Could someone please help?

Thanks

Body:
I would recommend this : Apache Commons FileUpload

if (ServletFileUpload.isMultipartContent(request)) {
    FileItemFactory factoryItem = new DiskFileItemFactory();
    ServletFileUpload uploadFile = new ServletFileUpload(factoryItem);

    try {
        List items = uploadFile.parseRequest(request);
        Iterator iterator = items.iterator();
        while (iterator.hasNext()) {
            FileItem item = (FileItem) iterator.next();

            if (!item.isFormField()) {
                String fileName = item.getName();

                String root = getServletContext().getRealPath("/");
                File path = new File(root + "/uploads");
                if (!path.exists()) {
                    boolean status = path.mkdirs();
                }

                File uploadedFile = new File(path + "/" + fileName);
                System.out.println(uploadedFile.getAbsolutePath());
                item.write(uploadedFile);
            }
        }
    } catch (FileUploadException ex) {
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}


问:
JMeter BeanShell - Loop through values
I try to use variables from an array as Path for HTTP Request. Path should be like this: mypath/${act_value}

```<code>String[] numbers = mylist.split(",");
String act_value;

for (int i = 1; i <= 25; i++) {
    vars.put(numbers[i], act_value);
}
</code>```

mylist is given as output of an extractor, comma separated string: mylist=123,456,343,909

HTTP Request state cannot access to this variable, I get error:

java.net.URISyntaxException: Illegal character in path

答:
Amend your code to look like:

```<code>String myList = "123,456,343,909";
String[] numbers = myList.split(",");
for (int i = 0; i < numbers.length; i++) {
    vars.put("number_" + i, numbers[i]);
}
</code>```

Add ForEach Controller somewhere after this script and configure it as follows:

Input variable prefix: number

Output variable name: act_value

Put your HTTP Request sampler as a child of the ForEach Controller

Your HTTP Request will be executed for each value in the myList

Also consider switching to JSR223 Test Elements and Groovy language, in the majority of cases valid Beanshell code will be valid Groovy code but performance will be much higher.

Title: JMeter BeanShell - Loop through values

Body:
I try to use variables from an array as Path for HTTP Request. Path should be like this: mypath/${act_value}

String[] numbers = mylist.split(",");
String act_value;

for (int i = 1; i <= 25; i++) {
    vars.put(numbers[i], act_value);
}

mylist is given as output of an extractor, comma separated string: mylist=123,456,343,909

HTTP Request state cannot access to this variable, I get error:

java.net.URISyntaxException: Illegal character in path

Body:
Amend your code to look like:

String myList = "123,456,343,909";
String[] numbers = myList.split(",");
for (int i = 0; i < numbers.length; i++) {
    vars.put("number_" + i, numbers[i]);
}

Add ForEach Controller somewhere after this script and configure it as follows:

Input variable prefix: number

Output variable name: act_value

Put your HTTP Request sampler as a child of the ForEach Controller

Your HTTP Request will be executed for each value in the myList

Also consider switching to JSR223 Test Elements and Groovy language, in the majority of cases valid Beanshell code will be valid Groovy code but performance will be much higher.


问:
MySQL select AND statement
I have a MySQL database like that:

```
Id | Name
1  | term1
1  | term2
1  | term3
2  | term4
2  | term5
2  | term6
```

I want to select ID that contains term1 AND term3.

Or, for example, term4 AND term5 AND term6.

How can I do that?
Any help would be greatly appreciated, thanks.

答:
Below query would give you all Id where Name is 'term1'

```<code>SELECT Id from table where Name in ('term1');
</code>```

To fetch Id having term1 or term3

```<code>SELECT Id from table where Name in ('term1', 'term3');
</code>```

Title: MySQL select AND statement

Body:
I have a MySQL database like that:

Id | Name
1  | term1
1  | term2
1  | term3
2  | term4
2  | term5
2  | term6

I want to select ID that contains term1 AND term3.

Or, for example, term4 AND term5 AND term6.

How can I do that?
Any help would be greatly appreciated, thanks.

Body:
Below query would give you all Id where Name is 'term1'

SELECT Id from table where Name in ('term1');

To fetch Id having term1 or term3

SELECT Id from table where Name in ('term1', 'term3');


问:
How to create a single color image using ImageView in android programmatically?
Is there any way to create an image using ImageView containing a solid single color programmatically?</p>

答:
You can use View or if you want to use ImageView then you can use any single color image in background.

```<code><View
   android:id="@+id/view_image"
   android:layout_width="100dp"
   android:layout_height="100dp"
   android:background="#ff0000 />
</code>```

With help of view id you can change color at any instance like this.

From Java(programatically)

```<code>View singlecolorImage= (View) findViewById(R.id.linear);
singlecolorImage.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
</code>```

Body:
You can use View or if you want to use ImageView then you can use any single color image in background.

<View
   android:id="@+id/view_image"
   android:layout_width="100dp"
   android:layout_height="100dp"
   android:background="#ff0000 />

With help of view id you can change color at any instance like this.

From Java(programatically)

View singlecolorImage= (View) findViewById(R.id.linear);
singlecolorImage.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));


问:
How to deserialise JSON datetime with nanosecond precision using gson
I'm trying to deserialise a JSON object using gson, but having issues when it comes to dates. The date is deserialised from the JSON object, but because the value in the JSON object is in nanoseconds, the value I get is slightly off of the expected value.

See the following code

JSONClass

```<code>public class JSONClass {
    private Date timestamp;

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }
}
</code>```

Main

```<code>public class GsonTestApplication {
    public static void main(String[] args) {
        final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
        final String responseJSON = "{ \"timestamp\":\"2017-11-09 11:07:20.079364+00\" }";
        final JSONClass foo = gson.fromJson(responseJSON, new TypeToken<JSONClass>(){}.getType());
        System.out.println(foo.getTimestamp().toString());
    }
}
</code>```

The output of the application is

```<code>Thu Nov 09 11:08:39 GMT 2017
</code>```

When I expect it to be

```<code>Thu Nov 09 11:07:20 GMT 2017
</code>```

I don't care about the nanosecond precision, so I'm happy for this to be truncated, but as I don't have control over the JSON format, I'm not sure the best way to do this.

How can I get gson to deserialise the date correctly?

答:
This is an issue with the precision available in Date, and with Java 8 it's best to use LocalDateTime. This also means that you will need a TypeAdapter as Gson doesn't work very well with LocalDateTime. This type adapter needs to be registered with Gson to deserialize (and potentially serialize) LocalDateTime objects from Strings.

Something like the below should give you what you need.

JSONClass

```<code>public class JSONClass {
    private LocalDateTime timestamp;

    public LocalDateTime getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(LocalDateTime timestamp) {
        this.timestamp = timestamp;
    }
}
</code>```

LocalDateTimeDeserialiser

```<code>static class LocalDateTimeDeserializer implements JsonDeserializer<LocalDateTime> {

        private DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        LocalDateTimeDeserializer(String datePattern) {
            this.formatter = DateTimeFormatter.ofPattern(datePattern);
        }

        @Override
        public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return LocalDateTime.parse(json.getAsString(), formatter);
        }
</code>```

Main

```<code>public class GsonTestApplication {
    public static void main(String[] args) {
        final Gson gson = new GsonBuilder().(LocalDateTime.class, new LocalDateTimeDeserializer("yyyy-MM-dd HH:mm:ss.SSSSSSx")).create();
        final String responseJSON = "{ \"timestamp\":\"2017-11-09 11:07:20.079364+00\" }";
        final JSONClass foo = gson.fromJson(responseJSON, new TypeToken<JSONClass>(){}.getType());
        System.out.println(foo.getTimestamp().toString());
    }
}
</code>```

Body:
I'm trying to deserialise a JSON object using gson, but having issues when it comes to dates. The date is deserialised from the JSON object, but because the value in the JSON object is in nanoseconds, the value I get is slightly off of the expected value.

See the following code

JSONClass

public class JSONClass {
    private Date timestamp;

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }
}

Main

public class GsonTestApplication {
    public static void main(String[] args) {
        final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
        final String responseJSON = "{ \"timestamp\":\"2017-11-09 11:07:20.079364+00\" }";
        final JSONClass foo = gson.fromJson(responseJSON, new TypeToken<JSONClass>(){}.getType());
        System.out.println(foo.getTimestamp().toString());
    }
}

The output of the application is

Thu Nov 09 11:08:39 GMT 2017

When I expect it to be

Thu Nov 09 11:07:20 GMT 2017

I don't care about the nanosecond precision, so I'm happy for this to be truncated, but as I don't have control over the JSON format, I'm not sure the best way to do this.

How can I get gson to deserialise the date correctly?

Body:
This is an issue with the precision available in Date, and with Java 8 it's best to use LocalDateTime. This also means that you will need a TypeAdapter as Gson doesn't work very well with LocalDateTime. This type adapter needs to be registered with Gson to deserialize (and potentially serialize) LocalDateTime objects from Strings.

Something like the below should give you what you need.

JSONClass

public class JSONClass {
    private LocalDateTime timestamp;

    public LocalDateTime getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(LocalDateTime timestamp) {
        this.timestamp = timestamp;
    }
}

LocalDateTimeDeserialiser

static class LocalDateTimeDeserializer implements JsonDeserializer<LocalDateTime> {

        private DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        LocalDateTimeDeserializer(String datePattern) {
            this.formatter = DateTimeFormatter.ofPattern(datePattern);
        }

        @Override
        public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return LocalDateTime.parse(json.getAsString(), formatter);
        }

Main

public class GsonTestApplication {
    public static void main(String[] args) {
        final Gson gson = new GsonBuilder().(LocalDateTime.class, new LocalDateTimeDeserializer("yyyy-MM-dd HH:mm:ss.SSSSSSx")).create();
        final String responseJSON = "{ \"timestamp\":\"2017-11-09 11:07:20.079364+00\" }";
        final JSONClass foo = gson.fromJson(responseJSON, new TypeToken<JSONClass>(){}.getType());
        System.out.println(foo.getTimestamp().toString());
    }
}


问:
Extra NotifyIcon shown in system tray
I'm having an issue with an app where my NotifyIcon displays an extra icon. The steps to reproduce it are easy, but the problem is that the extra icon shows up after any of the actual codebehind we've added fires. Put simply, clicking a button triggers execution of method FooBar() which runs all the way through fine but its primary duty is to fire a backgroundworker to log into another of our apps. It only appears if this particular button is clicked.

Strangely enough, we have a WndProc method override and if I step through until the extra NotifyIcon appears, it always appears during this method so something else beyond the codebehind must be triggering the behavior. Our WndProc method is currently (although I don't think it's caused by the WndProc):

```<code>Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)

    'Check for WM_COPYDATA message from other app or drag/drop action and handle message
    If m.Msg = NativeMethods.WM_COPYDATA Then
      ' get the standard message structure from lparam
      Dim CD As NativeMethods.COPYDATASTRUCT = m.GetLParam(GetType(NativeMethods.COPYDATASTRUCT))

      'setup byte array
      Dim B(CD.cbData) As Byte

      'copy data from memory into array
      Runtime.InteropServices.Marshal.Copy(New IntPtr(CD.lpData), B, 0, CD.cbData)

      'Get message as string and process
      ProcessWMCopyData(System.Text.Encoding.Default.GetString(B))

      'empty array
      Erase B

      'set message result to 'true', meaning message handled
      m.Result = New IntPtr(1)
    End If

    'pass on result and all messages not handled by this app
    MyBase.WndProc(m)
  End Sub
</code>```

The only place in the code where the NotifyIcon in question is manipulated at all is in the following event handler (again, don't think this is the culprit, but just for more info):

```<code>Private Sub TrayIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TrayIcon.MouseDoubleClick
    If Me.Visible Then
      Me.Hide()
    Else
      PositionBottomRight()
      Me.Show()
    End If
  End Sub
</code>```

The backgroundworker's DoWork is as follows (just a class call to log in to our other app, but again just for info):

```<code>Private Sub LoginBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles LoginBackgroundWorker.DoWork
    Settings.IsLoggedIn = _wdService.LogOn(Settings.UserName, Settings.Password)
End Sub
</code>```

Does anyone else have ideas on what might be causing this or how to possibly further debug this? I've been banging my head on this without seeing a pattern so another set of eyes would be extremely appreciated. :) I've posted this on MSDN winforms forums as well and have had no luck there so far either.

答: I remember seeing something like this years ago in an application that instantiated a new NotifyIcon without disposing the previous instance.

Title: Extra NotifyIcon shown in system tray

Body:
I'm having an issue with an app where my NotifyIcon displays an extra icon. The steps to reproduce it are easy, but the problem is that the extra icon shows up after any of the actual codebehind we've added fires. Put simply, clicking a button triggers execution of method FooBar() which runs all the way through fine but its primary duty is to fire a backgroundworker to log into another of our apps. It only appears if this particular button is clicked.

Strangely enough, we have a WndProc method override and if I step through until the extra NotifyIcon appears, it always appears during this method so something else beyond the codebehind must be triggering the behavior. Our WndProc method is currently (although I don't think it's caused by the WndProc):

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)

    'Check for WM_COPYDATA message from other app or drag/drop action and handle message
    If m.Msg = NativeMethods.WM_COPYDATA Then
      ' get the standard message structure from lparam
      Dim CD As NativeMethods.COPYDATASTRUCT = m.GetLParam(GetType(NativeMethods.COPYDATASTRUCT))

      'setup byte array
      Dim B(CD.cbData) As Byte

      'copy data from memory into array
      Runtime.InteropServices.Marshal.Copy(New IntPtr(CD.lpData), B, 0, CD.cbData)

      'Get message as string and process
      ProcessWMCopyData(System.Text.Encoding.Default.GetString(B))

      'empty array
      Erase B

      'set message result to 'true', meaning message handled
      m.Result = New IntPtr(1)
    End If

    'pass on result and all messages not handled by this app
    MyBase.WndProc(m)
  End Sub

The only place in the code where the NotifyIcon in question is manipulated at all is in the following event handler (again, don't think this is the culprit, but just for more info):

Private Sub TrayIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TrayIcon.MouseDoubleClick
    If Me.Visible Then
      Me.Hide()
    Else
      PositionBottomRight()
      Me.Show()
    End If
  End Sub

The backgroundworker's DoWork is as follows (just a class call to log in to our other app, but again just for info):

Private Sub LoginBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles LoginBackgroundWorker.DoWork
    Settings.IsLoggedIn = _wdService.LogOn(Settings.UserName, Settings.Password)
End Sub

Does anyone else have ideas on what might be causing this or how to possibly further debug this? I've been banging my head on this without seeing a pattern so another set of eyes would be extremely appreciated. :) I've posted this on MSDN winforms forums as well and have had no luck there so far either.


问:
cucumber jvm close browser after running all features
I'm testing a Spring Boot app using Cucumber-JVM and Selenium. I'm defining a web driver bean and passing a destroy method to quit (shutdown the webdriver and all instances of Chrome) but it is leaving the browser open.

```<code>@Configuration
@ComponentScan(basePackages = "com.rodmccutcheon.pensionator.bdd")
public class CucumberConfig {

    @Bean(destroyMethod = "quit")
    public WebDriver webDriver() {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        return new ChromeDriver();
    }

}
</code>```

I've basically copied an example from the Cucumber for Java book. The difference is they use xml configuration and I've opted for Java configuration.

```<code><bean class="org.openqa.selenium.support.events.EventFiringWebDriver" destroy-method="quit">
    <constructor-arg>
        <bean class="org.openqa.selenium.firefox.FirefoxDriver" />
    </constructor-arg>
</bean>
</code>```

How do I get the browser to close at the end of all tests?

答:
do you have the following code in your java class ?

```<code>public void quit()  {
      driver.quit();
    }
</code>```

In your bean definition, you are initialising the driver. By convention , you should use init-method attribute for setup and destroy-method attribute for teardown.

the bean should look like this.

```<code>WebDriver driver;

public void initDriver(){
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
driver = new ChromeDriver();
}

public void quit(){
driver.quit();
}

@Bean(init-method="initDriver" , destroy-Method = "quit")
    public void testUrl() {
    driver.get("https://www.stackoverflow.com");
    driver.getTitle();
    }
</code>```

Body:
I'm testing a Spring Boot app using Cucumber-JVM and Selenium. I'm defining a web driver bean and passing a destroy method to quit (shutdown the webdriver and all instances of Chrome) but it is leaving the browser open.

@Configuration
@ComponentScan(basePackages = "com.rodmccutcheon.pensionator.bdd")
public class CucumberConfig {

    @Bean(destroyMethod = "quit")
    public WebDriver webDriver() {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        return new ChromeDriver();
    }

}

I've basically copied an example from the Cucumber for Java book. The difference is they use xml configuration and I've opted for Java configuration.

<bean class="org.openqa.selenium.support.events.EventFiringWebDriver" destroy-method="quit">
    <constructor-arg>
        <bean class="org.openqa.selenium.firefox.FirefoxDriver" />
    </constructor-arg>
</bean>

How do I get the browser to close at the end of all tests?

Body:
do you have the following code in your java class ?

public void quit()  {
      driver.quit();
    }

In your bean definition, you are initialising the driver. By convention , you should use init-method attribute for setup and destroy-method attribute for teardown.

the bean should look like this.

WebDriver driver;

public void initDriver(){
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
driver = new ChromeDriver();
}

public void quit(){
driver.quit();
}

@Bean(init-method="initDriver" , destroy-Method = "quit")
    public void testUrl() {
    driver.get("https://www.stackoverflow.com");
    driver.getTitle();
    }


问:
Join arrays expression in ECMAScript 2016
I am new to JavaScript. I need to write simple script which should join several arrays into one. I found this example:

```<code>var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);
</code>```

But I have more than two arrays.
Is it possible to concat several arrays in one expression?

答:
The Array method concat() returns the concatenation result which you can in turn use for your next concatenation.

If you have a static list of arrays (3 for example):

```<code>let result = arr1.concat(arr2).concat(arr3);
</code>```

If you have an array of arrays:

```<code>let result = [];
for (let i = 0; i < bigArr.length; i++) {
    result = result.concat(bigArr[i]);
}
</code>```

Body:
I am new to JavaScript. I need to write simple script which should join several arrays into one. I found this example:

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);

But I have more than two arrays.
Is it possible to concat several arrays in one expression?

Body:
The Array method concat() returns the concatenation result which you can in turn use for your next concatenation.

If you have a static list of arrays (3 for example):

let result = arr1.concat(arr2).concat(arr3);

If you have an array of arrays:

let result = [];
for (let i = 0; i < bigArr.length; i++) {
    result = result.concat(bigArr[i]);
}


问:
Create New Page in Orchard Module
How do I create a new page in orchard module? I have one page and controller in orchard, but how to add a new page in the route module?</p>

```<code>        public IEnumerable<RouteDescriptor> GetRoutes() {
        return new[] {
            new RouteDescriptor {
                Priority = 5,
                Route = new Route(
                    "BlogX", // this is the name of the page url
                    new RouteValueDictionary {
                        {"area", "BlogX"}, // this is the name of your module
                        {"controller", "Home"},
                        {"action", "Index"}
                    },
                    new RouteValueDictionary(),
                    new RouteValueDictionary {
                        {"area", "BlogX"} // this is the name of your module
                    },
                    new MvcRouteHandler())
            }
        };
    }
</code>```

答: This should be easy. Inject an instance of Orchard.ContentManagement.IContentManager to your controller and then simply call ContentManager.New("YourContentType"). Also have a look at the other methods available for the content manager like Publish() which you may need to call also.

Title: Create New Page in Orchard Module

Body:
How do I create a new page in orchard module? I have one page and controller in orchard, but how to add a new page in the route module?

        public IEnumerable<RouteDescriptor> GetRoutes() {
        return new[] {
            new RouteDescriptor {
                Priority = 5,
                Route = new Route(
                    "BlogX", // this is the name of the page url
                    new RouteValueDictionary {
                        {"area", "BlogX"}, // this is the name of your module
                        {"controller", "Home"},
                        {"action", "Index"}
                    },
                    new RouteValueDictionary(),
                    new RouteValueDictionary {
                        {"area", "BlogX"} // this is the name of your module
                    },
                    new MvcRouteHandler())
            }
        };
    }


问:
Using git pull to track a remote branch without merging
I am using git to track content which is changed by some people and shared "read-only" with others.  The "readers" may from time to time need to make a change, but mostly they will not.

I want to allow for the git "writers" to rebase pushed branches** if need be, and ensure that the "readers" never accidentally get a merge.  That's normally easy enough.

```<code>git pull origin +master
</code>```

There's one case that seems to cause problems.  If a reader makes a local change, the command above will merge.  I want pull to be fully automatic if the reader has not made local changes, while if they have made local changes, it should stop and ask for input.  I want to track any upstream changes while being careful about merging downstream changes.

In a way, I don't really want to pull. I want to track the master branch exactly.

** (I know this is not a best practice, but it seems necessary in our case: we have one main branch that contains most of the work and some topic branches for specific customers with minor changes that need to be isolated.  It seems easiest to frequently rebase to keep the topics up to date.)

答:
How about:

```<code>  git pull --ff-only origin master
</code>```

I use that often. Unfortunately, as richard-hansen@ pointed out below, this does not work as an alias:

```<code>[alias]
pull = pull --ff-only
</code>```

OwnerDisplayName: J Barlow

Body:
I am using git to track content which is changed by some people and shared "read-only" with others.  The "readers" may from time to time need to make a change, but mostly they will not.

I want to allow for the git "writers" to rebase pushed branches** if need be, and ensure that the "readers" never accidentally get a merge.  That's normally easy enough.

git pull origin +master

There's one case that seems to cause problems.  If a reader makes a local change, the command above will merge.  I want pull to be fully automatic if the reader has not made local changes, while if they have made local changes, it should stop and ask for input.  I want to track any upstream changes while being careful about merging downstream changes.

In a way, I don't really want to pull. I want to track the master branch exactly.

** (I know this is not a best practice, but it seems necessary in our case: we have one main branch that contains most of the work and some topic branches for specific customers with minor changes that need to be isolated.  It seems easiest to frequently rebase to keep the topics up to date.)

Body:
How about:

  git pull --ff-only origin master

I use that often. Unfortunately, as richard-hansen@ pointed out below, this does not work as an alias:

[alias]
pull = pull --ff-only


问:
How to hide Login fields from the logged user
I am developping an ASP MVC using ADO.net. I am trying to hide the login fields after the user login on.

Indeed, after authentication from the home page, the user is redirected to his profil page. The problem is that when the user go back to the home page, he find always the Login Fields.

According to the Debugger, Session["currentUser"] stay always null and then the script is rendered.

I didn't find also an error in dev tools.

This is what I've tried :

```<code> @if (Session["currentUser"] != null)
 {
    <script type='text/javascript'>
$(document).ready(function(){
    $("#login").hide();
});
    </script>
 }
        <div class="login" id="login">
            @*@RenderPage("~/Views/Home/Login.cshtml")*@
            <link href="~/Content/toastr.css" rel="stylesheet" />
            <div class="main-w3l">
                <div class="w3layouts-main" style="background-image:url('/template/web/images/bg3.jpg'); margin-top:50px;">
                    <h2>Login Now</h2>

                    @using (Html.BeginForm("Login", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                    {

                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <input value="E-MAIL" name="Email" type="email" required="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'E-Mail';}" />
                        <input value="PASSWORD" name="Password" type="password" required="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'password';}" />
                        <span><input type="checkbox" />Remember Me</span>
                        <h6><a href="#">Forgot Password?</a></h6>
                        <div class="clear"></div>
                        <input type="submit" value="login" name="login">

                    }

                    <p>Don't Have an Account ?<a href="#" onclick="@("window.location.href='" + @Url.Action("Create", "Client") + "'") ;">Register Now</a></p>
                </div>
            </div>
</code>```

UPDATE :
Controller :

```<code>  public ActionResult Login()
        {
            return View();
        }

    database_Access_layer.db dblayer = new database_Access_layer.db();

    [HttpPost]
    public ActionResult Login(FormCollection fc, string LastName, string Email)
    {

        int res = dblayer.Admin_Login(fc["Email"], fc["Password"]);
        if (res == 1)
        {
            Session["currentUser"] = Email;
            string z = Email;
            connection();
            con.Open();
            SqlCommand command = new SqlCommand("select Email from Client", con);

            List<string> result = new List<string>();
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                    result.Add(reader.GetString(0));
                con.Close();
            }
            foreach (string x in result)
            {
                if (x == z)
                {

                    SqlCommand command2 = new SqlCommand($"select LastName from Client WHERE Email= '{x}' ", con);
                    con.Open();
                    string y = command2.ExecuteScalar().ToString();
                    con.Close();
                    Session["currentUser"] = y;

                }
            }

            return RedirectToAction("Profil", "Client");
            Session.RemoveAll();

        }
        else {

            TempData["msg"] = " Email or Password is wrong !";
            return RedirectToAction("Index", "Home");

        }

    }
</code>```

答: Store the token/related information from which you know weather the user is logged in or not in sessions/cache, then where ever you are writing user login functionality either you can write any service or just use jquery/javascript to access that, then show or hide form depending on that.</p>

Body:
I am developping an ASP MVC using ADO.net. I am trying to hide the login fields after the user login on.

Indeed, after authentication from the home page, the user is redirected to his profil page. The problem is that when the user go back to the home page, he find always the Login Fields.

According to the Debugger, Session["currentUser"] stay always null and then the script is rendered.

I didn't find also an error in dev tools.

This is what I've tried :

 @if (Session["currentUser"] != null)
 {

 }

            @*@RenderPage("~/Views/Home/Login.cshtml")*@
            <link href="~/Content/toastr.css" rel="stylesheet" />

Login Now

                    @using (Html.BeginForm("Login", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                    {

                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <input value="E-MAIL" name="Email" type="email" required="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'E-Mail';}" />
                        <input value="PASSWORD" name="Password" type="password" required="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'password';}" />
                        <input type="checkbox" />Remember Me

Forgot Password?

                        <input type="submit" value="login" name="login">

                    }

Don't Have an Account ?Register Now

UPDATE :
Controller :

  public ActionResult Login()
        {
            return View();
        }

    database_Access_layer.db dblayer = new database_Access_layer.db();

    [HttpPost]
    public ActionResult Login(FormCollection fc, string LastName, string Email)
    {

        int res = dblayer.Admin_Login(fc["Email"], fc["Password"]);
        if (res == 1)
        {
            Session["currentUser"] = Email;
            string z = Email;
            connection();
            con.Open();
            SqlCommand command = new SqlCommand("select Email from Client", con);

            List<string> result = new List<string>();
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                    result.Add(reader.GetString(0));
                con.Close();
            }
            foreach (string x in result)
            {
                if (x == z)
                {

                    SqlCommand command2 = new SqlCommand($"select LastName from Client WHERE Email= '{x}' ", con);
                    con.Open();
                    string y = command2.ExecuteScalar().ToString();
                    con.Close();
                    Session["currentUser"] = y;

                }
            }

            return RedirectToAction("Profil", "Client");
            Session.RemoveAll();

        }
        else {

            TempData["msg"] = " Email or Password is wrong !";
            return RedirectToAction("Index", "Home");

        }

    }


问:
Videogular2 control outside <vg-player> element
Is there a way to use a controler outside the <vg-player></vg-player> element?

I'm trying to make a fullscreen button outside the <vg-player> like following:

```<code><vg-controls>
    <vg-fullscreen></vg-fullscreen>
  </vg-controls>

  <vg-player>
    <vg-controls>
      <vg-fullscreen></vg-fullscreen>
    </vg-controls>
    <video [vgMedia]="media" #media id="singleVideo" preload="auto"  autoplay>
      <source src="assets/videos/mov_bbb.mp4" type="video/mp4"/>
    </video>
  </vg-player>´
</code>```

This because I want this button on another place, not ontop of the video.

The code above gives me following Error: ERROR TypeError: Invalid event target

答:
Found solution myself.

using the videogular2 API.

```<code>    <vg-player (onPlayerReady)="onPlayerReady($event)">
       <video> <source srcs="myvideo"/></video
    </vg-player>

fullscreen() {
        this.vg.fsAPI.toggleFullscreen();
    }
</code>```

Body:
Is there a way to use a controler outside the <vg-player></vg-player> element?

I'm trying to make a fullscreen button outside the <vg-player> like following:

<vg-controls>
    <vg-fullscreen></vg-fullscreen>
  </vg-controls>

  <vg-player>
    <vg-controls>
      <vg-fullscreen></vg-fullscreen>
    </vg-controls>
    <video [vgMedia]="media" #media id="singleVideo" preload="auto"  autoplay>
      <source src="assets/videos/mov_bbb.mp4" type="video/mp4"/>
    </video>
  </vg-player>´

This because I want this button on another place, not ontop of the video.

The code above gives me following Error: ERROR TypeError: Invalid event target

Body:
Found solution myself.

using the videogular2 API.

    <vg-player (onPlayerReady)="onPlayerReady($event)">
       <video> <source srcs="myvideo"/></video
    </vg-player>

fullscreen() {
        this.vg.fsAPI.toggleFullscreen();
    }


问:
keyboard appear and view scroll to top
I have a problem in my code: when I tap on the UITextView and the keyboard is showing, there is a scroll to top (and I really don't know why !)
I have to scroll down myself to go back to the UITextView.

I'm in a tableView, and my cells have dynamic heights.

Here is a little demo of my problem:

I made some research and I tried this:

```<code>   @objc func keyboardWillShow(_ notification: NSNotification) {
      print("show")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
         }
      }
   }

   @objc func keyboardWillHide(_ notification: NSNotification) {
      print("hide")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
         }
      }
   }
</code>```

It sitll doesn't work. That's really weird because that's the only view where I have this problem.

答:
If you have a reference to the textView, then try to add this code in your keyboardWillShow function.</p>

```<code>scrollView.scrollRectToVisible(textView.frame, animated: true)
</code>```

Title: keyboard appear and view scroll to top

Body:
I have a problem in my code: when I tap on the UITextView and the keyboard is showing, there is a scroll to top (and I really don't know why !)
I have to scroll down myself to go back to the UITextView.

I'm in a tableView, and my cells have dynamic heights.

Here is a little demo of my problem:

I made some research and I tried this:

   @objc func keyboardWillShow(_ notification: NSNotification) {
      print("show")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
         }
      }
   }

   @objc func keyboardWillHide(_ notification: NSNotification) {
      print("hide")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
         }
      }
   }

It sitll doesn't work. That's really weird because that's the only view where I have this problem.

Body:
If you have a reference to the textView, then try to add this code in your keyboardWillShow function.

scrollView.scrollRectToVisible(textView.frame, animated: true)