问:
Spring boot application deployment fails with JNDI warnings when custom logback-spring.xml included
Spring boot application deployment fails with JNDI debub messages when custom logback settings file (logback-spring.xml) included. This happens only in linux environment and in windows environment application runs without any issue even though same debug message are shown.

Few of long list of debug messages

```<code>15:33:22.537 [https-jsse-nio-8443-exec-70] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/logging.exception-conversion-word]
15:33:22.540 [https-jsse-nio-8443-exec-70] DEBUG org.springframework.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/logging.exception-conversion-word] not found - trying original name [logging.exception-conversion-word]. javax.naming.NameNotFoundException: Name [logging.exception-conversion-word] is not bound in this Context. Unable to find [logging.exception-conversion-word].
15:33:22.540 [https-jsse-nio-8443-exec-70] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [logging.exception-conversion-word]
15:33:22.540 [https-jsse-nio-8443-exec-70] DEBUG org.springframework.jndi.JndiPropertySource - JNDI lookup for name [logging.exception-conversion-word] threw NamingException with message: Name [logging.exception-conversion-word] is not bound in this Context. Unable to find [logging.exception-conversion-word].. Returning null.
</code>```

POM file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<artifactId>licenserequestsimulator</artifactId>
<packaging>war</packaging>
<name>License Request Simulator</name>
<description>License Request Simulator</description>
<url>https://pronto.net/</url>
<version>1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>com.ibm.informix</groupId>
        <artifactId>jdbc</artifactId>
        <version>4.10.7.20160517</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.42</version>
    </dependency>

    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.7</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

logback-spring.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<configuration>

<include resource="org/springframework/boot/logging/logback/base.xml"/>
<property name="DEV_HOME" value="/logs/prontolicensing/" />
<property resource="application.properties" />

<!-- Datasource connection example -->
<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
    <connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource">
        <dataSource class="org.apache.tomcat.jdbc.pool.DataSource">
            <driverClassName>${spring.datasource.driver-class-name}</driverClassName>
            <url>${spring.datasource.url}</url>
            <username>${spring.datasource.username}</username>
            <password>${spring.datasource.password}</password>
        </dataSource>
    </connectionSource>
</appender>
<!-- Datasource connection example ends-->

<!--File appender-->
<appender name="fileAppender"
          class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${DEV_HOME}/pronto-licensing-file.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} - %msg%n
        </Pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        rollover daily
        <fileNamePattern>
            ${DEV_HOME}/archived/pronto-licensing-file.%d{yyyy-MM-dd}.%i.log
        </fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
            class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>
</appender>

<logger name="fileLogger" level="INFO" additivity="false">
    <appender-ref ref="fileAppender" />
</logger>
<!--File appender ends-->

<root level="ERROR">
    <appender-ref ref="DB" />
</root>
</code>```

What should I do to overcome this?

答:
Try just change logback-spring.xml to logback.xml.

In that case Spring Boot don't configure logback with its templates (like mentioned here).

All messages about JNDI names should just gone - like logback autoconfiguraton features in Spring Boot.

Body:
Spring boot application deployment fails with JNDI debub messages when custom logback settings file (logback-spring.xml) included. This happens only in linux environment and in windows environment application runs without any issue even though same debug message are shown.

Few of long list of debug messages

15:33:22.537 [https-jsse-nio-8443-exec-70] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/logging.exception-conversion-word]
15:33:22.540 [https-jsse-nio-8443-exec-70] DEBUG org.springframework.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/logging.exception-conversion-word] not found - trying original name [logging.exception-conversion-word]. javax.naming.NameNotFoundException: Name [logging.exception-conversion-word] is not bound in this Context. Unable to find [logging.exception-conversion-word].
15:33:22.540 [https-jsse-nio-8443-exec-70] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [logging.exception-conversion-word]
15:33:22.540 [https-jsse-nio-8443-exec-70] DEBUG org.springframework.jndi.JndiPropertySource - JNDI lookup for name [logging.exception-conversion-word] threw NamingException with message: Name [logging.exception-conversion-word] is not bound in this Context. Unable to find [logging.exception-conversion-word].. Returning null.

POM file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<artifactId>licenserequestsimulator</artifactId>
<packaging>war</packaging>
<name>License Request Simulator</name>
<description>License Request Simulator</description>
<url>https://pronto.net/</url>
<version>1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>com.ibm.informix</groupId>
        <artifactId>jdbc</artifactId>
        <version>4.10.7.20160517</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.42</version>
    </dependency>

    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.7</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

logback-spring.xml

    <?xml version="1.0" encoding="UTF-8"?>
<configuration>

<include resource="org/springframework/boot/logging/logback/base.xml"/>
<property name="DEV_HOME" value="/logs/prontolicensing/" />
<property resource="application.properties" />

<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
    <connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource">
        <dataSource class="org.apache.tomcat.jdbc.pool.DataSource">
            <driverClassName>${spring.datasource.driver-class-name}</driverClassName>
            <url>${spring.datasource.url}</url>
            <username>${spring.datasource.username}</username>
            <password>${spring.datasource.password}</password>
        </dataSource>
    </connectionSource>
</appender>

<appender name="fileAppender"
          class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${DEV_HOME}/pronto-licensing-file.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} - %msg%n
        </Pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        rollover daily
        <fileNamePattern>
            ${DEV_HOME}/archived/pronto-licensing-file.%d{yyyy-MM-dd}.%i.log
        </fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
            class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>
</appender>

<logger name="fileLogger" level="INFO" additivity="false">
    <appender-ref ref="fileAppender" />
</logger>

<root level="ERROR">
    <appender-ref ref="DB" />
</root>

What should I do to overcome this?


来源: stackexchange

问:
Can I make a constructor that deserializes a string version of my object?
I'm serializing and deserializing an object (TComponent descendant) using the example in the ComponentToString section in the Delphi help file.  This is so I can store the object in a VARCHAR field in the database.

When I need to instantiate a new instance of my class from a string stored in the database, can I do that using a constructor of the form CreateFromString(AOwner: TComponent; AData: String)?  Or do I have to use a non-class method that returns an instance of my component class?

If I can use the constructor version, how to I "map" the return value of ReadComponent to the "self" that is being created by the constructor?

Here's the deserialization example from the help file:

```<code>function StringToComponentProc(Value: string): TComponent;
var
  StrStream:TStringStream;
  BinStream: TMemoryStream;
begin
  StrStream := TStringStream.Create(Value);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Seek(0, soFromBeginning);
      Result:= BinStream.ReadComponent(nil);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;
</code>```

答:
You can do this by a class (static) method, but not via a constructor.

Delphis' constructors are called by compiler intrinsic on the just-created instance, which is already partially initialized (it's of the desired class and instance/field storage is zeroed-out).

If you see the source of TStream.ReadComponent, you'll find that the components' real class is read from the source stream at first, then an empty instance is constructed and filled by RTTI from the stream and returned as the result. Which means:

To use TStream.ReadComponent, you'll need to register your class to Delphis' streaming system via RegisterClass.

ContentLicense: CC BY-SA 3.0

Body:
I'm serializing and deserializing an object (TComponent descendant) using the example in the ComponentToString section in the Delphi help file.  This is so I can store the object in a VARCHAR field in the database.

When I need to instantiate a new instance of my class from a string stored in the database, can I do that using a constructor of the form CreateFromString(AOwner: TComponent; AData: String)?  Or do I have to use a non-class method that returns an instance of my component class?

If I can use the constructor version, how to I "map" the return value of ReadComponent to the "self" that is being created by the constructor?

Here's the deserialization example from the help file:

function StringToComponentProc(Value: string): TComponent;
var
  StrStream:TStringStream;
  BinStream: TMemoryStream;
begin
  StrStream := TStringStream.Create(Value);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Seek(0, soFromBeginning);
      Result:= BinStream.ReadComponent(nil);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;

ContentLicense: CC BY-SA 2.5


问:
Multiple Ajax Queries on Ready Function in Jquery
I have a table something like the below image

I want to fill in the "ROL" column with data after the page is loaded via jquery .get method

To do that I am using the below mentioned code

```<code>$(function() {
    setTimeout(function() {
        $('.details').each(function() {
            locid = $(this).find('.locationId').html();
            prodid = $(this).find('.productId').html();
            alert(prodid);
            roqty = $(this).find('.roqty');

            $.get('myUrl', null, function(d) {
                CC = JSON.parse(d);
                roqty.html(CC.roqty);
            });
        });
    }, 5000);
})
</code>```

After the page is loaded only the last cell of ROL column is get filled. Please see the below image.

Although the alert is happening 3 times.
What could be the issue?

答:
Since you have defined roqty  as Global variable it's reference is updated to last element while waiting for $.get('myUrl') to complete.

Define roqty as  local variable scoped to each() callback function.

```<code>var roqty = $(this).find('.roqty');
</code>```

Body:
I have a table something like the below image

I want to fill in the "ROL" column with data after the page is loaded via jquery .get method

To do that I am using the below mentioned code

$(function() {
    setTimeout(function() {
        $('.details').each(function() {
            locid = $(this).find('.locationId').html();
            prodid = $(this).find('.productId').html();
            alert(prodid);
            roqty = $(this).find('.roqty');

            $.get('myUrl', null, function(d) {
                CC = JSON.parse(d);
                roqty.html(CC.roqty);
            });
        });
    }, 5000);
})

After the page is loaded only the last cell of ROL column is get filled. Please see the below image.

Although the alert is happening 3 times.
What could be the issue?

Body:
Since you have defined roqty  as Global variable it's reference is updated to last element while waiting for $.get('myUrl') to complete.

Define roqty as  local variable scoped to each() callback function.

var roqty = $(this).find('.roqty');


问:
multiDexKeepFile ignored / not working
My application is a custom class that extends MultiDexApplication.

```<code>public class CustomApp extends MultiDexApplication {
    @Override
    public void onCreate() {
        super.onCreate();
        //TODO
    }
}
</code>```

In my AndroidManifest.xml :

```<code><application
        android:name=".helper.CustomApp"
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="${app_name}"
        android:largeHeap="true"
        android:screenOrientation="portrait"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:allowBackup, android:label">
