问:
Chrome OS: how to enable direct SFTP access in the Files app / Pixelbook Review
An article on Chrome OS that I read here:
    https://medium.com/@JamesCridland/review-five-months-with-a-chromebook-for-web-development-writing-and-more-8adf36b4a061

says:
"Update: Above, I mention that I use SSH and vi to do my programming work. And I did. Except I don’t any more. It turns out that one of the newer updates added direct SFTP access into the Files app (the equivalent of Explorer or Finder), so that my development box appears simply as another drive on my Chromebook. And Caret is an excellent programmer’s editor. So now I have a proper programmer’s editor (as well as the SSH terminal I need to put those changes live)."

Ok. But, when I go into Chrome OS's files app, the apparent way 'mount' my equiv of his
'development box' is via 'add new services', which is launching a webstore-app named 'SFTP' (whose icon is a blue folder outline with "SFTP" on it).  i,e.:

    https://chrome.google.com/webstore/detail/sftp-file-system/gbheifiifcfekkamhepkeogobihicgmn?hl=en

(My equiv of his 'development box' I'm assuming to be my web-server at bluehost.com, where I currently use Firefox's FireFTP extension, on Win-10.)

I can't get this 3-stars webstore 'SFTP' app (authored by someone from Japan) to authenticate me into my bluehost acc't.  So, now I'm wondering whether
this 'SFTP' app is even the right thing to have installed, due to all the one- and two-star showstopper reviews.  One typical review by a guy named Tim says:

"It's a nice try, but I really wish someone who knows what they're doing would make this service. It looks like it works but if you drill down more than a few folders deep on the remote filesystem, operations slow to a crawl."