</code>```

When I try to run the apk on a samsung s6 (API 7.0), everything works fine. BUT, when I try to run it on a THOMSON (API 4.2.2), I get this error :

```<code>FATAL EXCEPTION: main
                                                            java.lang.RuntimeException: Unable to instantiate application me.blu.app.helper.CustomApp: java.lang.ClassNotFoundException: Didn't find class "me.blu.app.helper.CustomApp" on path: DexPathList[[zip file "/data/app/me.blu.app-1.apk"],nativeLibraryDirectories=[/data/app-lib/me.blu.app-1, /vendor/lib, /system/lib]]
                                                                at android.app.LoadedApk.makeApplication(LoadedApk.java:504)
</code>```

So this I did that - I created a multidex-config.txt and added this line :

```<code>me/blu/app/helper/CustomApp.class
</code>```

This file is located right next to my build.gradle file as needed.

Then I added this multiDexKeepFile file('multidex-config.txt') in my two builTypes but ALSO below multiDexEnabled true.

It's still not working. I would higly appreciate some help ^^

Thanks.

答:
I once facing with the same problems eventhough had adding the multidex. The problem arise whenever apk is running in Android 4.4 Xiaomi (If I remember it correctly). To solution is using MultiDex.install() in app like this:

```<code>public class CustomApp extends Application {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}
</code>```

Then adding the jumboMode true in module build.gradle:

```<code>android {
    ...
    dexOptions {
        jumboMode = true
    }

}
</code>```

Title: multiDexKeepFile ignored / not working

Body:
My application is a custom class that extends MultiDexApplication.

public class CustomApp extends MultiDexApplication {
    @Override
    public void onCreate() {
        super.onCreate();
        //TODO
    }
}

In my AndroidManifest.xml :

<application
        android:name=".helper.CustomApp"
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="${app_name}"
        android:largeHeap="true"
        android:screenOrientation="portrait"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:allowBackup, android:label">

When I try to run the apk on a samsung s6 (API 7.0), everything works fine. BUT, when I try to run it on a THOMSON (API 4.2.2), I get this error :

FATAL EXCEPTION: main
                                                            java.lang.RuntimeException: Unable to instantiate application me.blu.app.helper.CustomApp: java.lang.ClassNotFoundException: Didn't find class "me.blu.app.helper.CustomApp" on path: DexPathList[[zip file "/data/app/me.blu.app-1.apk"],nativeLibraryDirectories=[/data/app-lib/me.blu.app-1, /vendor/lib, /system/lib]]
                                                                at android.app.LoadedApk.makeApplication(LoadedApk.java:504)

So this I did that - I created a multidex-config.txt and added this line :

me/blu/app/helper/CustomApp.class

This file is located right next to my build.gradle file as needed.

Then I added this multiDexKeepFile file('multidex-config.txt') in my two builTypes but ALSO below multiDexEnabled true.

It's still not working. I would higly appreciate some help ^^

Thanks.

Body:
I once facing with the same problems eventhough had adding the multidex. The problem arise whenever apk is running in Android 4.4 Xiaomi (If I remember it correctly). To solution is using MultiDex.install() in app like this:

public class CustomApp extends Application {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}

Then adding the jumboMode true in module build.gradle:

android {
    ...
    dexOptions {
        jumboMode = true
    }

}


问:
Jenkins: Parameterize triggered job's name OR Link two multi-configuration jobs
My company produces a product in multiple flavors, on Linux and Android for example. On Jenkins, these are produced on a multi-configuration job.

I need to build a wrapper to the product on a different job. My manager insists that the wrapper and the product be built on separate jobs.

My problem is, I cannot seem to be able to pass axis variables.
Using the parameterized build plugin, "Trigger parameterized build on other projects" doesn't take parameters (how terribly ironic), and axis variables seem to be ignored (see example image).

Does anyone have a viable solution?

jenkins_example

答:
So here's my own answer for now:

It seems that linking matrix jobs on child job basis is impossible (or impractical. You could theoretically make a huge flexible publish if/else, but I didn't try that).

Instead I now build the whole second matrix once the first matrix is done. I trigger it like this:
Triggering the matrix

And I copy the artifacts like this:
Copying the artifacts


问:
ssh login using expect to directly login using c
I have created a c program using expect to login a server using ssh, the following is the program

```<code>#include <sys/wait.h>
#include <tcl8.6/expect.h>
int main()
{
exp_is_debugging = 0;
exp_timeout = 60;

FILE *expect = exp_popen((char *) "ssh user@ip");
if (expect == 0) {
    return 1;
}

enum { denied, invalid, command_not_found,
        command_failed, prompt };

switch (exp_fexpectl(expect,
            exp_glob, "password: ", prompt,
            exp_end)) {
    case prompt:
            // continue
            break;
    case EXP_TIMEOUT:
            return 1;
}

   fprintf(expect, "%s\r","password");

 switch (exp_fexpectl(expect,
            exp_glob, "denied", denied, // 1 case
            exp_glob, "invalid password", invalid, // another case
            exp_glob, "#", prompt, // third case
            exp_end)) {
    case denied:
    printf("denied %d",exp_glob);
             break;
    case invalid:
            break;
    case EXP_TIMEOUT:
    printf("EXP_TIMEOUT");
            break;
    case prompt:
            printf("loggedin");
            break;
    default:
    //return 0;
            break;
}
}
</code>```

I am able to login to the server but it immediately gone to my terminal after this, what i am looking to login to the server and need to interact with that terminal. Now, it is showing my terminal after that, do anyone have any idea on this ? i need to stay on that logged server's terminal

答:
I don't see any loop in your program. You just expect some output from your child process (ssh), reply accordingly, and finally terminate. When you terminate, your child process terminates as well. You'd have to indefinitely forward I/O between your stdin/stdout and the child process to achieve what you want.

That said, this whole idea is flawed. You just want to launch ssh and have the login done automatically, but use the shell interactively? There's no need to write code for that, have a look at ssh-agent and how to create an ssh key.

Body:
I have created a c program using expect to login a server using ssh, the following is the program

#include <sys/wait.h>
#include <tcl8.6/expect.h>
int main()
{
exp_is_debugging = 0;
exp_timeout = 60;

FILE *expect = exp_popen((char *) "ssh user@ip");
if (expect == 0) {
    return 1;
}

enum { denied, invalid, command_not_found,
        command_failed, prompt };

switch (exp_fexpectl(expect,
            exp_glob, "password: ", prompt,
            exp_end)) {
    case prompt:
            // continue
            break;
    case EXP_TIMEOUT:
            return 1;
}

   fprintf(expect, "%s\r","password");

 switch (exp_fexpectl(expect,
            exp_glob, "denied", denied, // 1 case
            exp_glob, "invalid password", invalid, // another case
            exp_glob, "#", prompt, // third case
            exp_end)) {
    case denied:
    printf("denied %d",exp_glob);
             break;
    case invalid:
            break;
    case EXP_TIMEOUT:
    printf("EXP_TIMEOUT");
            break;
    case prompt:
            printf("loggedin");
            break;
    default:
    //return 0;
            break;
}
}

I am able to login to the server but it immediately gone to my terminal after this, what i am looking to login to the server and need to interact with that terminal. Now, it is showing my terminal after that, do anyone have any idea on this ? i need to stay on that logged server's terminal


问:
Spa app w/ Web API security concern. Can a logged in user with a JWT make random requests to API
I have a security concern about building a SPA application.

What is stopping an end user to make calls to my Web API as long as they have a token?

For example: I am an end user to a Spa web application and I login through the login form. Get access to the JWT token provided to me (assuming this is easy). Then open up postman and try making every call possible putting that token in the header of every request.

I am assuming the only calls I would be able to make are the ones I would be authorized to make through the UI due to Web API authorization.

Is there any type of security out there to prevent this or is it basically just make sure your Web API has proper authorization?

答: There is absolutely no difference here to regular websites/web applications. Yes, anyone can try to make any HTTP calls they wish to your server. That holds for plain websites, jQuery sites, SPA sites, mobile applications or Flash games. Your server needs to do the proper authorisation and validation to ensure the user is allowed to do what they're attempting to do.


问:
Unable to auto-detect email address
I'm new to SmartGit. I can't commit through my repository, the message I'm receiving is:

```<code>Unable to auto-detect email address (got 'Arreane@Arreane-PC.(none)')

*** Please tell me who you are.

Run
  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.

Omit --global to set the identity only in this repository
</code>```

I'm using a different PC, but if I commit at home it commits and pushes perfectly, I don't know if this was the cause of the problem.

I've searched around and others say to edit the .git/config file, but I cannot find this file.

What am I missing?

答:
Just type like "correct" case

"wrong"

```<code>git config --global mike.email "mike@gmail.com"
git config --global mike.name  "mike"
</code>```

"correct"

```<code>git config --global user.email "mike@gmail.com"
git config --global user.name "mike"
</code>```

user.name is your account name in git-hub
user.email is your email when you sign in git-hub.

Title: Unable to auto-detect email address

Body:
I'm new to SmartGit. I can't commit through my repository, the message I'm receiving is:

Unable to auto-detect email address (got 'Arreane@Arreane-PC.(none)')

*** Please tell me who you are.

Run
  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.

Omit --global to set the identity only in this repository

I'm using a different PC, but if I commit at home it commits and pushes perfectly, I don't know if this was the cause of the problem.

I've searched around and others say to edit the .git/config file, but I cannot find this file.

What am I missing?

Body:
Just type like "correct" case

"wrong"

git config --global mike.email "mike@gmail.com"
git config --global mike.name  "mike"

"correct"

git config --global user.email "mike@gmail.com"
git config --global user.name "mike"

user.name is your account name in git-hub
user.email is your email when you sign in git-hub.


问:
WPF Entity Framework with multiple databases
I am developing a WPF application which uses different databases. The database is selected from a combobox on every form and fills the data grid with the data.

The problem I have is this: one of the databases has a table Projects, the rest of the databases don't have this table. Depending on the database, there are two queries which fill the datagrid.

The problem I am having is when start the application and select the database which doesn't have Project table, then select the database which has the project table from the combobox, I am getting the following error:

"System.NotSupportedException occurred   HResult=0x80131515

  Message=The specified type member 'ProjectCode' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

Here is my code:

```<code>    private void GetTemplates()
    {
        List<string> result = new List<string>();
        if (CrsInterfaceDbDataContext.DbSelector == StringEnum.GetStringValue(DatabaseHelper.GiCrsUtms))
        {
            try
            {
                using (var db = new CrsInterfaceDbDataContext())
                {
                    string projectCode = CrsInterfaceDbDataContext.ProjectCode;

                    if (projectCode != null)
                    {
                        var templates = (from c in db.ClientProducts
                                         join ps in db.ClientProductStatuses on c.ClientProductStatusID equals ps
                                             .ClientProductStatusID
                                         join pr in db.Projects on c.ProjectCode equals pr.ProjectCode
                                         join s in db.ClientProductStatuses on c.ClientProductStatusID equals s
                                             .ClientProductStatusID
                                         join pc in db.ClientProductComponents on c.ClientProductID equals pc.ClientProductID
                                         join f in db.GiFilename on c.FileNameID equals f.FileNameID
                                         join fg in db.GiFileGroups on f.FileGroupID equals fg.FileGroupID
                                         join mp in db.GiMailParamses on fg.FileGroupID equals mp.FileGroupID
                                         join cco in db.ClientComponent on pc.ClientComponentID equals cco.ClientComponentID
                                         join ct in db.GiComponentType on cco.ClientComponentTypeID equals ct
                                             .ClientComponentTypeID
                                         where (c.ProjectCode == projectCode)

                                         select new
                                         {
                                             c.ClientProductID,
                                             c.ClientProductName,
                                             StatusDescription = ps.Description,
                                             c.MailingRegion,
                                             FileName = f.Filename,
                                             FileGroup = fg.Description,
                                             c.Description,
                                             c.Duplex,
                                             mp.Carrier,
                                             mp.ServiceLevel,
                                             pc.Qty,
                                             ClientComponetType = ct.Description,
                                             c.ProjectCode,
                                             pr.ProjectName
                                         }).ToList();

                        DgTemplates.ItemsSource = templates;
                        LblTotalRecords.Content = "Total records: " + templates.Count();

                    }

                }
            }
            catch (InvalidOperationException ex)
            {
                lblError.Content = "Database not selected";
            }
        }
        else
        {
            try
            {
                using (var db = new CrsInterfaceDbDataContext())
                {
                    var templates = (from c in db.ClientProducts
                                     join ps in db.ClientProductStatuses on c.ClientProductStatusID equals ps
                                         .ClientProductStatusID
                                     join s in db.ClientProductStatuses on c.ClientProductStatusID equals s.ClientProductStatusID
                                     join pc in db.ClientProductComponents on c.ClientProductID equals pc.ClientProductID
                                     join f in db.GiFilename on c.FileNameID equals f.FileNameID
                                     join fg in db.GiFileGroups on f.FileGroupID equals fg.FileGroupID
                                     join cco in db.ClientComponent on pc.ClientComponentID equals cco.ClientComponentID
                                     join ct in db.GiComponentType on cco.ClientComponentTypeID equals ct
                              .ClientComponentTypeID
                                     select new
                                     {
                                         c.ClientProductID,
                                         c.ClientProductName,
                                         StatusDescription = ps.Description,
                                         c.MailingRegion,
                                         FileName = f.Filename,
                                         FileGroup = fg.Description,
                                         c.Description,
                                         c.Duplex,
                                         ServiceLevel = c.Class,
                                         c.Carrier,
                                     }).ToList();

                    DgTemplates.ItemsSource = templates;
                    LblTotalRecords.Content = "Total records: " + templates.Count();

                }

            }
            catch (InvalidOperationException ex)
            {
                lblError.Content = "Database not selected";
            }
        }
    }