Similarly, the two clients ('sFTP client' and 'sFTP client Lite) also have such low ratings, that my gut says that Google has failed to deliver a robust web-developer infrastructure.

Come on Google...you need to implement this stuff under your own logo.

Am I missing something???

答:
No, not an answer yet...just more wishlist stuff:

Ok, more recent info about the Firefox browser's "FireFTP" addon:

It no longer works on the (new) std Firefox browser, as of a couple of
weeks ago when version 57.0 was released.  (No biggie tho...a goggle revealed
a new-to-me browser called 'Waterfox' and it nicely supports FireFTP and the
other addons that Firefox dropped support for.)

So a bit more research yielded only yet more 'mumble-mode' confusion: it revealed that FireFTP is open source...located here:
    https://github.com/mimecuvalo/fireftp
(So I submitted a new 'issue' there and asked about porting it to Chrome.)

I'm desperate, and recently test-drove Google's new Pixelbook.
(Sigh...nothing inspirational came of that...I give it one-thumb-down rating.
Here's my notes from that experience:

------------ Review notes of Pixelbook: ----------------------

Google didn’t think to include a USB-C to USB-A adapter. (A $2 item. e.g.)
    https://www.amazon.com/Remax-USB3-1-Female-Adapter-Silver/dp/B01MCSRSKN/

That was my 'showstopper'...like a few other reviewers said...it's not well
thought out / matured.  To me it feels more like a gimmick, than a product.
At a minimum, it rates my newest hashtag: #NRFPT (not ready for prime time).

I found no obvious way to disable the touchpad, when using a mouse.
In fact, no other reviewers expressed interest in using a mouse. (???)

Lastly, my favorite kind of Android apps are 'widgets', and I see no signs
that it has occurred to Google to allow Chrome-OS's desktop/background to
host any widgets.

Ok, I'm still in mumble-mode...and still in search of a FTP/SFTP GUI client for
the Chrome browser / Chrome-OS that is the quality of FireFTP.


来源: stackexchange

问:
PHPUnit CI Test against different vendor versions
I'm writing PHP Software with composer and PHPUnit CI.
I set it up to test against different PHP versions - php 5.6 / 7.0 / 7.1.

But my software have 3rd party software dependencies.
How can I setup unit test to run against different vendor modules ?

For example: My software wants symfony/forms either ~2.8 either ~3.0.

How do I setup 2 tests: one with symfony 2.8 and one with 3.0 ?

I think the only way is with some kind of before_script: composer require vendor:~specific_version ?

答:
You can use multiple composer.json, for example :

composer.5_6.json (with "require": {"php":">=5.6", "symfony/symfony":"~2.8"})

composer.7_0.json (with "require": {"php":">=7.0", "symfony/symfony":"~3.0"})

and then in your before_script :

cp composer.5_6.json composer.json && composer update

run your 5.6 unit tests

rm composer.json && rm composer.lock

cp composer.7_0.json composer.json && composer update

run your 7.0 unit tests

ContentLicense: CC BY-SA 3.0


问:
How can I create a map from object properties?
I get an object via some 3rd party api. I use a wrapper function to get it and then return a map from its properties:

```<code>wrapperFunc() {
    def myObj = someapi.getblah().getSomeObect()
    return [
        aaa: myObj.aaa,
        bbb: myObj.bbb,
        ccc: myObj.ccc
    ]
}
</code>```

Now I could manually go through EVERY property in the object like this, but is there an elegant groovy feature to dynamically build a map from the object's properties?

答:
This is basically a variant of @jeff-scott-brown's answer.

First, create a class that contains the Object-to-Map logic that uses the Groovy MetaClass to access a type's properties. findAll filters out the "class" property, which I assume you don't care about. The collectEntries line transforms each MetaProperty object into a Map entry.

```<code>class ElegantGroovyFeature {
    static Map asType(Object o, Class m) {
        if (m == Map) {
            o.metaClass.properties
                       .findAll { it.getSetter() != null }
                       .collectEntries { prop -> [prop.name, prop.getProperty(o)] }
        } else {
            o.asType(m)
        }
    }
}
</code>```

The extension class overrides the asType method, which corresponds to the as operator, enabling you to convert arbitrary objects to Maps using obj as Map expressions:

```<code>def obj = someapi.getBlah().getSomeObject()
use (ElegantGroovyFeature) {
    def mapOfProperties = obj as Map
}
</code>```

Body:
I get an object via some 3rd party api. I use a wrapper function to get it and then return a map from its properties:

wrapperFunc() {
    def myObj = someapi.getblah().getSomeObect()
    return [
        aaa: myObj.aaa,
        bbb: myObj.bbb,
        ccc: myObj.ccc
    ]
}

Now I could manually go through EVERY property in the object like this, but is there an elegant groovy feature to dynamically build a map from the object's properties?

Body:
This is basically a variant of @jeff-scott-brown's answer.

First, create a class that contains the Object-to-Map logic that uses the Groovy MetaClass to access a type's properties. findAll filters out the "class" property, which I assume you don't care about. The collectEntries line transforms each MetaProperty object into a Map entry.

class ElegantGroovyFeature {
    static Map asType(Object o, Class m) {
        if (m == Map) {
            o.metaClass.properties
                       .findAll { it.getSetter() != null }
                       .collectEntries { prop -> [prop.name, prop.getProperty(o)] }
        } else {
            o.asType(m)
        }
    }
}

The extension class overrides the asType method, which corresponds to the as operator, enabling you to convert arbitrary objects to Maps using obj as Map expressions:

def obj = someapi.getBlah().getSomeObject()
use (ElegantGroovyFeature) {
    def mapOfProperties = obj as Map
}


问:
Non-Prime Number Counter in C
I want to write a program for storing all the non-prime(composite) numbers before 10.000 in an array. I did this algorithm below, but it's not working. When I print out the array which is supposed to be holding composite numbers, it's simply counting from 4 to 10.000 .

Where is the problem? I really looked so much but I can't see.

```<code>#include <stdio.h>
#define SIZE 10000

void compositeChecker(int[]);

int main() {
    int k;
    int compositeArray[SIZE]= {0};
    compositeChecker(compositeArray);
    for(k=0; k<100; k++) {
        printf("%d\n",compositeArray[k]);
    }
}

void compositeChecker(int arr[]) {
    int i,j,counter=0;

    for(i=4; i<10000; i++) {
        for(j=2; j<i; j++) {
            if((i%j)==0) {
                counter++;
            }
        }
        if(counter!=0) {
            arr[i-4]=i;
        }
    }
}
</code>```

答:
This is happening because of the logic in your code.  Inside of your for loop, you say this:

```<code>for(j=2;j<i;j++) {
 if((i%j)==0){

    counter++;

 }
}

if(counter!=0){

    arr[i-4]=i;
}
</code>```

So, once you find any composite number, you increment counter.  Counter is never reset to zero in your loop, so every single number is added to your array.  Even if your logic were fixed, you would be adding values to an array in a way that doesn't make sense.  Consider the values 5 and 6.

Even if you corrected the logic, 5 would not be added... So arr[i-4] (arr[1]) would have no value... but when I=6, arr[i-4] would have a value.  You probably want to change this logic to count how many composite numbers you have found so far and add the number found to the array at that point.

Title: Non-Prime Number Counter in C

Body:
I want to write a program for storing all the non-prime(composite) numbers before 10.000 in an array. I did this algorithm below, but it's not working. When I print out the array which is supposed to be holding composite numbers, it's simply counting from 4 to 10.000 .

Where is the problem? I really looked so much but I can't see.

#include <stdio.h>
#define SIZE 10000

void compositeChecker(int[]);

int main() {
    int k;
    int compositeArray[SIZE]= {0};
    compositeChecker(compositeArray);
    for(k=0; k<100; k++) {
        printf("%d\n",compositeArray[k]);
    }
}

void compositeChecker(int arr[]) {
    int i,j,counter=0;

    for(i=4; i<10000; i++) {
        for(j=2; j<i; j++) {
            if((i%j)==0) {
                counter++;
            }
        }
        if(counter!=0) {
            arr[i-4]=i;
        }
    }
}

Body:
This is happening because of the logic in your code.  Inside of your for loop, you say this:

for(j=2;j<i;j++) {
 if((i%j)==0){

    counter++;

 }
}

if(counter!=0){

    arr[i-4]=i;
}

So, once you find any composite number, you increment counter.  Counter is never reset to zero in your loop, so every single number is added to your array.  Even if your logic were fixed, you would be adding values to an array in a way that doesn't make sense.  Consider the values 5 and 6.

Even if you corrected the logic, 5 would not be added... So arr[i-4] (arr[1]) would have no value... but when I=6, arr[i-4] would have a value.  You probably want to change this logic to count how many composite numbers you have found so far and add the number found to the array at that point.


问:
Directory for external files in the standard maven directory layout
In Java, we have two different approaches for loading data into the application.

If a file is packed into the jar (call it resource file) we get its InputStream by Class.getResourceAsStream() method.

If a file is not inside the jar (call it external file) we use new FileInputStream().

If I understand correctly, the distinction between resource and external files is due to the fact that the former are required for the application to launch and run properly (therefore packed into an executable jar - shouldn't be modified) and the latter are rather optional and may or may be not provided by the user.

In the standard maven directory layout we put our resource files in the src/main/resources directory so they are included in the jar when building a project. But I can't figure out what the proper directory for external files is.

In the distributed version of my application I want to provide a certain set of default external files, so I need to put them somewhere in the project structure. What is the best location?

So far, I've seen src/main/webapp (which doesn't seem appropriate for desktop applications) and src/main/conf (which seems to get out of use and besides the external files may be of different types - not only text).

A custom directory like src/main/assets or src/main/data? Or maybe there should be another source directory next to the main and test?

I'll be grateful for any suggestions!

答:
As it is an external file, it can't be under src, you can put it under (for example) static_content (a folder next to the POM.xml) and add this to your POM</p>

```<code><build>
    <plugins>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.5</version>
            <executions>
                <execution>
                    <id>copy-resources</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>
                            target/static_content/csvs
                        </outputDirectory>
                        <resources>
                            <resource>
                               <directory>static_content/csvs</directory>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

Body:
As it is an external file, it can't be under src, you can put it under (for example) static_content (a folder next to the POM.xml) and add this to your POM

<build>
    <plugins>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.5</version>
            <executions>
                <execution>
                    <id>copy-resources</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>
                            target/static_content/csvs
                        </outputDirectory>
                        <resources>
                            <resource>
                               <directory>static_content/csvs</directory>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


问:
Matching two data frames' columns and store it in new column
I have two data frames:

```<code>df:

id         id.1      weight
RoLu1976   Gr1969     50
MaRg1988   FuDa1989   10
FiKy1977   RoBa1983   12
MaTe1980   SeNd1998   23
Gr69       MaGe1977   72
</code>```

And:

```<code>df1:

id         id.1
Gr1969     RoLu1976
FiKy1977   RoBa1983
</code>```

I need to make a weight column in df1 by matching df1$id and df1$id.1 with df$id and df$id.1.

```<code>df1:

id         id.1      weight
Gr1969     RoLu1976   50
FiKy1977   RoBa1983   12
</code>```

Sometimes the observations are exchanged in the columns, for example, df's first row and df1's first row:

```<code>df:
id        id.1     weight
Rolu1976  Gr1969   50
</code>```

and

```<code>df1:
id       id.1
Gr1969   RoLu1976
</code>```

It means that the column order doesn't matter for the matching.

[EDIT]

I try to do it with inner_join function from dplyr package, and merge function, but, it is necessary make all the combinations of the columns.
There is a way to matching them without specify all the combinations?

Or there is a fastest way to do it with python pandas module?

答:
Not sure, if the interchange in the columns was intended or by mistake. Here is the solution

solution

```<code>rbind(merge(df1, df2, by.x = c('id.1','id'), by.y = c('id','id.1')),
merge(df1, df2, by.x = c('id.1','id'), by.y = c('id.1','id')))
</code>```

output

```<code>      id.1       id weight
1   Gr1969 RoLu1976     50
2 RoBa1983 FiKy1977     12
</code>```

data

```<code> df1 <- read.table(text='id         id.1      weight
    RoLu1976   Gr1969     50
    MaRg1988   FuDa1989   10
    FiKy1977   RoBa1983   12
    MaTe1980   SeNd1998   23
    Gr69       MaGe1977   72', header=TRUE)

    df2 <- read.table(text='id         id.1
    Gr1969     RoLu1976
    FiKy1977   RoBa1983', header=TRUE)
</code>```

Body:
I have two data frames:

df:

id         id.1      weight
RoLu1976   Gr1969     50
MaRg1988   FuDa1989   10
FiKy1977   RoBa1983   12
MaTe1980   SeNd1998   23
Gr69       MaGe1977   72

And:

df1:

id         id.1
Gr1969     RoLu1976
FiKy1977   RoBa1983

I need to make a weight column in df1 by matching df1$id and df1$id.1 with df$id and df$id.1.

df1:

id         id.1      weight
Gr1969     RoLu1976   50
FiKy1977   RoBa1983   12

Sometimes the observations are exchanged in the columns, for example, df's first row and df1's first row:

df:
id        id.1     weight
Rolu1976  Gr1969   50

and

df1:
id       id.1
Gr1969   RoLu1976

It means that the column order doesn't matter for the matching.

[EDIT]

I try to do it with inner_join function from dplyr package, and merge function, but, it is necessary make all the combinations of the columns.
There is a way to matching them without specify all the combinations?

Or there is a fastest way to do it with python pandas module?

Body:
Not sure, if the interchange in the columns was intended or by mistake. Here is the solution

solution

rbind(merge(df1, df2, by.x = c('id.1','id'), by.y = c('id','id.1')),
merge(df1, df2, by.x = c('id.1','id'), by.y = c('id.1','id')))

output

      id.1       id weight
1   Gr1969 RoLu1976     50
2 RoBa1983 FiKy1977     12

data

 df1 <- read.table(text='id         id.1      weight
    RoLu1976   Gr1969     50
    MaRg1988   FuDa1989   10
    FiKy1977   RoBa1983   12
    MaTe1980   SeNd1998   23
    Gr69       MaGe1977   72', header=TRUE)

    df2 <- read.table(text='id         id.1
    Gr1969     RoLu1976
    FiKy1977   RoBa1983', header=TRUE)


问:
Spring Boot and Apache Shiro with JWT - Am I using it correctly?
I have Spring Boot application and I attempted to integrate Apache shiro with it. As a first iteration, I am authenticating and authorizing the JWT way, no session whatsoever.

The way I have architected it, every REST request has to contain a JWT header that needs to be validated. I am doing it in a shiro filter. Post validation, filter sets a context, that any REST controller method will be able to fetch and act upon it.

I want the opinion of community to make sure my configuration is correct.
Moreover, there are certain problems (at least IMO), I am facing with it. So if someone can throw some light on a correct way of handing it, would be greatly appreciated.

Following are some code snippets demonstrating my configuration and realm design.

Snippet 1 : ShiroConfiguration

```<code>private AuthenticationService authenticationService;
/**
 * FilterRegistrationBean
 * @return
 */
@Bean
public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
    filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
    filterRegistration.setEnabled(true);
    filterRegistration.setDispatcherTypes(DispatcherType.REQUEST);
    filterRegistration.setOrder(1);
    return filterRegistration;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager securityManager() {
    DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
    dwsm.setRealm(authenticationService());
    final DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
    // disable session cookie
    sessionManager.setSessionIdCookieEnabled(false);
    dwsm.setSessionManager(sessionManager);
    return dwsm;
}

/**
 * @see org.apache.shiro.spring.web.ShiroFilterFactoryBean
 * @return
 */
@Bean(name="shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager, JWTTimeoutProperties jwtTimeoutProperties, TokenUtil tokenUtil) {
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    bean.setSecurityManager(securityManager);

    //TODO: Create a controller to replicate unauthenticated request handler
    bean.setUnauthorizedUrl("/unauthor");

    Map<String, Filter> filters = new HashMap<>();
    filters.put("perms", new AuthenticationTokenFilter(jwtTimeoutProperties, tokenUtil));
    filters.put("anon", new AnonymousFilter());
    bean.setFilters(filters);

    LinkedHashMap<String, String> chains = new LinkedHashMap<>();
    chains.put("/", "anon");
    chains.put("/favicon.ico", "anon");
    chains.put("/index.html", "anon");
    chains.put("/**/swagger-resources", "anon");
    chains.put("/api/**", "perms");

    bean.setFilterChainDefinitionMap(chains);
    return bean;
}
@Bean
@DependsOn(value="lifecycleBeanPostProcessor")
public AuthenticationService authenticationService() {
    if (authenticationService==null){
        authenticationService = new AuthenticationService();
    }

    return  authenticationService;
}

@Bean
@DependsOn(value="lifecycleBeanPostProcessor")
public Authorizer authorizer() {
    return authenticationService();
}

@Bean
@DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
    DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
    proxyCreator.setProxyTargetClass(true);
    return proxyCreator;
}
</code>```

Snippet 2 : AuthenticationFilter

```<code>public class AuthenticationTokenFilter extends PermissionsAuthorizationFilter {
@Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authorizationHeader = httpRequest.getHeader(TOKEN_HEADER);
    String authToken;

    String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
    httpRequest.setAttribute(alreadyFilteredAttributeName, true);

    AuthenticationService.ensureUserIsLoggedOut(); // To not end up getting following error.

    if (authorizationHeader != null && !authorizationHeader.isEmpty()) {

        if (authorizationHeader.startsWith(BEARER_TOKEN_START_WITH)) {
            authToken = authorizationHeader.substring(BEARER_TOKEN_START_INDEX);
        } else if (authorizationHeader.startsWith(BASIC_TOKEN_START_WITH)) {
            String caseId = UUID.randomUUID().toString();
            log.warn("{} Basic authentication is not supported but a Basic authorization header was passed in", caseId);
            return false;
        } else {
            // if its neither bearer nor basic, default it to bearer.
            authToken = authorizationHeader;
        }
        try {
            if(tokenUtil.validateTokenAgainstSignature(authToken, jwtTimeoutProperties.getSecret())) {
                Map<String, Object> outerClaimsFromToken = tokenUtil.getOuterClaimsFromToken(authToken, jwtTimeoutProperties.getSecret());

                JWTAuthenticationToken jwtAuthenticationToken = new JWTAuthenticationToken(outerClaimsFromToken.get(TokenUtil.CLAIM_KEY_USERID),
                                                (String) outerClaimsFromToken.get(TokenUtil.CLAIM_KEY_INNER_TOKEN));
                SecurityUtils.getSubject().login(jwtAuthenticationToken);

        } catch (JwtException | AuthenticationException ex) {
            log.info("JWT validation failed.", ex);
        }
    }
    return false;
}
</code>```

Snippet 3 : TokenRestController

```<code>public Response getToken() {

    AuthenticationService.ensureUserIsLoggedOut(); // To not end up getting following error.
                                                        // org.apache.shiro.session.UnknownSessionException: There is no session with id

        // TODO: In case of logging in with the organization, create own token class implementing HostAuthenticationToken class.
        IAMLoginToken loginToken = new IAMLoginToken(authenticationRequestDTO.getUsername(), authenticationRequestDTO.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(loginToken);
        } catch (AuthenticationException e) {
            log.debug("Unable to login", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }

        AuthenticatingUser user = (AuthenticatingUser) subject.getPrincipal();

            String authToken = authenticationService.generateToken(user);
            return ResponseEntity.status(HttpStatus.OK).body(new AuthenticationResponseDTO(authToken));
    });
</code>```

Snippet 4 : AuthorizingRealm

```<code>@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (token instanceof IAMLoginToken) {
        IAMLoginToken usernamePasswordToken = (IAMLoginToken) token;

        UserBO user = identityManagerRepository.getUserByUsername(usernamePasswordToken.getUsername(), true);

        if (user != null && user.getSecret() != null && !user.getSecret().isEmpty()) {
            if(passwordEncoder.matches(String.valueOf(usernamePasswordToken.getPassword()), user.getPassword())) {
                if (!isActive(user)) {
                    throw new AuthenticationException("User account inactive.");
                }
                return new SimpleAuthenticationInfo(toAuthenticatingUser(user).withSecret(user.getSecret()), usernamePasswordToken.getPassword(), getName());
            }
        }
    } else if (token instanceof JWTAuthenticationToken) {
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) token;
        String userId = (String) jwtToken.getUserId();
        String secret = cache.getUserSecretById(userId, false);

        if (secret != null && !secret.isEmpty()) {
            Map<String, Object> tokenClaims = tokenUtil.getClaims(jwtToken.getToken(), secret);
            String orgId = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_ORG);
            String email = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_EMAIL);
            String firstName = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_FIRSTNAME);
            String lastName = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_LASTNAME);
            Set<String> permissions = (Set<String>) tokenClaims.get(TokenUtil.CLAIM_KEY_PERMISSIONS);

            return new SimpleAccount(new AuthenticatingUser(userId, orgId, email, firstName, lastName, permissions), jwtToken.getToken(), getName());
        }
    }

    throw new AuthenticationException("Invalid username/password combination!");
}

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.setStringPermissions(((AuthenticatingUser)principals.getPrimaryPrincipal()).getPermissions());
    return authorizationInfo;
}
</code>```

Problems and issues

Same error as mentioned in here.
Shiro complaining "There is no session with id xxx" with DefaultSecurityManager
I basically want Shiro to stop using and/or validating sessions. Is there a way to achieve that ? I solved it by implementing the same fix as mentioned in the answer, thats what ensureUserIsLoggedOut() does.

As you can see in the configuration's ShiroFilterFactoryBean definition, I am setting some filter chain definitions. And there you can see I set every api call that starts with /api will have authentication filter in front. But the thing is I want to add some exceptions to it. Such as, /api/v0/login is one of them. Is there a way of achieving this ?

Overall, I am not sure if the configuration I have come up with is appropriate, as I found very limited documentation and similar open source project samples.

Any feedback is welcome.

答:
I resolved the first issue of unwanted session validation and management by stopping Shiro from using a Subject’s session to store that Subject’s state across requests/invocations/messages for all Subjects.

I just had to apply following configuration to my session manager in my shiro configuration.
https://shiro.apache.org/session-management.html#disabling-subject-state-session-storage

Body:
I have Spring Boot application and I attempted to integrate Apache shiro with it. As a first iteration, I am authenticating and authorizing the JWT way, no session whatsoever.

The way I have architected it, every REST request has to contain a JWT header that needs to be validated. I am doing it in a shiro filter. Post validation, filter sets a context, that any REST controller method will be able to fetch and act upon it.

I want the opinion of community to make sure my configuration is correct.
Moreover, there are certain problems (at least IMO), I am facing with it. So if someone can throw some light on a correct way of handing it, would be greatly appreciated.

Following are some code snippets demonstrating my configuration and realm design.

Snippet 1 : ShiroConfiguration

private AuthenticationService authenticationService;
/**
 * FilterRegistrationBean
 * @return
 */
@Bean
public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
    filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
    filterRegistration.setEnabled(true);
    filterRegistration.setDispatcherTypes(DispatcherType.REQUEST);
    filterRegistration.setOrder(1);
    return filterRegistration;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager securityManager() {
    DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
    dwsm.setRealm(authenticationService());
    final DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
    // disable session cookie
    sessionManager.setSessionIdCookieEnabled(false);
    dwsm.setSessionManager(sessionManager);
    return dwsm;
}

/**
 * @see org.apache.shiro.spring.web.ShiroFilterFactoryBean
 * @return
 */
@Bean(name="shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager, JWTTimeoutProperties jwtTimeoutProperties, TokenUtil tokenUtil) {
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    bean.setSecurityManager(securityManager);

    //TODO: Create a controller to replicate unauthenticated request handler
    bean.setUnauthorizedUrl("/unauthor");

    Map<String, Filter> filters = new HashMap<>();
    filters.put("perms", new AuthenticationTokenFilter(jwtTimeoutProperties, tokenUtil));
    filters.put("anon", new AnonymousFilter());
    bean.setFilters(filters);

    LinkedHashMap<String, String> chains = new LinkedHashMap<>();
    chains.put("/", "anon");
    chains.put("/favicon.ico", "anon");
    chains.put("/index.html", "anon");
    chains.put("/**/swagger-resources", "anon");
    chains.put("/api/**", "perms");

    bean.setFilterChainDefinitionMap(chains);
    return bean;
}
@Bean
@DependsOn(value="lifecycleBeanPostProcessor")
public AuthenticationService authenticationService() {
    if (authenticationService==null){
        authenticationService = new AuthenticationService();
    }

    return  authenticationService;
}

@Bean
@DependsOn(value="lifecycleBeanPostProcessor")
public Authorizer authorizer() {
    return authenticationService();
}

@Bean
@DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
    DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
    proxyCreator.setProxyTargetClass(true);
    return proxyCreator;
}

Snippet 2 : AuthenticationFilter

public class AuthenticationTokenFilter extends PermissionsAuthorizationFilter {
@Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authorizationHeader = httpRequest.getHeader(TOKEN_HEADER);
    String authToken;

    String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
    httpRequest.setAttribute(alreadyFilteredAttributeName, true);

    AuthenticationService.ensureUserIsLoggedOut(); // To not end up getting following error.

    if (authorizationHeader != null && !authorizationHeader.isEmpty()) {

        if (authorizationHeader.startsWith(BEARER_TOKEN_START_WITH)) {
            authToken = authorizationHeader.substring(BEARER_TOKEN_START_INDEX);
        } else if (authorizationHeader.startsWith(BASIC_TOKEN_START_WITH)) {
            String caseId = UUID.randomUUID().toString();
            log.warn("{} Basic authentication is not supported but a Basic authorization header was passed in", caseId);
            return false;
        } else {
            // if its neither bearer nor basic, default it to bearer.
            authToken = authorizationHeader;
        }
        try {
            if(tokenUtil.validateTokenAgainstSignature(authToken, jwtTimeoutProperties.getSecret())) {
                Map<String, Object> outerClaimsFromToken = tokenUtil.getOuterClaimsFromToken(authToken, jwtTimeoutProperties.getSecret());

                JWTAuthenticationToken jwtAuthenticationToken = new JWTAuthenticationToken(outerClaimsFromToken.get(TokenUtil.CLAIM_KEY_USERID),
                                                (String) outerClaimsFromToken.get(TokenUtil.CLAIM_KEY_INNER_TOKEN));
                SecurityUtils.getSubject().login(jwtAuthenticationToken);

        } catch (JwtException | AuthenticationException ex) {
            log.info("JWT validation failed.", ex);
        }
    }
    return false;
}

Snippet 3 : TokenRestController

public Response getToken() {

    AuthenticationService.ensureUserIsLoggedOut(); // To not end up getting following error.
                                                        // org.apache.shiro.session.UnknownSessionException: There is no session with id

        // TODO: In case of logging in with the organization, create own token class implementing HostAuthenticationToken class.
        IAMLoginToken loginToken = new IAMLoginToken(authenticationRequestDTO.getUsername(), authenticationRequestDTO.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(loginToken);
        } catch (AuthenticationException e) {
            log.debug("Unable to login", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }

        AuthenticatingUser user = (AuthenticatingUser) subject.getPrincipal();

            String authToken = authenticationService.generateToken(user);
            return ResponseEntity.status(HttpStatus.OK).body(new AuthenticationResponseDTO(authToken));
    });

Snippet 4 : AuthorizingRealm

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (token instanceof IAMLoginToken) {
        IAMLoginToken usernamePasswordToken = (IAMLoginToken) token;

        UserBO user = identityManagerRepository.getUserByUsername(usernamePasswordToken.getUsername(), true);

        if (user != null && user.getSecret() != null && !user.getSecret().isEmpty()) {
            if(passwordEncoder.matches(String.valueOf(usernamePasswordToken.getPassword()), user.getPassword())) {
                if (!isActive(user)) {
                    throw new AuthenticationException("User account inactive.");
                }
                return new SimpleAuthenticationInfo(toAuthenticatingUser(user).withSecret(user.getSecret()), usernamePasswordToken.getPassword(), getName());
            }
        }
    } else if (token instanceof JWTAuthenticationToken) {
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) token;
        String userId = (String) jwtToken.getUserId();
        String secret = cache.getUserSecretById(userId, false);

        if (secret != null && !secret.isEmpty()) {
            Map<String, Object> tokenClaims = tokenUtil.getClaims(jwtToken.getToken(), secret);
            String orgId = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_ORG);
            String email = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_EMAIL);
            String firstName = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_FIRSTNAME);
            String lastName = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_LASTNAME);
            Set<String> permissions = (Set<String>) tokenClaims.get(TokenUtil.CLAIM_KEY_PERMISSIONS);

            return new SimpleAccount(new AuthenticatingUser(userId, orgId, email, firstName, lastName, permissions), jwtToken.getToken(), getName());
        }
    }

    throw new AuthenticationException("Invalid username/password combination!");
}

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.setStringPermissions(((AuthenticatingUser)principals.getPrimaryPrincipal()).getPermissions());
    return authorizationInfo;
}

Problems and issues

Same error as mentioned in here.
Shiro complaining "There is no session with id xxx" with DefaultSecurityManager
I basically want Shiro to stop using and/or validating sessions. Is there a way to achieve that ? I solved it by implementing the same fix as mentioned in the answer, thats what ensureUserIsLoggedOut() does.

As you can see in the configuration's ShiroFilterFactoryBean definition, I am setting some filter chain definitions. And there you can see I set every api call that starts with /api will have authentication filter in front. But the thing is I want to add some exceptions to it. Such as, /api/v0/login is one of them. Is there a way of achieving this ?

Overall, I am not sure if the configuration I have come up with is appropriate, as I found very limited documentation and similar open source project samples.

Any feedback is welcome.


问:
System.Windows.Forms.Timer performance
We have an application containing a lot of user controls that update frequently based on a System.Windows.Forms.Timer. Am I safe to add a Timer instance to each control peformancewise? Or should I have one Singleton Timer that runs all the time that is to be used by all instances? What is acutally happening under the hood? Will there be a an additional thread (for counting) for each timer?</p>

答:
System.Windows.Forms.Timer is implemented via good ol' User32 Timers. As such, they do not use or require a separate thread for operation. That said, they are a limited resource, in that you cannot have an infinite number of them.

When you say you have a lot of user controls using timers, what do you really mean by "a lot"? 10? 10000?

When you say they update frequently, what do you really mean? Every minute? Every 100 milliseconds? As fast as their timers can fire?

Stress test your app. See how many controls you can have active before it starts crashing or becomes so slow as to be unusable. Chances are, you'll hit the point where the overhead of internal processing for WM_TIMER messages kills performance long before you run out of other resources.

OwnerDisplayName: bitbonk

ContentLicense: CC BY-SA 2.5

Title: System.Windows.Forms.Timer performance

LastEditorDisplayName: Fabian Steeg


问:
Objective-c NSArray with values from another class
I am trying to create a table view in my view based application but I am facing a problem

```<code>NSArray *array = [[NSArray alloc] initWithObjects:@"iPod",forecast.desc,nil];
NSLog(@"this is the forecast routeNo = %@", forecast.desc);
</code>```

As you can see this is the array that shows the values in the table, the result of this code is iPod (only), "forecast.desc" doesn't show anything knowing that forecast is an instance of another class and "desc" is a string in that class

and just to make sure forecast.desc shows the correct information in the log but in the table as if doesn't exist can anyone see where is the problem ?

Thanks

答:
@bhappy the result of array variable is @"iPod" only means that forecast.desc has nil value.

So try to debug the code using single stepping and check what is the value of desc at the time of initializing the array.

And one more thing if desc is a member variable of class forecast than did you set the property for it, if not then forecast.desc wont work. You should check that first.

Body:
I am trying to create a table view in my view based application but I am facing a problem

NSArray *array = [[NSArray alloc] initWithObjects:@"iPod",forecast.desc,nil];
NSLog(@"this is the forecast routeNo = %@", forecast.desc);

As you can see this is the array that shows the values in the table, the result of this code is iPod (only), "forecast.desc" doesn't show anything knowing that forecast is an instance of another class and "desc" is a string in that class

and just to make sure forecast.desc shows the correct information in the log but in the table as if doesn't exist can anyone see where is the problem ?

Thanks


问:
Access respective parent object from $('.class').appendTo()
I'm trying to adapt some slideshow code I found here to be reusable based on classes.  The first slideshow toggles once, but then there is no other change.  I'm assuming this is due to the use of $(this).parent().  If so, how would I access the respective parent properly? If not, what is going on?

Edit: To be clear, both boxes contents should change independently!

$('.widget-slide:first').show();
setInterval(function() {
    $('.widget-slide:first')
        .fadeOut(1000)
        .next()
        .fadeIn(1000)
        .end()
        .appendTo($(this).parent());
}, 2000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.widget-slideshow {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid blue;
}

.widget-slide:not(:first-child){
  display: none;
}

.widget-slide {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  font-size: 20px;
  line-height: 50px;
  text-align: center;
  overflow: hidden;
}</code>```

        1

        2

        3

        4

        A

        B

        C

        D