</code>```

答: I found  a solution. I have created separate DBContext for each database. As all databases are not quite identical this was a challenge. Context for each database works perfect</p>

Body:
I am developing a WPF application which uses different databases. The database is selected from a combobox on every form and fills the data grid with the data.

The problem I have is this: one of the databases has a table Projects, the rest of the databases don't have this table. Depending on the database, there are two queries which fill the datagrid.

The problem I am having is when start the application and select the database which doesn't have Project table, then select the database which has the project table from the combobox, I am getting the following error:

"System.NotSupportedException occurred   HResult=0x80131515

  Message=The specified type member 'ProjectCode' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

Here is my code:

    private void GetTemplates()
    {
        List<string> result = new List<string>();
        if (CrsInterfaceDbDataContext.DbSelector == StringEnum.GetStringValue(DatabaseHelper.GiCrsUtms))
        {
            try
            {
                using (var db = new CrsInterfaceDbDataContext())
                {
                    string projectCode = CrsInterfaceDbDataContext.ProjectCode;

                    if (projectCode != null)
                    {
                        var templates = (from c in db.ClientProducts
                                         join ps in db.ClientProductStatuses on c.ClientProductStatusID equals ps
                                             .ClientProductStatusID
                                         join pr in db.Projects on c.ProjectCode equals pr.ProjectCode
                                         join s in db.ClientProductStatuses on c.ClientProductStatusID equals s
                                             .ClientProductStatusID
                                         join pc in db.ClientProductComponents on c.ClientProductID equals pc.ClientProductID
                                         join f in db.GiFilename on c.FileNameID equals f.FileNameID
                                         join fg in db.GiFileGroups on f.FileGroupID equals fg.FileGroupID
                                         join mp in db.GiMailParamses on fg.FileGroupID equals mp.FileGroupID
                                         join cco in db.ClientComponent on pc.ClientComponentID equals cco.ClientComponentID
                                         join ct in db.GiComponentType on cco.ClientComponentTypeID equals ct
                                             .ClientComponentTypeID
                                         where (c.ProjectCode == projectCode)

                                         select new
                                         {
                                             c.ClientProductID,
                                             c.ClientProductName,
                                             StatusDescription = ps.Description,
                                             c.MailingRegion,
                                             FileName = f.Filename,
                                             FileGroup = fg.Description,
                                             c.Description,
                                             c.Duplex,
                                             mp.Carrier,
                                             mp.ServiceLevel,
                                             pc.Qty,
                                             ClientComponetType = ct.Description,
                                             c.ProjectCode,
                                             pr.ProjectName
                                         }).ToList();

                        DgTemplates.ItemsSource = templates;
                        LblTotalRecords.Content = "Total records: " + templates.Count();

                    }

                }
            }
            catch (InvalidOperationException ex)
            {
                lblError.Content = "Database not selected";
            }
        }
        else
        {
            try
            {
                using (var db = new CrsInterfaceDbDataContext())
                {
                    var templates = (from c in db.ClientProducts
                                     join ps in db.ClientProductStatuses on c.ClientProductStatusID equals ps
                                         .ClientProductStatusID
                                     join s in db.ClientProductStatuses on c.ClientProductStatusID equals s.ClientProductStatusID
                                     join pc in db.ClientProductComponents on c.ClientProductID equals pc.ClientProductID
                                     join f in db.GiFilename on c.FileNameID equals f.FileNameID
                                     join fg in db.GiFileGroups on f.FileGroupID equals fg.FileGroupID
                                     join cco in db.ClientComponent on pc.ClientComponentID equals cco.ClientComponentID
                                     join ct in db.GiComponentType on cco.ClientComponentTypeID equals ct
                              .ClientComponentTypeID
                                     select new
                                     {
                                         c.ClientProductID,
                                         c.ClientProductName,
                                         StatusDescription = ps.Description,
                                         c.MailingRegion,
                                         FileName = f.Filename,
                                         FileGroup = fg.Description,
                                         c.Description,
                                         c.Duplex,
                                         ServiceLevel = c.Class,
                                         c.Carrier,
                                     }).ToList();

                    DgTemplates.ItemsSource = templates;
                    LblTotalRecords.Content = "Total records: " + templates.Count();

                }

            }
            catch (InvalidOperationException ex)
            {
                lblError.Content = "Database not selected";
            }
        }
    }


问:
How do I import an excel spreadsheet into SQL Server?
I need to import an excel spreadsheet into SQL Server 2005.  What steps would I need to take to accomplish that?</p>

答:
An alternative quick and (very) dirty solution is to add a formula to the excel sheet, like this:

```<code>="INSERT INTO table1(col1, col2, col3) SELECT " & A1 & ", '" & B1 & "', '" & C1 & "'"
</code>```

Copy this down (CTRL+D) and you're good to go.

OwnerDisplayName: Fiona

LastEditorDisplayName: Onorio Catenacci

Body:
An alternative quick and (very) dirty solution is to add a formula to the excel sheet, like this:

="INSERT INTO table1(col1, col2, col3) SELECT " & A1 & ", '" & B1 & "', '" & C1 & "'"

Copy this down (CTRL+D) and you're good to go.

OwnerDisplayName: Edoode


问:
Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?
I am getting the below exception on app launch.

```<code>java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.vfirst.ifbagro-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.vfirst.ifbagro-1, /vendor/lib, /system/lib]]
at android.app.ActivityThread.installProvider(ActivityThread.java:4993)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4596)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4536)
at android.app.ActivityThread.access$1300(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5214)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.vfirst.ifbagro-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.vfirst.ifbagro-1, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
at android.app.ActivityThread.installProvider(ActivityThread.java:4978)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4596)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4536)
at android.app.ActivityThread.access$1300(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5214)
at java.lang.reflect.Method.invokeNative(Native Method)
</code>```

Here is the the app level build.gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'android-apt'

android {
compileSdkVersion 24
buildToolsVersion "24.0.1"

defaultConfig {
    applicationId "com.vfirst.ifbagro"
    minSdkVersion 17
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
compile 'com.google.android.gms:play-services-location:9.4.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.firebase:firebase-messaging:9.4.0'
compile 'com.google.android.gms:play-services:9.4.0'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

This is my application level build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.0'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    classpath 'com.google.gms:google-services:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
     delete rootProject.buildDir
}
</code>```

How to solve the issue?

答:
1: Go to the gradle enable multiDexEnabled and add the multidex library in the dependencies.

```<code>android {
   ...
   defaultConfig {
      multiDexEnabled true
      ...
   }
}

dependencies {
  // add dependency
  implementation 'com.android.support:multidex:1.0.1'
}
</code>```

2: Go to the Manifest file and write android:name=".MyApplication" (Class name(MyApplication) is optional you can write whatever you want ).

```<code>    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        .
        .
        .
        .
        .
    </application>
</code>```

3: As you wrote android:name=".MyApplication" Inside Application at Manifest file. it will give you an error because you didn't create MyApplication class. Create MyApplication Class extend it by "application" class or Simply click on.MyApplication, a small red balloon appear on the left side of a syntax click on it, you will see (create MyApplication class) in the menu, click on it and Include below Method Inside that class.

```<code>    public class MyApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
</code>```

If you want to get more information then Click on this Link:[https://developer.android.com/studio/build/multidex.html]

Hopefully, It works for you.

Body:
I am getting the below exception on app launch.

java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.vfirst.ifbagro-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.vfirst.ifbagro-1, /vendor/lib, /system/lib]]
at android.app.ActivityThread.installProvider(ActivityThread.java:4993)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4596)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4536)
at android.app.ActivityThread.access$1300(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5214)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.vfirst.ifbagro-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.vfirst.ifbagro-1, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
at android.app.ActivityThread.installProvider(ActivityThread.java:4978)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4596)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4536)
at android.app.ActivityThread.access$1300(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5214)
at java.lang.reflect.Method.invokeNative(Native Method)

Here is the the app level build.gradle

apply plugin: 'com.android.application'
apply plugin: 'android-apt'

android {
compileSdkVersion 24
buildToolsVersion "24.0.1"

defaultConfig {
    applicationId "com.vfirst.ifbagro"
    minSdkVersion 17
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
compile 'com.google.android.gms:play-services-location:9.4.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.firebase:firebase-messaging:9.4.0'
compile 'com.google.android.gms:play-services:9.4.0'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

This is my application level build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.0'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    classpath 'com.google.gms:google-services:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
     delete rootProject.buildDir
}

How to solve the issue?

Body:
1: Go to the gradle enable multiDexEnabled and add the multidex library in the dependencies.

android {
   ...
   defaultConfig {
      multiDexEnabled true
      ...
   }
}

dependencies {
  // add dependency
  implementation 'com.android.support:multidex:1.0.1'
}

2: Go to the Manifest file and write android:name=".MyApplication" (Class name(MyApplication) is optional you can write whatever you want ).

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        .
        .
        .
        .
        .
    </application>

3: As you wrote android:name=".MyApplication" Inside Application at Manifest file. it will give you an error because you didn't create MyApplication class. Create MyApplication Class extend it by "application" class or Simply click on.MyApplication, a small red balloon appear on the left side of a syntax click on it, you will see (create MyApplication class) in the menu, click on it and Include below Method Inside that class.

    public class MyApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

If you want to get more information then Click on this Link:[https://developer.android.com/studio/build/multidex.html]

Hopefully, It works for you.

ContentLicense: CC BY-SA 4.0


问:
MVC Razor - BeginForm with Anchor Action
I have a contact form that is near the bottom of the page, and requires scrolling to get to; when the form is submitted, the page is reloaded, and I need for the page to go to an anchor, at the contact form. When I change the action of the BeginForm, the '#' within the anchor is encoded to '%23' - how do I stop this form happening?

I need this to function without the use of any JavaScript.

```<code>@{
    using (Html.BeginForm(null, null, new { ReturnURL = "#contact" }, FormMethod.Post, new { novalidate = "novalidate" }))
    {
        //Fields...

        <button type="submit">Submit</button>
    }
}
</code>```

The above code will return the following HTML, and will not go to the anchor:

```<code><form action="/en/Home/Contact?ReturnURL=%23contact" method="post" novalidate="novalidate">
</code>```

While the following HTML would (but I don't know how to generate it with Razor):

```<code><form action="/en/Home/Contact?ReturnURL=#contact" method="post" novalidate="novalidate">
</code>```

I've also tried the following, but the '#' is always encoded:

```<code>using (Html.BeginForm(null, null, new { ReturnURL = HttpUtility.HtmlDecode("#contact") }, FormMethod.Post, new { novalidate = "novalidate" }))

using (Html.BeginForm(null, null, new { ReturnURL = HttpUtility.UrlDecode("#contact") }, FormMethod.Post, new { novalidate = "novalidate" }))

using (Html.BeginForm(new { action = Url.Action("Index", "Home") + Html.Raw("Contact/#contact") }))
</code>```

答:
It seems that using the keyword 'action' overwrites the form's action - the following code is a solution:

```<code>using (Html.BeginForm(null, null, FormMethod.Post, new { action = "#contact" }))
</code>```

On submission, the user will be sent to site.com/#contact

For sites where the form isn't on the index/home/front page, I've used the following to build a route:

```<code>using (Html.BeginForm(null, null, FormMethod.Post,
  new { action = string.Format("{0}/{1}#contact",
        ViewContext.RouteData.Values["controller"],
        ViewContext.RouteData.Values["action"])
  }))
</code>```

Body:
I have a contact form that is near the bottom of the page, and requires scrolling to get to; when the form is submitted, the page is reloaded, and I need for the page to go to an anchor, at the contact form. When I change the action of the BeginForm, the '#' within the anchor is encoded to '%23' - how do I stop this form happening?

I need this to function without the use of any JavaScript.

@{
    using (Html.BeginForm(null, null, new { ReturnURL = "#contact" }, FormMethod.Post, new { novalidate = "novalidate" }))
    {
        //Fields...

        <button type="submit">Submit</button>
    }
}

The above code will return the following HTML, and will not go to the anchor:

<form action="/en/Home/Contact?ReturnURL=%23contact" method="post" novalidate="novalidate">

While the following HTML would (but I don't know how to generate it with Razor):

<form action="/en/Home/Contact?ReturnURL=#contact" method="post" novalidate="novalidate">

I've also tried the following, but the '#' is always encoded:

using (Html.BeginForm(null, null, new { ReturnURL = HttpUtility.HtmlDecode("#contact") }, FormMethod.Post, new { novalidate = "novalidate" }))

using (Html.BeginForm(null, null, new { ReturnURL = HttpUtility.UrlDecode("#contact") }, FormMethod.Post, new { novalidate = "novalidate" }))

using (Html.BeginForm(new { action = Url.Action("Index", "Home") + Html.Raw("Contact/#contact") }))

Body:
It seems that using the keyword 'action' overwrites the form's action - the following code is a solution:

using (Html.BeginForm(null, null, FormMethod.Post, new { action = "#contact" }))

On submission, the user will be sent to site.com/#contact

For sites where the form isn't on the index/home/front page, I've used the following to build a route:

using (Html.BeginForm(null, null, FormMethod.Post,
  new { action = string.Format("{0}/{1}#contact",
        ViewContext.RouteData.Values["controller"],
        ViewContext.RouteData.Values["action"])
  }))


问:
Chart.js: Line displayed thinner than defined
I've created a simple line chart with a straight line, but if the line runs along the top and bottom horizontal grid line it is displayed thinner than defined. Even if the grid lines are hidden.

https://i.stack.imgur.com/rD58f.png

My code:

```<code>window.onload = function() {

    var config =  {
        type: "line",
        data: {
            labels: ["Jan", "Feb", "Mar","Jun","Jul","Aug","Sep", "Oct", "Nov"],
            datasets: [ {
                backgroundColor: "#ff0000",
                borderColor: "#ff0000",
                fill: false,
                borderWidth: 2,
                lineTension: 0,
                data: [0, 0, 0, 1, 6, 8, 8, 8, 8]
            }]
        },
        options: {
            responsive: true,
            scales: {
                xAxes: [{
                    gridLines: { display: false }
                }],
                yAxes: [{
                    gridLines: { display: false }
                }]
            },
            legend: {
                display: false
            }
        }
    };

    var ctx = document.getElementById("canvas").getContext("2d");
    var chart = new Chart(ctx, config);
}
</code>```

How can I solve this?

答:
I tried a litte bit. But the only solution i found which actually worked, was to add the space with the canvas helpers of chartjs. You can achieve this by adding the following code to your application:

```<code>var WIDE_CLIP = {top: 2, bottom: 4};

Chart.canvasHelpers.clipArea = function(ctx, clipArea) {
    ctx.save();
    ctx.beginPath();
    ctx.rect(
      clipArea.left,
      clipArea.top - WIDE_CLIP.top,
      clipArea.right - clipArea.left,
      clipArea.bottom - clipArea.top + WIDE_CLIP.bottom
    );
    ctx.clip();
}
</code>```

Take a look at this: https://stackoverflow.com/a/46303679/4032712

I tried to use the padding and position options but none of the seems to work for your problem. Hope I could help you with this!

Body:
I've created a simple line chart with a straight line, but if the line runs along the top and bottom horizontal grid line it is displayed thinner than defined. Even if the grid lines are hidden.

https://i.stack.imgur.com/rD58f.png

My code:

window.onload = function() {

    var config =  {
        type: "line",
        data: {
            labels: ["Jan", "Feb", "Mar","Jun","Jul","Aug","Sep", "Oct", "Nov"],
            datasets: [ {
                backgroundColor: "#ff0000",
                borderColor: "#ff0000",
                fill: false,
                borderWidth: 2,
                lineTension: 0,
                data: [0, 0, 0, 1, 6, 8, 8, 8, 8]
            }]
        },
        options: {
            responsive: true,
            scales: {
                xAxes: [{
                    gridLines: { display: false }
                }],
                yAxes: [{
                    gridLines: { display: false }
                }]
            },
            legend: {
                display: false
            }
        }
    };

    var ctx = document.getElementById("canvas").getContext("2d");
    var chart = new Chart(ctx, config);
}

How can I solve this?

Body:
I tried a litte bit. But the only solution i found which actually worked, was to add the space with the canvas helpers of chartjs. You can achieve this by adding the following code to your application:

var WIDE_CLIP = {top: 2, bottom: 4};

Chart.canvasHelpers.clipArea = function(ctx, clipArea) {
    ctx.save();
    ctx.beginPath();
    ctx.rect(
      clipArea.left,
      clipArea.top - WIDE_CLIP.top,
      clipArea.right - clipArea.left,
      clipArea.bottom - clipArea.top + WIDE_CLIP.bottom
    );
    ctx.clip();
}

Take a look at this: https://stackoverflow.com/a/46303679/4032712

I tried to use the padding and position options but none of the seems to work for your problem. Hope I could help you with this!


问:
Automapper - Mapper already initialized error
I am using AutoMapper 6.2.0 in my ASP.NET MVC 5 application.

When I call my view through controller it shows all things right. But, when I refresh that view, Visual Studio shows an error:

System.InvalidOperationException: 'Mapper already initialized. You must call Initialize once per application domain/process.'

I am using AutoMapper only in one controller. Not made any configuration in any place yet nor used AutoMapper in any other service or controller.

My controller:

```<code>public class StudentsController : Controller
{
    private DataContext db = new DataContext();

    // GET: Students
    public ActionResult Index([Form] QueryOptions queryOptions)
    {
        var students = db.Students.Include(s => s.Father);

        AutoMapper.Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Student, StudentViewModel>();
        });
            return View(new ResulList<StudentViewModel> {
            QueryOptions = queryOptions,
            Model = AutoMapper.Mapper.Map<List<Student>,List<StudentViewModel>>(students.ToList())
        });
    }

    // Other Methods are deleted for ease...
</code>```

Error within controller:

My Model class:

```<code>public class Student
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string CNIC { get; set; }
    public string FormNo { get; set; }
    public string PreviousEducaton { get; set; }
    public string DOB { get; set; }
    public int AdmissionYear { get; set; }

    public virtual Father Father { get; set; }
    public virtual Sarparast Sarparast { get; set; }
    public virtual Zamin Zamin { get; set; }
    public virtual ICollection<MulaqatiMehram> MulaqatiMehram { get; set; }
    public virtual ICollection<Result> Results { get; set; }
}
</code>```

My ViewModel Class:

```<code>public class StudentViewModel
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string CNIC { get; set; }
    public string FormNo { get; set; }
    public string PreviousEducaton { get; set; }
    public string DOB { get; set; }
    public int AdmissionYear { get; set; }

    public virtual FatherViewModel Father { get; set; }
    public virtual SarparastViewModel Sarparast { get; set; }
    public virtual ZaminViewModel Zamin { get; set; }
}
</code>```

答:
I've used this method before and it worked till version 6.1.1

```<code> Mapper.Initialize(cfg => cfg.CreateMap<ContactModel, ContactModel>()
            .ConstructUsing(x => new ContactModel(LoggingDelegate))
            .ForMember(x => x.EntityReference, opt => opt.Ignore())
        );
</code>```

Since version 6.2, this doesn't work any more. To correctly use Automapper create a new Mapper and us this one like this:

```<code> var mapper = new MapperConfiguration(cfg => cfg.CreateMap<ContactModel, ContactModel>()
            .ConstructUsing(x => new ContactModel(LoggingDelegate))
            .ForMember(x => x.EntityReference, opt => opt.Ignore())).CreateMapper();

        var model = mapper.Map<ContactModel>(this);
</code>```

Body:
I am using AutoMapper 6.2.0 in my ASP.NET MVC 5 application.

When I call my view through controller it shows all things right. But, when I refresh that view, Visual Studio shows an error:

System.InvalidOperationException: 'Mapper already initialized. You must call Initialize once per application domain/process.'

I am using AutoMapper only in one controller. Not made any configuration in any place yet nor used AutoMapper in any other service or controller.

My controller:

public class StudentsController : Controller
{
    private DataContext db = new DataContext();

    // GET: Students
    public ActionResult Index([Form] QueryOptions queryOptions)
    {
        var students = db.Students.Include(s => s.Father);

        AutoMapper.Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Student, StudentViewModel>();
        });
            return View(new ResulList<StudentViewModel> {
            QueryOptions = queryOptions,
            Model = AutoMapper.Mapper.Map<List<Student>,List<StudentViewModel>>(students.ToList())
        });
    }

    // Other Methods are deleted for ease...

Error within controller:

My Model class:

public class Student
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string CNIC { get; set; }
    public string FormNo { get; set; }
    public string PreviousEducaton { get; set; }
    public string DOB { get; set; }
    public int AdmissionYear { get; set; }

    public virtual Father Father { get; set; }
    public virtual Sarparast Sarparast { get; set; }
    public virtual Zamin Zamin { get; set; }
    public virtual ICollection<MulaqatiMehram> MulaqatiMehram { get; set; }
    public virtual ICollection<Result> Results { get; set; }
}

My ViewModel Class:

public class StudentViewModel
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string CNIC { get; set; }
    public string FormNo { get; set; }
    public string PreviousEducaton { get; set; }
    public string DOB { get; set; }
    public int AdmissionYear { get; set; }

    public virtual FatherViewModel Father { get; set; }
    public virtual SarparastViewModel Sarparast { get; set; }
    public virtual ZaminViewModel Zamin { get; set; }
}

Body:
I've used this method before and it worked till version 6.1.1

 Mapper.Initialize(cfg => cfg.CreateMap<ContactModel, ContactModel>()
            .ConstructUsing(x => new ContactModel(LoggingDelegate))
            .ForMember(x => x.EntityReference, opt => opt.Ignore())
        );

Since version 6.2, this doesn't work any more. To correctly use Automapper create a new Mapper and us this one like this:

 var mapper = new MapperConfiguration(cfg => cfg.CreateMap<ContactModel, ContactModel>()
            .ConstructUsing(x => new ContactModel(LoggingDelegate))
            .ForMember(x => x.EntityReference, opt => opt.Ignore())).CreateMapper();

        var model = mapper.Map<ContactModel>(this);


问:
Retrieving Local Resource Values correctly: GetGlobalResourceObject or .NET Control?
While developing I've seen a couple different ways to get local resources values from the resx files. Which one is considered the best practice?

Using the GetGlobalResourceObject method:

```<code><a id="myLink" href="#"><%= GetGlobalResourceObject("Filter","Diary")%></a>
</code>```

Or using a control and setting the value directly in the resx:

Any better ways I should know?
Thanks for your help!

答:
Basically the names tell everything: Global Resources and Local Resources.

If you need the same resource to be used in different places (pages, controls, back-end, etc.) use Global Resources.
Local resources are tight to pages and user controls. You should be creating one local source file for each page (aspx) and user controls (ascx).

Body:
While developing I've seen a couple different ways to get local resources values from the resx files. Which one is considered the best practice?

Using the GetGlobalResourceObject method:

<%= GetGlobalResourceObject("Filter","Diary")%>

Or using a control and setting the value directly in the resx:

Any better ways I should know?
Thanks for your help!


问:
Loadrunner 12.55 (community edition) parallel Controller for testing 2 different URL's at same time
I'm new to LoadRunner. I'm using LoadRunner 12.55 (community edition). My current scenario is, I have two URL's one with new code and one with old code. I need to find the mean value and throughput for the two URL's separately to find if the new code's performance is increased. But the condition is I need to test both the URL's at the same time. And I need the reports separately for both the URL's. Is it possible? Pls help.

Thanks in Advance

答:
Simply produce two test scripts and run them together.   Or, you may run two independent tests and then use the cross scenario analysis to join the two test sets in the analysis to observe differences.

I would recommend that you name your timers (transactions) uniquely in each test script to ease the identification of response from build A vs build A+1

As you are new to LoadRunner, at a minimum your management owes you some time to go through the self paced tutorial before engaging in actual work.  Ideally, you should be paired with a mentor for a period of time as well.  If your management is unwilling to engage in either then you would do well to question whether they are interested more in the quality of the output or the ability to bill for the effort.


问:
How can I receive the missing messages in STOMP?
I have a python script which has to run 24/7 on a linux server and receive ActiveMQ push notification from another server via STOMP. It can happen that the script fails for any reason and will be down for some time, apparently for 30 minutes at most or just a few minutes in average.

I'll need to receive the missing messages-notifications somehow after the script becomes up again if it was down before. As far as I understand, and my understanding is limited, it's possible and the server will send them once my script becomes up. Here's what me believe it to be true

https://activemq.apache.org/apollo/documentation/stomp-manual.html#Topic_Durable_Subscriptions

A durable subscription is a queue which is subscribed to a topic so
  that even if the client which created the durable subscription is not
  online, he can still get a copy of all the messages sent to the topic
  when he comes back online. Multiple clients can subscribe to the same
  durable subscription and since it's backed by a queue, those
  subscribers will have the topic's messages load balanced across them.

And in python:

```<code>import stomp

# ....
conn.subscribe(destination="/topic/some_topic", id=1, ack="auto", headers={"activemq.subscriptionName": "SampleSubscription"})
</code>```

Is that what I think it is?

Will my script receive the missing messages once it becomes up again?

Does "id" have always be equal to 1?

update:

Here are the headers I receive at on_message method in Python:

```<code>{
'priority': '4',
'persistent': 'true',
'message-id': 'fdsfds',
'expires': '432432432',
'destination': '/topic/fdsfds',
'timestamp': '42343243',
'subscription': '0',
'type': 'aaaaa'
}
</code>```

Do "persistent" and, maybe, "subscription", imply that if my client-consumer is offline then once it goes online again it'll be sent all the messages it's missed while it was offline?

答:
No, actually persistent doesn't send the missed messages when server is offline; Persistent messages in activeMQ means that when you restart activeMQ, messages in queue doesn't get lost and they will be kept to be received in future.

And if you want to send a persistent message in activemq using python and stomp, you have to add the following STOMP header to all SEND requests: persistent:true.

And you have to do write it like this:

```<code>conn.send('queue name', 'message', headers={'persistent':'true'})
</code>```

Body:
I have a python script which has to run 24/7 on a linux server and receive ActiveMQ push notification from another server via STOMP. It can happen that the script fails for any reason and will be down for some time, apparently for 30 minutes at most or just a few minutes in average.

I'll need to receive the missing messages-notifications somehow after the script becomes up again if it was down before. As far as I understand, and my understanding is limited, it's possible and the server will send them once my script becomes up. Here's what me believe it to be true

https://activemq.apache.org/apollo/documentation/stomp-manual.html#Topic_Durable_Subscriptions

A durable subscription is a queue which is subscribed to a topic so
  that even if the client which created the durable subscription is not
  online, he can still get a copy of all the messages sent to the topic
  when he comes back online. Multiple clients can subscribe to the same
  durable subscription and since it's backed by a queue, those
  subscribers will have the topic's messages load balanced across them.

And in python:

import stomp

# ....
conn.subscribe(destination="/topic/some_topic", id=1, ack="auto", headers={"activemq.subscriptionName": "SampleSubscription"})

Is that what I think it is?

Will my script receive the missing messages once it becomes up again?

Does "id" have always be equal to 1?

update:

Here are the headers I receive at on_message method in Python:

{
'priority': '4',
'persistent': 'true',
'message-id': 'fdsfds',
'expires': '432432432',
'destination': '/topic/fdsfds',
'timestamp': '42343243',
'subscription': '0',
'type': 'aaaaa'
}

Do "persistent" and, maybe, "subscription", imply that if my client-consumer is offline then once it goes online again it'll be sent all the messages it's missed while it was offline?

Body:
No, actually persistent doesn't send the missed messages when server is offline; Persistent messages in activeMQ means that when you restart activeMQ, messages in queue doesn't get lost and they will be kept to be received in future.

And if you want to send a persistent message in activemq using python and stomp, you have to add the following STOMP header to all SEND requests: persistent:true.

And you have to do write it like this:

conn.send('queue name', 'message', headers={'persistent':'true'})


问:
Calculate cumulative sum (cumsum) by group
With data frame:

```<code>df <- data.frame(id = rep(1:3, each = 5)
                 , hour = rep(1:5, 3)
                 , value = sample(1:15))
</code>```

I want to add a cumulative sum column that matches the id:

```<code>df
   id hour value csum
1   1    1     7    7
2   1    2     9   16
3   1    3    15   31
4   1    4    11   42
5   1    5    14   56
6   2    1    10   10
7   2    2     2   12
8   2    3     5   17
9   2    4     6   23
10  2    5     4   27
11  3    1     1    1
12  3    2    13   14
13  3    3     8   22
14  3    4     3   25
15  3    5    12   37
</code>```

How can I do this efficiently? Thanks!

答:
Using dplyr::</p>

```<code>require(dplyr)
df %>% group_by(id) %>% mutate(csum = cumsum(value))
</code>```

Body:
With data frame:

df <- data.frame(id = rep(1:3, each = 5)
                 , hour = rep(1:5, 3)
                 , value = sample(1:15))

I want to add a cumulative sum column that matches the id:

df
   id hour value csum
1   1    1     7    7
2   1    2     9   16
3   1    3    15   31
4   1    4    11   42
5   1    5    14   56
6   2    1    10   10
7   2    2     2   12
8   2    3     5   17
9   2    4     6   23
10  2    5     4   27
11  3    1     1    1
12  3    2    13   14
13  3    3     8   22
14  3    4     3   25
15  3    5    12   37

How can I do this efficiently? Thanks!

Body:
Using dplyr::

require(dplyr)
df %>% group_by(id) %>% mutate(csum = cumsum(value))


问:
What does '@' at beginning of a variable mean?

Possible Duplicate:

  What does the @ symbol before a variable name mean in C#?

I've seen this a couple of times in code that has been passed onto me:

```<code>try {
   //Do some stuff
}
catch(Exception @exception)
{
   //Do catch stuff
}
</code>```

Can anyone please explain the purpose of the '@' at the beginning of the Exception variable?

答:
It lets you name a variable using a reserved keyword.

For example:

```<code>var @class = "something"; // OK
var class = "something"; // Compilation error
</code>```

Body:
Possible Duplicate:

  What does the @ symbol before a variable name mean in C#?

I've seen this a couple of times in code that has been passed onto me:

try {
   //Do some stuff
}
catch(Exception @exception)
{
   //Do catch stuff
}

Can anyone please explain the purpose of the '@' at the beginning of the Exception variable?

Body:
It lets you name a variable using a reserved keyword.

For example:

var @class = "something"; // OK
var class = "something"; // Compilation error


问:
Display Data From 2 Table in GridView Asp.net
i have Two Table Like This

```<code>Request     Example          UniTerm    Example

St_Code     1                 Id       1        2
St_Name     FirstStudent     Term      96-97    95-94
St_Family   FirstFamily
</code>```

and i have a Grid View contain St_Code,Name,Family and Term
now the problem is i want to display all records of the student with the Just Last Record Term field in Term table
i need gridview data like below

```<code>1 FirstStudent FirstFamily 96-97
</code>```

show last record of the Term table and all of the Student table Records

i tried this SQL Code to select them

```<code>SELECT Request.St_Code, Request.St_Name, Request.St_Family, UniTerm.Term FROM Student CROSS JOIN UniTerm ORDER BY UniTerm.Term DESC
</code>```

its ok but shows all of the records in UniTerm table i need just last one!

thanks in advance

答:
Just update your query

SELECT Request.St_Code, Request.St_Name, Request.St_Family, UniTerm.Term FROM Student CROSS JOIN UniTerm ORDER BY UniTerm.Id  DESC

Body:
i have Two Table Like This

Request     Example          UniTerm    Example

St_Code     1                 Id       1        2
St_Name     FirstStudent     Term      96-97    95-94
St_Family   FirstFamily

and i have a Grid View contain St_Code,Name,Family and Term
now the problem is i want to display all records of the student with the Just Last Record Term field in Term table
i need gridview data like below

1 FirstStudent FirstFamily 96-97

show last record of the Term table and all of the Student table Records

i tried this SQL Code to select them

SELECT Request.St_Code, Request.St_Name, Request.St_Family, UniTerm.Term FROM Student CROSS JOIN UniTerm ORDER BY UniTerm.Term DESC

its ok but shows all of the records in UniTerm table i need just last one!

thanks in advance


问:
How to notify app when phone's location changes(in case app is killed i.e not running is background)
I m creating an app, where I want to notify my app when phone's location changes in case app is not running in background or in killed state, how will broadcast receiver help me.Please help!

Thanks in advance.

答:
*if you use googleApiClient and use onLocationChanged(Location location) override method then it automatically called after get new location, and this methods called every some time of seconds so don't depend if your device is really move from previous location
so in onLocationChanged() you can do whatever you want of work like send notification to nitifi you but it bad because it will send you maybe every 5 sec or more new notification

*if you don't know how to get location even if app is killed you must create class that extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener  , and write it's methods

hope my answer is helpful , and if you wan't something till me


问:
SAS Macro help to loop monthly sas datasets
I have monthly datasets in SAS Library for customers from Jan 2013 onwards with datasets name as CUST_JAN2013,CUST_FEB2013........CUST_OCT2017. These customers datasets have huge records of 2 million members for each month.This monthly datset has two columns (customer number and customer monthly expenses).

I have one input dataset Cust_Expense with customer number and month as columns. This Cust_Expense table has only 250,000 members and want to pull expense data for each member from SPECIFIC monthly SAS dataset by joining customer number.

```<code>Cust_Expense
------------
Customer_Number  Month
111              FEB2014
987              APR2017
784              FEB2014
768              APR2017
.....
145              AUG2017
345              AUG2014
</code>```

I have tried using call execute, but it tries to loop thru each 250,000 records of input dataset (Cust_Expense) and join with corresponding monthly SAS customer tables which takes too much of time.
Is there a way to read input tables (Cust_Expense) by month so that we read all customers for a specific month and then read the same monthly table ONCE to pull all the records from that month, so that it does not loop 250,000 times.

答:
I guess you could output your data in specific dataset like this example :

```<code>data test;
infile datalines dsd;
   input ID : $2. MONTH  $3. ;
   datalines;
1,JAN
2,JAN
3,JAN
4,FEB
5,FEB
6,MAR
7,MAR
8,MAR
9,MAR
;
run;

data  JAN FEB MAR;
set test;
if MONTH = "JAN" then output JAN;
if MONTH = "FEB" then output FEB;
if MONTH = "MAR" then output MAR;
run;
</code>```

You will avoid to loop through all your ID (250000)
and you will use dataset statement from SAS

At the end you will get 12 DATASET containing the ID related.

If you case, FEB2014 , for example, you will use a substring fonction and the condition in your dataset will become :

```<code>...
set test;
...
if SUBSTR(MONTH,1,3)="FEB" then output FEB;
...
</code>```

Regards

Body:
I have monthly datasets in SAS Library for customers from Jan 2013 onwards with datasets name as CUST_JAN2013,CUST_FEB2013........CUST_OCT2017. These customers datasets have huge records of 2 million members for each month.This monthly datset has two columns (customer number and customer monthly expenses).

I have one input dataset Cust_Expense with customer number and month as columns. This Cust_Expense table has only 250,000 members and want to pull expense data for each member from SPECIFIC monthly SAS dataset by joining customer number.

Cust_Expense
------------
Customer_Number  Month
111              FEB2014
987              APR2017
784              FEB2014
768              APR2017
.....
145              AUG2017
345              AUG2014

I have tried using call execute, but it tries to loop thru each 250,000 records of input dataset (Cust_Expense) and join with corresponding monthly SAS customer tables which takes too much of time.
Is there a way to read input tables (Cust_Expense) by month so that we read all customers for a specific month and then read the same monthly table ONCE to pull all the records from that month, so that it does not loop 250,000 times.

Body:
I guess you could output your data in specific dataset like this example :

data test;
infile datalines dsd;
   input ID : $2. MONTH  $3. ;
   datalines;
1,JAN
2,JAN
3,JAN
4,FEB
5,FEB
6,MAR
7,MAR
8,MAR
9,MAR
;
run;

data  JAN FEB MAR;
set test;
if MONTH = "JAN" then output JAN;
if MONTH = "FEB" then output FEB;
if MONTH = "MAR" then output MAR;
run;

You will avoid to loop through all your ID (250000)
and you will use dataset statement from SAS

At the end you will get 12 DATASET containing the ID related.

If you case, FEB2014 , for example, you will use a substring fonction and the condition in your dataset will become :

...
set test;
...
if SUBSTR(MONTH,1,3)="FEB" then output FEB;
...

Regards


问:
How can I make Node.js 'require' absolute? (instead of relative)
I would like to 'require' my files always by the root of my project and not relative to the current module.

For example, if you look at Express.js' app.js line 6, you will see

```<code>express = require('../../')
</code>```

That's really bad, IMO. Imagine I would like to put all my examples closer to the root only by one level. That would be impossible, because I would have to update more than 30 examples and many times within each example. To this:

```<code>express = require('../')
</code>```

My solution would be to have a special case for root based: if a string starts with an $ then it's relative to the root folder of the project.

What can I do?

Update 2

Now I'm using RequireJS which allows you to write in one way and works both on client and on server. RequireJS also allows you to create custom paths.

Update 3

Now I moved to Webpack and Gulp.js and I use enhanced-require to handle modules on the server side. See here for the rationale: http://hackhat.com/p/110/module-loader-webpack-vs-requirejs-vs-browserify/

答:
Another answer:

Imagine this folders structure:

node_modules
- lodash

src
- subdir
- foo.js
- bar.js
- main.js

tests

```<code>- test.js
</code>```

Then in test.js, you need to require files like this:

```<code>const foo = require("../src/subdir/foo");
const bar = require("../src/subdir/bar");
const main = require("../src/main");
const _ = require("lodash");
</code>```

and in main.js:

```<code>const foo = require("./subdir/foo");
const bar = require("./subdir/bar");
const _ = require("lodash");
</code>```

Now you can use babel and the babel-plugin-module-resolver with this .babelrc file to configure two root folders:

```<code>{
    "plugins": [
        ["module-resolver", {
            "root": ["./src", "./src/subdir"]
        }]
    ]
}
</code>```

Now you can require files in the same manner in tests and in src:

```<code>const foo = require("foo");
const bar = require("bar");
const main = require("main");
const _ = require("lodash");
</code>```

And if you want use the ES6 module syntax:

```<code>{
    "plugins": [
        ["module-resolver", {
            "root": ["./src", "./src/subdir"]
        }],
        "transform-es2015-modules-commonjs"
    ]
}
</code>```

then you import files in tests and src like this:

```<code>import foo from "foo"
import bar from "bar"
import _ from "lodash"
</code>```

Body:
I would like to 'require' my files always by the root of my project and not relative to the current module.

For example, if you look at Express.js' app.js line 6, you will see

express = require('../../')

That's really bad, IMO. Imagine I would like to put all my examples closer to the root only by one level. That would be impossible, because I would have to update more than 30 examples and many times within each example. To this:

express = require('../')

My solution would be to have a special case for root based: if a string starts with an $ then it's relative to the root folder of the project.

What can I do?

Update 2

Now I'm using RequireJS which allows you to write in one way and works both on client and on server. RequireJS also allows you to create custom paths.

Update 3

Now I moved to Webpack and Gulp.js and I use enhanced-require to handle modules on the server side. See here for the rationale: http://hackhat.com/p/110/module-loader-webpack-vs-requirejs-vs-browserify/

Body:
Another answer:

Imagine this folders structure:

node_modules
- lodash

src
- subdir
- foo.js
- bar.js
- main.js

tests

- test.js

Then in test.js, you need to require files like this:

const foo = require("../src/subdir/foo");
const bar = require("../src/subdir/bar");
const main = require("../src/main");
const _ = require("lodash");

and in main.js:

const foo = require("./subdir/foo");
const bar = require("./subdir/bar");
const _ = require("lodash");

Now you can use babel and the babel-plugin-module-resolver with this .babelrc file to configure two root folders:

{
    "plugins": [
        ["module-resolver", {
            "root": ["./src", "./src/subdir"]
        }]
    ]
}

Now you can require files in the same manner in tests and in src:

const foo = require("foo");
const bar = require("bar");
const main = require("main");
const _ = require("lodash");

And if you want use the ES6 module syntax:

{
    "plugins": [
        ["module-resolver", {
            "root": ["./src", "./src/subdir"]
        }],
        "transform-es2015-modules-commonjs"
    ]
}

then you import files in tests and src like this:

import foo from "foo"
import bar from "bar"
import _ from "lodash"


问:
pip3 can't install anything due to some reason about ssl
After upgrading my ubuntu server 16.04, I can't install modules with pip3 for my python3.6. This is what I get when I try to install tensorflow-gpu for python3:

```<code>root@amax:~# pip3 install tensorflow-gpu
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting tensorflow-gpu
  Could not fetch URL https://pypi.python.org/simple/tensorflow-gpu/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping
  Could not find a version that satisfies the requirement tensorflow-gpu (from versions: )
No matching distribution found for tensorflow-gpu
</code>```

This is my python3 and pip3 version:

```<code>root@amax:~# python3 -V
Python 3.6.1
root@amax:~# which python3
/usr/local/bin/python3
root@amax:~# pip3 -V
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)
</code>```

I am sure that the openssl is installed on my server:

```<code>root@amax:~# apt -y install openssl libssl-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
libssl-dev is already the newest version (1.0.2g-1ubuntu13).
openssl is already the newest version (1.0.2g-1ubuntu13).
</code>```

I think the cause of the problem might be the version of my pip3 doesn't match the openssl version. What should I do? Any suggestions will be appreciated! Thank you!

答:
may be you can download a .whl file and install it with pip3

The wheel file can be found here

and then just use this to install

```<code>pip3 install /home/Downloads/tensorflow-1.4.0-cp36-cp36m-manylinux1_x86_64.whl
</code>```

Hopes this solves your problem

Cheers!

Body:
After upgrading my ubuntu server 16.04, I can't install modules with pip3 for my python3.6. This is what I get when I try to install tensorflow-gpu for python3:

root@amax:~# pip3 install tensorflow-gpu
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting tensorflow-gpu
  Could not fetch URL https://pypi.python.org/simple/tensorflow-gpu/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping
  Could not find a version that satisfies the requirement tensorflow-gpu (from versions: )
No matching distribution found for tensorflow-gpu

This is my python3 and pip3 version:

root@amax:~# python3 -V
Python 3.6.1
root@amax:~# which python3
/usr/local/bin/python3
root@amax:~# pip3 -V
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

I am sure that the openssl is installed on my server:

root@amax:~# apt -y install openssl libssl-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
libssl-dev is already the newest version (1.0.2g-1ubuntu13).
openssl is already the newest version (1.0.2g-1ubuntu13).

I think the cause of the problem might be the version of my pip3 doesn't match the openssl version. What should I do? Any suggestions will be appreciated! Thank you!

Body:
may be you can download a .whl file and install it with pip3

The wheel file can be found here

and then just use this to install

pip3 install /home/Downloads/tensorflow-1.4.0-cp36-cp36m-manylinux1_x86_64.whl

Hopes this solves your problem

Cheers!


问:
Is there a tool to analyse if a C# and WPF project can be ported to Silverlight?
I have a WPF and C# application, and I want to know if it can be ported to silverlight. Is there a tool to analyse the dependencies and tell me what I can't use, and what I can ?

Thanks.

答:
I've just remembered that when I tried to port a C# app to Linux/Mono I used Moma analyser, it helps to identify issues you may have when porting a .Net application to Mono, and I know that Mono only implement Silverlight not WPF, so I will give it a try.

And you can see and change the data for what Moma consider to be implemented or not. In the Definition directory there is a 2.8-4.0-defs.zip file, inside there are 4 text files exception.txt, missing.txt, monotodo.txt, and version.txt, it is 3 lists of functions that will produce errors. So maybe someone can scrape the info about what Silverlight implements, and change the files accordingly.