```

答:
Although it doesn't technically answer my question, this works great.

$('.widget-slide:first').show();
  setInterval(function() {
  $('.widget-slideshow').each(function(i) {
    $(this).find('.widget-slide:first')
      .fadeOut(1000)
      .next()
      .fadeIn(1000)
      .end()
      .appendTo($(this));
    })
}, 2000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.widget-slideshow {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid blue;
}

.widget-slide:not(:first-child){
  display: none;
}

.widget-slide {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  font-size: 20px;
  line-height: 50px;
  text-align: center;
  overflow: hidden;
}</code>```

        1

        2

        3

        4

        A

        B

        C

        D

```

Body:
I'm trying to adapt some slideshow code I found here to be reusable based on classes.  The first slideshow toggles once, but then there is no other change.  I'm assuming this is due to the use of $(this).parent().  If so, how would I access the respective parent properly? If not, what is going on?

Edit: To be clear, both boxes contents should change independently!

$('.widget-slide:first').show();
setInterval(function() {
    $('.widget-slide:first')
        .fadeOut(1000)
        .next()
        .fadeIn(1000)
        .end()
        .appendTo($(this).parent());
}, 2000);

.widget-slideshow {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid blue;
}

.widget-slide:not(:first-child){
  display: none;
}

.widget-slide {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  font-size: 20px;
  line-height: 50px;
  text-align: center;
  overflow: hidden;
}

        1

        2

        3

        4

        A

        B

        C

        D

Body:
Although it doesn't technically answer my question, this works great.

$('.widget-slide:first').show();
  setInterval(function() {
  $('.widget-slideshow').each(function(i) {
    $(this).find('.widget-slide:first')
      .fadeOut(1000)
      .next()
      .fadeIn(1000)
      .end()
      .appendTo($(this));
    })
}, 2000);

.widget-slideshow {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid blue;
}

.widget-slide:not(:first-child){
  display: none;
}

.widget-slide {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  font-size: 20px;
  line-height: 50px;
  text-align: center;
  overflow: hidden;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget-slideshow">
    <div class="widget-slide">
        1
    </div>
    <div class="widget-slide">
        2
    </div>
    <div class="widget-slide">
        3
    </div>
    <div class="widget-slide">
        4
    </div>
</div>

<div class="widget-slideshow">
    <div class="widget-slide">
        A
    </div>
    <div class="widget-slide">
        B
    </div>
    <div class="widget-slide">
        C
    </div>
    <div class="widget-slide">
        D
    </div>
</div>


问:
How to write a function where the original list of integers is changed without using return?
Let us say we have a list of integers:

list = [6, 4, 1, 4, 4, 4, 4, 4, 2, 1]

I now wrote a function which returns another list with all the integers from the list above without repeats.

```<code>def no_repeats(s):
    new_list = []
    for number in s:
        if new_list.count(number) < 1:
            new_list.append(number)
    return(new_list)
</code>```

The new_list returns [6, 4, 1, 2] which is good! My question is how I would now write two similar functions:

A function clean(s) which does not return a new list like the function above, but changes the original list by deleting all the numbers that repeat. Thus, the result has to be the same and the function must not include "return" or create a new list. It must only clean the original list.

A function double(s) which, again, changes the original list (does not return a new list!) but this time, by doubling every number in the original list. Thus, double(list) should change the original list above to:

[6, 6, 4, 4, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 1, 1]

Thank you for all the help!

答:
```<code>>>> def clean(s):
...     s[:] = [s[i] for i in range(len(s)) if s[i] not in s[:i]]
...
>>> st = [1, 2, 3, 2, 1]

>>> clean(st)
>>> st
[1, 2, 3]

>>> def double(s):
...     s[:] = [s[i//3] for i in range(3*len(s)) if i % 3]
...
>>> st = [1, 2, 3, 2, 1]
>>> double(st)
>>> st
[1, 1, 2, 2, 3, 3, 2, 2, 1, 1]
</code>```

neither is particularly efficient nor pythonic, yet do address the OP question

def double(s):
      ...     s[:] = [s[i//2] for i in range(2*len(s))]

will also do the trick, with a little less obsfucation

Body:
Let us say we have a list of integers:

list = [6, 4, 1, 4, 4, 4, 4, 4, 2, 1]

I now wrote a function which returns another list with all the integers from the list above without repeats.

def no_repeats(s):
    new_list = []
    for number in s:
        if new_list.count(number) < 1:
            new_list.append(number)
    return(new_list)

The new_list returns [6, 4, 1, 2] which is good! My question is how I would now write two similar functions:

A function clean(s) which does not return a new list like the function above, but changes the original list by deleting all the numbers that repeat. Thus, the result has to be the same and the function must not include "return" or create a new list. It must only clean the original list.

A function double(s) which, again, changes the original list (does not return a new list!) but this time, by doubling every number in the original list. Thus, double(list) should change the original list above to:

[6, 6, 4, 4, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 1, 1]

Thank you for all the help!

Body:
>>> def clean(s):
...     s[:] = [s[i] for i in range(len(s)) if s[i] not in s[:i]]
...
>>> st = [1, 2, 3, 2, 1]

>>> clean(st)
>>> st
[1, 2, 3]

>>> def double(s):
...     s[:] = [s[i//3] for i in range(3*len(s)) if i % 3]
...
>>> st = [1, 2, 3, 2, 1]
>>> double(st)
>>> st
[1, 1, 2, 2, 3, 3, 2, 2, 1, 1]

neither is particularly efficient nor pythonic, yet do address the OP question

def double(s):
      ...     s[:] = [s[i//2] for i in range(2*len(s))]

will also do the trick, with a little less obsfucation


问:
Extracting the RGB value from a string
How would I extract the RBG value from the following string?:

let string = "

I would like to get extract "rgb(230, 0, 0)" from the background-color value, so I can convert it to a hex string and update some UI.

```<code>let range = string.range(of: "\"background-color: ")
let startPoint = range.location + range.length
let subString = string.substring(from: startPoint)
//generating error claiming 'cannot convert value of type 'int' to expected argument type 'string.index'.
//paused here to ask S.O b/c I do not think substrings is the best way to do this, maybe there is a library that extracts values from html elements, or regex?
</code>```

答:
You can use a regex to get the string between two strings:</p>

```<code>let string = "<span style=\"background-color: rgb(230, 0, 0);\">"

let pattern = "(?<=background-color: )(.*)(?=;)"
if let rgb = string.range(of: pattern, options: .regularExpression).map({String(string[$0])}) {
    print(rgb)  // "rgb(230, 0, 0)"
}
</code>```

Title: Extracting the RGB value from a string

Body:
How would I extract the RBG value from the following string?:

let string = "

I would like to get extract "rgb(230, 0, 0)" from the background-color value, so I can convert it to a hex string and update some UI.

let range = string.range(of: "\"background-color: ")
let startPoint = range.location + range.length
let subString = string.substring(from: startPoint)
//generating error claiming 'cannot convert value of type 'int' to expected argument type 'string.index'.
//paused here to ask S.O b/c I do not think substrings is the best way to do this, maybe there is a library that extracts values from html elements, or regex?

Body:
You can use a regex to get the string between two strings:

let string = "<span style=\"background-color: rgb(230, 0, 0);\">"

let pattern = "(?<=background-color: )(.*)(?=;)"
if let rgb = string.range(of: pattern, options: .regularExpression).map({String(string[$0])}) {
    print(rgb)  // "rgb(230, 0, 0)"
}


问:
Simba][ImpalaJDBCDriver](500151) Error setting/closing session in Imapala jdbc connection
I  am trying to connect to impala using JDBC connection.
Imapala driver jar used is impalaJDBC41.
Error occured while creating connection object 'con'
Error is -[Simba]ImpalaJDBCDriver Error setting/closing session in Imapala jdbc connection

Code is as below:

```<code>import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_Connection1 {
    private static String driverName = "com.cloudera.impala.jdbc41.Driver";
    public static void main(String[] args) throws SQLException {
    try {
       Class.forName(driverName);

        }
   catch (ClassNotFoundException e)
       {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.exit(1);
        }
         Connection con =   DriverManager.getConnection("jdbc:impala://host:25004/;principal=impala/host@abc.ENTERPRISENET.ORG");
         Statement stmt = con.createStatement();
         String tableName = "yogesh";
         stmt.executeQuery("drop table " + tableName);
    }

}
</code>```

答:
I had the same error (code 500151) with the Cloudera JDBC driver for Hive, and was able to solve it by adding ;SocketTimeout=0 to my connection string.

Be sure to read the documentation to make sure you're not forgetting some properties:

Configuring the Simba Hive JDBC Driver

Driver Configuration Options

Body:
I  am trying to connect to impala using JDBC connection.
Imapala driver jar used is impalaJDBC41.
Error occured while creating connection object 'con'
Error is -[Simba]ImpalaJDBCDriver Error setting/closing session in Imapala jdbc connection

Code is as below:

import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_Connection1 {
    private static String driverName = "com.cloudera.impala.jdbc41.Driver";
    public static void main(String[] args) throws SQLException {
    try {
       Class.forName(driverName);

        }
   catch (ClassNotFoundException e)
       {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.exit(1);
        }
         Connection con =   DriverManager.getConnection("jdbc:impala://host:25004/;principal=impala/host@abc.ENTERPRISENET.ORG");
         Statement stmt = con.createStatement();
         String tableName = "yogesh";
         stmt.executeQuery("drop table " + tableName);
    }

}


问:
MongoDB Unauthorized: replSetGetConfig
I am trying to setup a replica set with mongodb 3.4 and am facing the following error. Have tried searching around a bit but am not able to find a solution.

```<code>root@mongo-db-1:~# mongo MongoDB shell version v3.4.0 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.0
> use admin
switched to db admin
> db.auth('admin','****');
1
> db.system.users.find();
{ "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "DKkxOnMHCSSPwJCJyLA9Eg==", "storedKey" : "9aD//lm3eyeBN2LqZeTdqvvKXlU=", "serverKey" : "OX07H3FVQ447OqGMD7mCmX0WU0M=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
> rs.conf()
2016-12-20T09:58:45.579+0530 E QUERY    [main] Error: Could not retrieve replica set config: {
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { replSetGetConfig: 1.0 }",
    "code" : 13,
    "codeName" : "Unauthorized"
} :
rs.conf@src/mongo/shell/utils.js:1262:11
@(shell):1:1
</code>```

MongoDB Logs

```<code>2016-12-20T09:58:01.278+0530 I NETWORK  [thread1] connection accepted from 127.0.0.1:60804 #2 (1 connection now open)
2016-12-20T09:58:01.279+0530 I NETWORK  [conn2] received client metadata from 127.0.0.1:60804 conn2: { application: { name: "MongoDB Shell" }, driver: { name: "MongoDB Internal Client", version: "3.4.0" }, os: { type: "Linux", name: "Ubuntu", architecture: "x86_64", version: "14.04" } }
2016-12-20T09:58:01.282+0530 I ACCESS   [conn2] Unauthorized: not authorized on admin to execute command { getLog: "startupWarnings" }
2016-12-20T09:58:01.285+0530 I ACCESS   [conn2] Unauthorized: not authorized on admin to execute command { replSetGetStatus: 1.0, forShell: 1.0 }
2016-12-20T09:58:19.044+0530 I ACCESS   [conn2] Successfully authenticated as principal admin on admin
2016-12-20T09:58:19.046+0530 I ACCESS   [conn2] Unauthorized: not authorized on admin to execute command { replSetGetStatus: 1.0, forShell: 1.0 }
2016-12-20T09:58:45.578+0530 I ACCESS   [conn2] Unauthorized: not authorized on admin to execute command { replSetGetConfig: 1.0 }
</code>```

Is there something I am missing here?

Mongo Config

```<code>root@mongo-db-1:~# cat /etc/mongod.conf
storage:
    dbPath: /var/lib/mongodb
    journal:
        enabled: true
# where to write logging data.
systemLog:
    destination: file
    logAppend: true
    path: /var/log/mongodb/mongod.log
# network interfaces
net:
    port: 27017
    bindIp: 127.0.0.1
security:
    authorization: enabled
    keyFile: /thefile
processManagement:
    fork: true
replication:
    replSetName: rs0
</code>```

答:
You must give clusterMagnager permissions to your "admin" user. To add the clusterManager role to your admin user you have to execute the following function after you authenticate.</p>

```<code>db.grantRolesToUser(
   "admin",
   [ "clusterManager" ]
)
</code>```

Title: MongoDB Unauthorized: replSetGetConfig

Body:
I am trying to setup a replica set with mongodb 3.4 and am facing the following error. Have tried searching around a bit but am not able to find a solution.

root@mongo-db-1:~# mongo MongoDB shell version v3.4.0 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.0
> use admin
switched to db admin
> db.auth('admin','****');
1
> db.system.users.find();
{ "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "DKkxOnMHCSSPwJCJyLA9Eg==", "storedKey" : "9aD//lm3eyeBN2LqZeTdqvvKXlU=", "serverKey" : "OX07H3FVQ447OqGMD7mCmX0WU0M=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
> rs.conf()
2016-12-20T09:58:45.579+0530 E QUERY    [main] Error: Could not retrieve replica set config: {
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { replSetGetConfig: 1.0 }",
    "code" : 13,
    "codeName" : "Unauthorized"
} :
rs.conf@src/mongo/shell/utils.js:1262:11
@(shell):1:1

MongoDB Logs

2016-12-20T09:58:01.278+0530 I NETWORK  [thread1] connection accepted from 127.0.0.1:60804 #2 (1 connection now open)
2016-12-20T09:58:01.279+0530 I NETWORK  [conn2] received client metadata from 127.0.0.1:60804 conn2: { application: { name: "MongoDB Shell" }, driver: { name: "MongoDB Internal Client", version: "3.4.0" }, os: { type: "Linux", name: "Ubuntu", architecture: "x86_64", version: "14.04" } }
2016-12-20T09:58:01.282+0530 I ACCESS   [conn2] Unauthorized: not authorized on admin to execute command { getLog: "startupWarnings" }
2016-12-20T09:58:01.285+0530 I ACCESS   [conn2] Unauthorized: not authorized on admin to execute command { replSetGetStatus: 1.0, forShell: 1.0 }
2016-12-20T09:58:19.044+0530 I ACCESS   [conn2] Successfully authenticated as principal admin on admin
2016-12-20T09:58:19.046+0530 I ACCESS   [conn2] Unauthorized: not authorized on admin to execute command { replSetGetStatus: 1.0, forShell: 1.0 }
2016-12-20T09:58:45.578+0530 I ACCESS   [conn2] Unauthorized: not authorized on admin to execute command { replSetGetConfig: 1.0 }

Is there something I am missing here?

Mongo Config

root@mongo-db-1:~# cat /etc/mongod.conf
storage:
    dbPath: /var/lib/mongodb
    journal:
        enabled: true
# where to write logging data.
systemLog:
    destination: file
    logAppend: true
    path: /var/log/mongodb/mongod.log
# network interfaces
net:
    port: 27017
    bindIp: 127.0.0.1
security:
    authorization: enabled
    keyFile: /thefile
processManagement:
    fork: true
replication:
    replSetName: rs0

Body:
You must give clusterMagnager permissions to your "admin" user. To add the clusterManager role to your admin user you have to execute the following function after you authenticate.

db.grantRolesToUser(
   "admin",
   [ "clusterManager" ]
)


问:
In MarkLogic 9 how to update a column in a template that is already created
I have created a template with some x columns. Let us say I want to add one more column, how I can update the template ?

Looking into MarkLogic doc there is tde functions only for Insert.

答: The TDE API is based on whole templates. There's no command to "add this column to this template." Rather, insert the updated whole template and it will overwrite the original. </p>


问:
object name dynamic create
i have a single question,

i have this JS.

```<code>Scene.platform = new MenuItem();
Scene.platform.init(...code...);
</code>```

this works fine, but i have N platforms, how i creat dynamic?

i tryed :

```<code>for(i=0....){

Scene.platform+i = new MenuItem();
or
Scene.platform.i = new MenuItem();

}
</code>```

i need the result like that:

```<code>Scene.platform1 = new MenuItem();
Scene.platform2 = new MenuItem();
Scene.platform3 = new MenuItem();
</code>```

its possible? thanks in advance.

答:
Any time you have variables like this:

```<code>platform1
platform2
platform...
platformN
</code>```

What you really want is an array.  Give your object an array called platforms, then you can store your "platforms" in that array.  For example, if you have this:

```<code>Scene.platforms = [];
</code>```

Then you can push elements to it:

```<code>for (var i = 0; i < someAmount; i++) {
    Scene.platforms.push(new MenuItem());
}
</code>```

Title: object name dynamic create

Body:
i have a single question,

i have this JS.

Scene.platform = new MenuItem();
Scene.platform.init(...code...);

this works fine, but i have N platforms, how i creat dynamic?

i tryed :

for(i=0....){

Scene.platform+i = new MenuItem();
or
Scene.platform.i = new MenuItem();

}

i need the result like that:

Scene.platform1 = new MenuItem();
Scene.platform2 = new MenuItem();
Scene.platform3 = new MenuItem();

its possible? thanks in advance.

Body:
Any time you have variables like this:

platform1
platform2
platform...
platformN

What you really want is an array.  Give your object an array called platforms, then you can store your "platforms" in that array.  For example, if you have this:

Scene.platforms = [];

Then you can push elements to it:

for (var i = 0; i < someAmount; i++) {
    Scene.platforms.push(new MenuItem());
}


问:
`test:first job: script should be a string or an array of a strings`
I'd like to create a simple "hello, world" Gitlab CI script. I already got the Docker runner working and I'm experimenting with something like this:

```<code>image: debian:sid

test:first:
  script:
  - true
</code>```

Unfortunately, the build fails with the error: test:first job: script should be a string or an array of a strings

What am I doing wrong?

答:
Double-check your spacing on the list lines - specifically that each dash is followed by a space.  It can be an easy thing to overlook, especially if the "list" is only a single item.

(Though admittedly, that was not the cause of error in your "Hello world" CI file)

Body:
I'd like to create a simple "hello, world" Gitlab CI script. I already got the Docker runner working and I'm experimenting with something like this:

image: debian:sid

test:first:
  script:
  - true

Unfortunately, the build fails with the error: test:first job: script should be a string or an array of a strings

What am I doing wrong?


问:
Detect an indirect update to a field with jQuery
I have a <textarea> that is getting updated from a form with jquery. I might never actually enter anything into the textarea directly.

But I need to know how I can monitor changes to the textarea that aren't directly from direct input on the textarea?

I can use

```<code>$('#myTextbox').on('input', function() {
    // do something
});
</code>```

to know when the user is editing the myTextbox.

I tried

```<code>$('#myTextbox').on('change', function () {
  // do something
});
</code>```

but that didn't work either.

Is this possible?

答:
Just use keyboard command to check to see if something is happening:

```<code>$('#myTextbox').on('keydown', function () {
  // do something
});
</code>```

That way if someone ever types into it you will know. Else if you are trying to find out indirectly, you can use something that will check whenever an input is being used, so like:

```<code>$('input').on('keydown', function () {
  var checkDiv = $('#myTextbox').val();
  if(checkDiv != ""){
      // do something
  }
});
</code>```

Body:
I have a <textarea> that is getting updated from a form with jquery. I might never actually enter anything into the textarea directly.

But I need to know how I can monitor changes to the textarea that aren't directly from direct input on the textarea?

I can use

$('#myTextbox').on('input', function() {
    // do something
});

to know when the user is editing the myTextbox.

I tried

$('#myTextbox').on('change', function () {
  // do something
});

but that didn't work either.

Is this possible?

Body:
Just use keyboard command to check to see if something is happening:

$('#myTextbox').on('keydown', function () {
  // do something
});

That way if someone ever types into it you will know. Else if you are trying to find out indirectly, you can use something that will check whenever an input is being used, so like:

$('input').on('keydown', function () {
  var checkDiv = $('#myTextbox').val();
  if(checkDiv != ""){
      // do something
  }
});


问:
Minimal three.js skeleton animation?
I want to understand how three.js animates rigged models in glorious low-level detail. Here's my current code:

```<code>renderer = new THREE.WebGLRenderer();

renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);

camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 500);

camera.position.set(0, 0, 50);
camera.lookAt(new THREE.Vector3(0, 0, 0));

scene = new THREE.Scene();

var geometry = new THREE.BoxGeometry(10, 1, 1);

for (var i = 0; i < geometry.vertices.length; i++) {
    geometry.skinIndices.push(new THREE.Vector4(0, 1, 0, 0));
    geometry.skinWeights.push(new THREE.Vector4(1, 1, 0, 0));
}

var bones = [];

var bone1 = new THREE.Bone();
bone1.position.x = 5;
bones.push(bone1);

var bone2 = new THREE.Bone();
bone2.position.x = -5;
bones.push(bone2);
bone1.add(bone2);

var material = new THREE.MeshBasicMaterial({ color: 0x156289 });

var mesh = new THREE.SkinnedMesh(geometry, material);
var skeleton = new THREE.Skeleton(bones);

mesh.add(bone1);
mesh.bind(skeleton);
scene.add(mesh);

skeletonHelper = new THREE.SkeletonHelper(mesh);
skeletonHelper.material.linewidth = 2;
scene.add(skeletonHelper);

function animate() {
  requestAnimationFrame(animate);

  var time = Date.now() * 0.001;

  mesh.skeleton.bones[0].rotation.z = Math.sin(time) * 2;

  renderer.render(scene, camera);
}

animate();
</code>```

The SkeletonHelper is visibly animated but the box isn't. How do I fix my code to animate the box?

Here's a CodePen pen with the above code:

An Anonymous Pen on CodePen

答:
To fix, just add a skinning: true property to the material. So this line:

```<code>var material = new THREE.MeshBasicMaterial({ color: 0x156289 });
</code>```

would become something like this:

```<code>var material =
    new THREE.MeshBasicMaterial({
        color: 0x156289,
        skinning: true
    });
</code>```

Title: Minimal three.js skeleton animation?

Body:
I want to understand how three.js animates rigged models in glorious low-level detail. Here's my current code:

renderer = new THREE.WebGLRenderer();

renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);

camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 500);

camera.position.set(0, 0, 50);
camera.lookAt(new THREE.Vector3(0, 0, 0));

scene = new THREE.Scene();

var geometry = new THREE.BoxGeometry(10, 1, 1);

for (var i = 0; i < geometry.vertices.length; i++) {
    geometry.skinIndices.push(new THREE.Vector4(0, 1, 0, 0));
    geometry.skinWeights.push(new THREE.Vector4(1, 1, 0, 0));
}

var bones = [];

var bone1 = new THREE.Bone();
bone1.position.x = 5;
bones.push(bone1);

var bone2 = new THREE.Bone();
bone2.position.x = -5;
bones.push(bone2);
bone1.add(bone2);

var material = new THREE.MeshBasicMaterial({ color: 0x156289 });

var mesh = new THREE.SkinnedMesh(geometry, material);
var skeleton = new THREE.Skeleton(bones);

mesh.add(bone1);
mesh.bind(skeleton);
scene.add(mesh);

skeletonHelper = new THREE.SkeletonHelper(mesh);
skeletonHelper.material.linewidth = 2;
scene.add(skeletonHelper);

function animate() {
  requestAnimationFrame(animate);

  var time = Date.now() * 0.001;

  mesh.skeleton.bones[0].rotation.z = Math.sin(time) * 2;

  renderer.render(scene, camera);
}

animate();

The SkeletonHelper is visibly animated but the box isn't. How do I fix my code to animate the box?

Here's a CodePen pen with the above code:

An Anonymous Pen on CodePen

Body:
To fix, just add a skinning: true property to the material. So this line:

var material = new THREE.MeshBasicMaterial({ color: 0x156289 });

would become something like this:

var material =
    new THREE.MeshBasicMaterial({
        color: 0x156289,
        skinning: true
    });


问:
Why we use mysqli_poll() function in php?
I am totally new to php and mysql. Please can anyone tell why we use mysqli_poll() function in php ?

I found 2 questions on stack overflow:

1) How does mysqli_poll work?

2) mysqli_poll() - what's the third parameter for?

But both are different from my question. In fact i have read them but unable to understand.

Currently i am on php.net for this function and trying to understand the examples but i am too much depressed and failed to understand.

Please can anyone tell me in easy and beginners level, that what is the use of this function in php and mysql. What is means by poll in the sense of mysql database ?

Thanks in advance !!!

答:
I have a feeling this is a wrapper around a POSIX-style select call, or something similar in nature, that's used to efficiently poll multiple handles for data that can be read.

Normally select-driven code is deemed to be "polling" when it checks for data ready to be read or handles ready to be written to.

It's unlikely that most programmers have ever used this function. It has very narrow use cases, you must be juggling a non-trivial number of MySQL handles at once. Most applications use a handful, and often with a connection pool.


问:
Cordova 6.2.3 has no WebChromeClient,how can i override the onJsPrompt()?
when I update my project from cordova 3 to cordova 6,I find there is no WebChromeClient,but my project used this Class and override the onJsPrompt().
Now,how should i do base on Cordova 6  to override OnJsPrompt()
```</p>

<code>package com.qtby.gxwlc;
import org.apache.cordova.CordovaChromeClient;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import com.jsdemo.ClientTool;
import com.jsdemo.JsNativeFunc;
import android.content.Intent;
import android.webkit.JsPromptResult;
import android.webkit.WebView;
public class CustomerWebChromeClient extends CordovaChromeClient {
    public CustomerWebChromeClient(CordovaInterface ctx, CordovaWebView app){
        super(ctx, app);
    }

    JsNativeFunc jsNativeFunc;

    public JsNativeFunc getJsNativeFunc(){
        return jsNativeFunc;
    }

    public boolean isJsNativeFunc(int requestCode){
        if(jsNativeFunc == null)
            return false;
        return jsNativeFunc.isJsNativeFunc(requestCode);
    }

    public void jsResult(int requestCode, int resultCode,
            Intent intent){
        jsNativeFunc.jsResult(requestCode, resultCode, intent);
    }

    @Override
    public boolean onJsPrompt(WebView view, String origin, String message,
            String defaultValue, JsPromptResult result) {
        if(ClientTool.callNativeFunc(message)){
                return super.onJsPrompt(view, origin, message, defaultValue, result);
            }
            return true;
        }
        return super.onJsPrompt(view, origin, message, defaultValue, result);
    }
}
</code>```

答:
You do this now.

```<code>import org.apache.cordova.engine.SystemWebChromeClient;
</code>```

extends SystemWebChromeClient

https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/engine/SystemWebChromeClient.java

Cheers

Body:
when I update my project from cordova 3 to cordova 6,I find there is no WebChromeClient,but my project used this Class and override the onJsPrompt().
Now,how should i do base on Cordova 6  to override OnJsPrompt()

package com.qtby.gxwlc;
import org.apache.cordova.CordovaChromeClient;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import com.jsdemo.ClientTool;
import com.jsdemo.JsNativeFunc;
import android.content.Intent;
import android.webkit.JsPromptResult;
import android.webkit.WebView;
public class CustomerWebChromeClient extends CordovaChromeClient {
    public CustomerWebChromeClient(CordovaInterface ctx, CordovaWebView app){
        super(ctx, app);
    }

    JsNativeFunc jsNativeFunc;

    public JsNativeFunc getJsNativeFunc(){
        return jsNativeFunc;
    }

    public boolean isJsNativeFunc(int requestCode){
        if(jsNativeFunc == null)
            return false;
        return jsNativeFunc.isJsNativeFunc(requestCode);
    }

    public void jsResult(int requestCode, int resultCode,
            Intent intent){
        jsNativeFunc.jsResult(requestCode, resultCode, intent);
    }

    @Override
    public boolean onJsPrompt(WebView view, String origin, String message,
            String defaultValue, JsPromptResult result) {
        if(ClientTool.callNativeFunc(message)){
                return super.onJsPrompt(view, origin, message, defaultValue, result);
            }
            return true;
        }
        return super.onJsPrompt(view, origin, message, defaultValue, result);
    }
}

Body:
You do this now.

import org.apache.cordova.engine.SystemWebChromeClient;

extends SystemWebChromeClient

https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/engine/SystemWebChromeClient.java

Cheers


问:
How can I push to a mysql database from Mamp to my domain?
I just made a blog post on my localhost machine (I.E. Draft) now I want to update the remote MYSQL database that is now running on the machine.

So in analgous terms when uploading the files, I just run PHPStorm and include upload to remote database, is there a way to do that or a PHP file that will administrate the process

My pseudocode guess will be:

localhost:admin.php

if publish clicked, connect to remote sql and copy entry.

答:
If I understood correctly you need to remotely access your database right?
If so you have some options, starting with:

1) Use a tunnel over ssh with mysql workbench!

How? Example Here: Standard TCP/IP over SSH Connection Method

You can import your local database by reverse engineering and after that simply accessing to database menu, you can synchronise model with remote database etc. That is to grant that both databases have the same structure. You can put your sql and execute as well... there are plenty of options here.

2) You can also access your remote database with a data source under PHPSTORM. here it is how you can do it! Managing Data Sources

3) Via terminal, if you have access to root simple scp your sql file to remote and after that well update remote database.

Backup database: mysqldump -u username -p database_to_backup > backup_name.sql

Restore database mysql -u username -p database_name < backup_name.sql

4) Make you sql server accessible to the world (not recommended)!
Steps include creating a new user or upgrade an existent user privileges options are wide here.

Read this article: it says pretty much everything!

5) Install phpmyadmin (not recommended)