问:
src/main/resources not added in war class path
I have developed a web + maven project. All development is completed. Now I am trying to deploy on production. I am encountering a problem that no content from src/main/resources is added in my ProjectName.war/WEB-INF/classes/ folder. Check the screenshot

Like hibernate.cfg.xml is not there and also other files/folders are not in class path (ProjectName.war/WEB-INF/classes/). Am I missing any plugin ? I thought that src/main/resources's content should be added automatically according to this link.

pom.xml

```<code><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>
    <groupId>IncidentManagement</groupId>
    <artifactId>IncidentManagement</artifactId>
    <version>1</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src.main.java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <java.version>1.8</java.version>
        <junit.version>4.12</junit.version>
        <servlet.version>3.1.0</servlet.version>
        <mojarra.version>2.2.12</mojarra.version>
        <primefaces.version>5.3</primefaces.version>
        <maven.compiler.plugin.version>3.3</maven.compiler.plugin.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <!-- ORACLE database driver -->

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <!-- <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>  -->

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.6.3.Final</version>
        </dependency>

        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- Mojarra JSF -->
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>${mojarra.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>${mojarra.version}</version>
        </dependency>
        <!-- PrimeFaces -->
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>${primefaces.version}</version>
        </dependency>

        <!-- Excel and CSV -->

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10-FINAL</version>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.10-FINAL</version>
            <type>jar</type>
        </dependency>

        <!-- PDF -->

        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>

        <!-- JSON -->
        <dependency>
           <groupId>com.googlecode.json-simple</groupId>
           <artifactId>json-simple</artifactId>
           <version>1.1.1</version>
        </dependency>

        <!-- Primefaces Theme -->
        <!-- https://mvnrepository.com/artifact/org.primefaces.extensions/all-themes -->
        <dependency>
            <groupId>org.primefaces.extensions</groupId>
            <artifactId>all-themes</artifactId>
            <version>1.0.8</version>
        </dependency>

    </dependencies>

</project>
</code>```

答:
Your folder structure is wrong, it should be src/main/java or src/test/java.. and what you have is with src.main.java. Please re-create the maven project from start use the command below

```<code>mvn archetype:generate -DgroupId=IncidentManagement
   -DartifactId=IncidentManagement
   -DarchetypeArtifactId=maven-archetype-quickstart
   -DinteractiveMode=false
</code>```

Body:
I have developed a web + maven project. All development is completed. Now I am trying to deploy on production. I am encountering a problem that no content from src/main/resources is added in my ProjectName.war/WEB-INF/classes/ folder. Check the screenshot

Like hibernate.cfg.xml is not there and also other files/folders are not in class path (ProjectName.war/WEB-INF/classes/). Am I missing any plugin ? I thought that src/main/resources's content should be added automatically according to this link.

pom.xml

<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>
    <groupId>IncidentManagement</groupId>
    <artifactId>IncidentManagement</artifactId>
    <version>1</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src.main.java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <java.version>1.8</java.version>
        <junit.version>4.12</junit.version>
        <servlet.version>3.1.0</servlet.version>
        <mojarra.version>2.2.12</mojarra.version>
        <primefaces.version>5.3</primefaces.version>
        <maven.compiler.plugin.version>3.3</maven.compiler.plugin.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.6.3.Final</version>
        </dependency>

        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>${mojarra.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>${mojarra.version}</version>
        </dependency>

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>${primefaces.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10-FINAL</version>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.10-FINAL</version>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>

        <dependency>
           <groupId>com.googlecode.json-simple</groupId>
           <artifactId>json-simple</artifactId>
           <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.primefaces.extensions</groupId>
            <artifactId>all-themes</artifactId>
            <version>1.0.8</version>
        </dependency>

    </dependencies>

</project>

Body:
Your folder structure is wrong, it should be src/main/java or src/test/java.. and what you have is with src.main.java. Please re-create the maven project from start use the command below

mvn archetype:generate -DgroupId=IncidentManagement
   -DartifactId=IncidentManagement
   -DarchetypeArtifactId=maven-archetype-quickstart
   -DinteractiveMode=false


来源: stackexchange

问:
How do you prevent two persons from editing the same file?
In TFS 2010, How do you prevent two persons from editing the same file?</p>

答:
In Visual Studio 2015 and 2017 follow the steps:

1. Open Team Explorer if VS and go to Settings

Open Team Project Source Control Settings and uncheck Enable multiple check-out

ContentLicense: CC BY-SA 3.0


问:
SVN checking out new files from repo that others have added
If I have checked out a SVN repo and work on it locally all is fine.  If my colleague also checks out the repo and they can also work on it fine.

When my colleague creates a new file, adds it to the repo and commits it.  Running update does not automatically download the additional file.

Deleting the local repo and checking it out a second gets the additional file.

What command do I need to execute to ensure that when running update it does get any additional files?

I am using the Tortoise shell and subversion SVN.   The end application is an electronics cad package, Altium, so we normally only use checkout, commit and update commands.

答:
To update all the files (from the current directory downwards):</p>

```<code>svn up
</code>```

ContentLicense: CC BY-SA 2.5

Body:
To update all the files (from the current directory downwards):

svn up


问:
XPath to select all elements between two headings?
```<code><h2>Headline 1</h2>
<p>some text</p>
<p>some more text</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
<p>more text</p>
<h2>Headline 2</h2>
</code>```

I have the above in a webpage and I want to be able to target all elements following the first h2 that contains the text 'Headline 1' up to but NOT including the element h2 that contains the text 'Headline 2'.

I can target the elements like this:

```<code>//*[count(preceding-sibling::hr)=1]
</code>```

but this is not specific to the text contained and so if the page ever changed then the xpath could be pointing to something totally different.

What I would like in sudo code terms is this:

give me all the elements between the header 'Headline 1' and the
  header 'Headline 2' including 'Headline 1'

Is this at all possible?

答:
```<code>//h2[contains(.,'Headline 1')]//*
</code>```

Will return every element below the header.  You could further narrow it down with

```<code>//h2[contains(.,'Headline 1')]//p
</code>```

for paragraph text, but that would not include the li elements.

Body:
Headline 1

some text

some more text

list item 1

list item 2

more text

Headline 2

I have the above in a webpage and I want to be able to target all elements following the first h2 that contains the text 'Headline 1' up to but NOT including the element h2 that contains the text 'Headline 2'.

I can target the elements like this:

//*[count(preceding-sibling::hr)=1]

but this is not specific to the text contained and so if the page ever changed then the xpath could be pointing to something totally different.

What I would like in sudo code terms is this:

give me all the elements between the header 'Headline 1' and the
  header 'Headline 2' including 'Headline 1'

Is this at all possible?

Body:
//h2[contains(.,'Headline 1')]//*

Will return every element below the header.  You could further narrow it down with

//h2[contains(.,'Headline 1')]//p

for paragraph text, but that would not include the li elements.


问:
LDAPS for an Azure AD
I am trying to setup custom AD on azure for access over the internet (ldap)
I followed the steps in this document
Azure AD Setup

I am stuck at step 5 - Configure DNS to access the managed domain from the internet
I was able to generate EXTERNAL IP ADDRESS FOR LDAPS ACCESS but cant ping it. I've setup domain services and virtual network in azure but cant figure out what needs to be done for the dns setting to make the AD access over public internet

答: I just finished setting this up. You won't be able to ping it. The LDAPS server doesn't respond to ping requests. You need to set an A record for the server that matches the certificate you configured when setting up the server. Ex. ldaps.example.com. Then you can try and connect to it using LDP over SSL to test the configuration.</p>

Title: LDAPS for an Azure AD


问:
In express how do I redirect a user to an external url?
I have a payment system using node.js and braintree, when the payment is successful I want to send the user to the back end. My back end is setup elsewhere.

I have tried

```<code>res.writeHead(301,
  {Location: 'http://app.example.io'}
);
res.end();
</code>```

So window.location is obviously not available. I cant think of any ways to redirect a user?

答:
I just have the same issue and got it work by adding "next". I use routers so maybe you have same issue as mine? Without next, i got error about no render engine...weird</p>

```<code>var express = require('express');
var router = express.Router();
var debug = require('debug')('node_blog:server');

/* GET home page. */
router.get('/', function(req, res, next) {
  debug("index debug");
  res.render('index.html', { title: 'Express' });
});

router.post("/", function (req, res, next) {
    //var pass = req.body("password");
    //var loginx = req.body("login");
    //res.render('index.html', { title: 'Express' });
    res.redirect("/users")
    next
});

module.exports = router;
</code>```

Body:
I have a payment system using node.js and braintree, when the payment is successful I want to send the user to the back end. My back end is setup elsewhere.

I have tried

res.writeHead(301,
  {Location: 'http://app.example.io'}
);
res.end();

So window.location is obviously not available. I cant think of any ways to redirect a user?

Body:
I just have the same issue and got it work by adding "next". I use routers so maybe you have same issue as mine? Without next, i got error about no render engine...weird

var express = require('express');
var router = express.Router();
var debug = require('debug')('node_blog:server');

/* GET home page. */
router.get('/', function(req, res, next) {
  debug("index debug");
  res.render('index.html', { title: 'Express' });
});

router.post("/", function (req, res, next) {
    //var pass = req.body("password");
    //var loginx = req.body("login");
    //res.render('index.html', { title: 'Express' });
    res.redirect("/users")
    next
});

module.exports = router;


问:
Codenameone android build error manifest merger
I have been using the default codescanner cn1-lib but I got sick of the app having to download and external app to scan qr codes on android. So I downloaded the littlemonkey zbar cn1-lib and I added both .cn1lib files to my lib directory and then I started getting build errors. The first were about the minSdkVersion couldn't be lower than a library's sdk version so I changed the build hint android.min_sdkversion=15 then I started getting the error that the java version of the main project can't be lower than a library so I changed build.xml all 'target' and 'source' to 1.8 and I added the build hint java.version=8 however I am still getting a build error.
The log is giving me a Manifest merger failed with multiple errors, see logs

```<code>    Merging result:ERROR
/tmp/build5026335701129669511xxx/MyApplication/src/main/AndroidManifest.xml:43:149-325 Warning:
    Element activity#com.dm.zbar.android.scanner.ZBarScannerActivity at AndroidManifest.xml:43:149-325 duplicated with element declared at AndroidManifest.xml:43:3-149
/tmp/build5026335701129669511xxx/MyApplication/src/main/AndroidManifest.xml:43:114-146 Error:
    Attribute activity#com.dm.zbar.android.scanner.ZBarScannerActivity@label value=(@string/app_name) from AndroidManifest.xml:43:114-146
    is also present at [:ZBarScannerLibrary:] AndroidManifest.xml:18:13-36 value=(Scanner).
    Suggestion: add 'tools:replace="android:label"' to <activity> element at AndroidManifest.xml:43:3-149 to override.
</code>```

I paste binned the whole log: https://pastebin.com/tBJJvGkR

答: You should update to the latest QR scanner library using the Extensions section of Codename One Settings.  It should resolve that issue.</p>

Body:
I have been using the default codescanner cn1-lib but I got sick of the app having to download and external app to scan qr codes on android. So I downloaded the littlemonkey zbar cn1-lib and I added both .cn1lib files to my lib directory and then I started getting build errors. The first were about the minSdkVersion couldn't be lower than a library's sdk version so I changed the build hint android.min_sdkversion=15 then I started getting the error that the java version of the main project can't be lower than a library so I changed build.xml all 'target' and 'source' to 1.8 and I added the build hint java.version=8 however I am still getting a build error.
The log is giving me a Manifest merger failed with multiple errors, see logs

    Merging result:ERROR
/tmp/build5026335701129669511xxx/MyApplication/src/main/AndroidManifest.xml:43:149-325 Warning:
    Element activity#com.dm.zbar.android.scanner.ZBarScannerActivity at AndroidManifest.xml:43:149-325 duplicated with element declared at AndroidManifest.xml:43:3-149
/tmp/build5026335701129669511xxx/MyApplication/src/main/AndroidManifest.xml:43:114-146 Error:
    Attribute activity#com.dm.zbar.android.scanner.ZBarScannerActivity@label value=(@string/app_name) from AndroidManifest.xml:43:114-146
    is also present at [:ZBarScannerLibrary:] AndroidManifest.xml:18:13-36 value=(Scanner).
    Suggestion: add 'tools:replace="android:label"' to <activity> element at AndroidManifest.xml:43:3-149 to override.

I paste binned the whole log: https://pastebin.com/tBJJvGkR


问:
regexp for renaming multiple files using 'rename.pl'
I'm using rename.pl to rename a multiple files. I am having trouble coming up with the right regexp. My file names are of the form:

nn.some.title.string.ext

I want to change just the first '.' to ' - '. I thought this would work but it does not.

```<code>s/\.?/ - /
</code>```

Can someone help me out with this? TIA.

答:
\.? can match a sequence of zero characters, so s/\.?/ - / replaces the dot or the empty string at the start of the input.

```<code>"abc.def.ghi" ⇒  " - abc.def.ghi"
".abc"        ⇒  " - abc"
</code>```

To replace the first ., you can use the following:

```<code>s/\./ - /
</code>```

```<code>"abc.def.ghi" ⇒ "abc - def.ghi"
</code>```

To substitute all . but a leading one or the one in the extension, you can use the following:

```<code>s/(?!^)\.(?!\w+\z)/ - /g
</code>```

Body:
I'm using rename.pl to rename a multiple files. I am having trouble coming up with the right regexp. My file names are of the form:

nn.some.title.string.ext

I want to change just the first '.' to ' - '. I thought this would work but it does not.

s/\.?/ - /

Can someone help me out with this? TIA.

Body:
\.? can match a sequence of zero characters, so s/\.?/ - / replaces the dot or the empty string at the start of the input.

"abc.def.ghi" ⇒  " - abc.def.ghi"
".abc"        ⇒  " - abc"

To replace the first ., you can use the following:

s/\./ - /

"abc.def.ghi" ⇒ "abc - def.ghi"

To substitute all . but a leading one or the one in the extension, you can use the following:

s/(?!^)\.(?!\w+\z)/ - /g


问:
Unable to set the mode of the realtime clock to UTC
On my Debian (Jessie) Linux machine I would like to set the mode of the realtime clock to UTC as recommended by the timedatectl command (see below). But this doesn't seem to work properly.

Execution of the timedatectl command which is part of the systemd-timesyncd daemon concept, results in the following warning:

Warning: The system is configured to read the RTC time in the local time zone. This mode can not be fully supported. It will create various problems with time
zone changes and daylight saving time adjustments. The RTC time is never updated, it relies on external facilities to maintain it. If at all possible, use RTC in UTC by calling 'timedatectl set-local-rtc 0'.

Submitting the suggested command:

```<code>timedatectl set-local-rtc 0
</code>```

results in the following error:

Failed to set local RTC: Failed to set RTC to local/UTC: Input/output error

When immediately submitting the same command a second time, there is no error and the UTC warning from above is gone. But unfortunately this is reverting back after 1-2 min.! That means that when waiting some minutes and then executing timedatectl again, the warning is back!!

REMARK: I'm working on a regular Linux machine which has an RTC clock (not an embedded system)!

答:
Very tricky!

As stated in the documentation, setting the RTC mode with:

timedatectl set-local-rtc 0

modifies the third line in /etc/adjtime. It turned out that this file on my machine only had two lines! In this case the command is NOT capable of writing the change!!! This is really a joke! The third line MUST exist! So since I've added "UTC" in the third line, I'm now able to switch the content of this line with the command above ... 0 or ... 1. Accordingly the warning is gone and does not return!

Body:
On my Debian (Jessie) Linux machine I would like to set the mode of the realtime clock to UTC as recommended by the timedatectl command (see below). But this doesn't seem to work properly.

Execution of the timedatectl command which is part of the systemd-timesyncd daemon concept, results in the following warning:

Warning: The system is configured to read the RTC time in the local time zone. This mode can not be fully supported. It will create various problems with time
zone changes and daylight saving time adjustments. The RTC time is never updated, it relies on external facilities to maintain it. If at all possible, use RTC in UTC by calling 'timedatectl set-local-rtc 0'.

Submitting the suggested command:

timedatectl set-local-rtc 0

results in the following error:

Failed to set local RTC: Failed to set RTC to local/UTC: Input/output error

When immediately submitting the same command a second time, there is no error and the UTC warning from above is gone. But unfortunately this is reverting back after 1-2 min.! That means that when waiting some minutes and then executing timedatectl again, the warning is back!!

REMARK: I'm working on a regular Linux machine which has an RTC clock (not an embedded system)!


问:
XMLHttpRequest Object wants to .open file one folder up?
I have an XMLHttpRequest Object that is trying to access a file outside of it's folder.

W3Schools says that: For security reasons, modern browsers do not allow access across domains.

This means that both the web page and the XML file it tries to load, must be located on the same server.

So, my file is on the same server. just in a different directory (folder.) It’s not reading the file. Is there a workaround for this?

The javascript file works perfectly when the .xml file is located in the same folder. However, I want to access it from outside the folder - one directory up. i used the syntax ../ to indicate that it is located one file up. it doesn't seem to get access to it...

1 works perfectly with myFile.xml located in the same folder.

2 does not seem to be able to locate myFile.xml in the directory that the folder is located in.

Using the direct path does not work.

1.)    xmlhttp.open("GET", "myFile.xml", true);

2.)    xmlhttp.open("GET", "../myFile.xml", true);

[EDIT - Update] solved. It works. Exactly as is. I moved the files over to the host server from my desktop folder. I still don't know why there's a different outcome from the desktop environment... but, I'm glad to know I was coding it correctly.

答:
I'm working on my desktop, in a folder on my desktop.

Most browsers forbid XMLHttpRequest access to file: URIs entirely.

Firefox allows access with certain restrictions:

a file can read another file only if the parent directory of the originating file is an ancestor directory of the target file.

Since the file you are trying to read is in a directory above the one containing the HTML document you are trying to access it from, permission is denied.

To avoid this limitation, don't try to use XMLHttpRequest without HTTP.


问:
Main class instance for all subclasses
I got three classes: Bank, account and Coin. I want the class Bank to have a default coin variable , which I pass on to its constructor. So I extended account to Bank, this would mean that I can access the default coin variable through the method getmainCoin() via the account class. For some reason I'm getting this error when trying that:

Error:(12, 32) java: constructor bank in class com.company.bank cannot be applied to given types;
    required: com.company.Coin
    found: no arguments
    reason: actual and formal argument lists differ in length

```<code>// Instantiations
Coin dollars = new Coin("Dollar", "$");;
bank SomeBank = new bank(dollars);
Person john = new Person("John Doe", 20, dollars, new account(9058));
System.out.println(john.checkbalance());

public class bank {
  public String name;
  private int coinsheld;
  private Coin maincoin;

  public bank(Coin maincoin){
      this.maincoin = maincoin;
  }

  public Coin getmainCoin(){
      return this.maincoin;
  }

}

public class account extends bank {
  private int balance;
  private static int accounts;
  private int accnumber;
  private Coin coin;

  public account(int balance){
      this.balance = balance;
      this.accounts += 1;
      this.accnumber = accounts;
      this.coin = getmainCoin();
  }
}

public class Coin {
  public static int total;
  private String name;
  private String sign;
  private int id;

  public Coin(String name, String sign){
      this.name = name;
      this.sign = sign;
      this.id = total + 1;
  }

  public int getID(){
      return this.id;
  }
}
</code>```

答:
The problem is when you getCoin() in your "Account" object there is no coin set in that given object, lets review it step by step:

There is an Bank class

Account class extends bank (BUT DOESNT set the coin attribute/variable because you dont set it in constructor neither with a setCoint() method)

You use getMainCoin()->coin value was never set->Error:"com.company.Coin found".

So you can take this approaches:

If you want to set the default coin to ALL the Bank objects you can do a class variable (also called static variable) changing "private Coin maincoin;" to "private static Coin maincoin". If you take this approach you should create a static method "setCoin()" or make your constructor static.

That way if you extend that class, and once a Coin object has been set to the Bank class, every object of that class (or that extends it, for instance) will have the same Coin Object.

But if you want each Bank object to have a different default Coin (even the new Account objects you create) then you sould add to your Account constructor a parameter to set the coin or a setCoint() method and not calling getCoin() before you even set if, of course.

EDITED: because of typos and visual appeal.

Title: Main class instance for all subclasses

Body:
I got three classes: Bank, account and Coin. I want the class Bank to have a default coin variable , which I pass on to its constructor. So I extended account to Bank, this would mean that I can access the default coin variable through the method getmainCoin() via the account class. For some reason I'm getting this error when trying that:

Error:(12, 32) java: constructor bank in class com.company.bank cannot be applied to given types;
    required: com.company.Coin
    found: no arguments
    reason: actual and formal argument lists differ in length

// Instantiations
Coin dollars = new Coin("Dollar", "$");;
bank SomeBank = new bank(dollars);
Person john = new Person("John Doe", 20, dollars, new account(9058));
System.out.println(john.checkbalance());

public class bank {
  public String name;
  private int coinsheld;
  private Coin maincoin;

  public bank(Coin maincoin){
      this.maincoin = maincoin;
  }

  public Coin getmainCoin(){
      return this.maincoin;
  }

}

public class account extends bank {
  private int balance;
  private static int accounts;
  private int accnumber;
  private Coin coin;

  public account(int balance){
      this.balance = balance;
      this.accounts += 1;
      this.accnumber = accounts;
      this.coin = getmainCoin();
  }
}

public class Coin {
  public static int total;
  private String name;
  private String sign;
  private int id;

  public Coin(String name, String sign){
      this.name = name;
      this.sign = sign;
      this.id = total + 1;
  }

  public int getID(){
      return this.id;
  }
}


问:
bash's strange behavior on a function named "@"
Today I found a strange behavior in bash.

When you define function named "@" in an interactive shell using this syntax:

```<code>$ function @() { echo foo; }
</code>```

it (of course) defines a function named "@".

However, in specific situations, e.g. in tmux session or in virtual console (Ctrl+Alt+F1), this defines a function named "@()".
I couldn't find any difference in these environments (output of echo $- was himBH). Besides, function @ { echo bar; } doesn't have this trap and defines "@" in both situations. I couldn't find any document that says @ is a special symbol in bash.

Does anyone know anything about this?
I confirmed these on vanilla Ubuntu 16.04.2.

答:
The "problem" is caused by the shell option extglob.

extglob: on

[STEP 100] # echo $BASH_VERSION
4.4.12(1)-release
[STEP 101] # shopt -s extglob
[STEP 102] # echo @()
@()
[STEP 103] # function @() { shopt extglob; }
[STEP 104] # @()
extglob         on
[STEP 105] # unset -f @()
[STEP 106] #
```

<p>When <code>extglob on</code>, I guess Bash's syntax parser would treat <code>@()</code> as a whole (because it looks like a valid <em>extended glob pattern</em>) and pass it to the <code>function</code> command as <strong>one single</strong> paramter so <code>function @() {}</code> is in the <code>function NAME {}</code> syntax and so <code>@()</code> is the function name.</p>

<h3>extglob: off</h3>

<pre class="lang-none prettyprint-override"><code>[STEP 107] # shopt -u extglob
[STEP 108] # echo @()
bash: syntax error near unexpected token `('
[STEP 109] # function @() { shopt extglob; }
[STEP 110] # @
extglob         off
[STEP 111] #
</code>```

When extglob off, function @() {} is in the function NAME() {} syntax and so @ is the function name.

Chet's explanation in the bug-bash mailing list:

A shell function name is a WORD, though POSIX mode restricts it to a NAME.
  It does not undergo any expansions.

When extglob is enabled, @() is part of a WORD, since it's a valid extended
  glob pattern, and glob patterns can be contained in a WORD.  This is one
  example of the differing parser behavior when extglob is enabled. So
  there's no problem with defining a function named @().  When extglob is
  not enabled, @() is not a valid pattern, and the parens are parsed as
  separate operators. In this case they happen to make sense, and define a
  function named @.

When you try to execute it, since it's not quoted, it undergoes the normal
  word expansions, one of which is filename generation.  It doesn't match
  anything, so it's left intact, and the function named @() executes.  When
  nullglob is enabled, the pattern still doesn't match anything, and is
  removed. This leaves you with the null command, which also executes, and
  returns a status of 0.

Body:
Today I found a strange behavior in bash.

When you define function named "@" in an interactive shell using this syntax:

$ function @() { echo foo; }

it (of course) defines a function named "@".

However, in specific situations, e.g. in tmux session or in virtual console (Ctrl+Alt+F1), this defines a function named "@()".
I couldn't find any difference in these environments (output of echo $- was himBH). Besides, function @ { echo bar; } doesn't have this trap and defines "@" in both situations. I couldn't find any document that says @ is a special symbol in bash.

Does anyone know anything about this?
I confirmed these on vanilla Ubuntu 16.04.2.

Body:
The "problem" is caused by the shell option extglob.

extglob: on

[STEP 100] # echo $BASH_VERSION
4.4.12(1)-release
[STEP 101] # shopt -s extglob
[STEP 102] # echo @()
@()
[STEP 103] # function @() { shopt extglob; }
[STEP 104] # @()
extglob         on
[STEP 105] # unset -f @()
[STEP 106] #

When extglob on, I guess Bash's syntax parser would treat @() as a whole (because it looks like a valid extended glob pattern) and pass it to the function command as one single paramter so function @() {} is in the function NAME {} syntax and so @() is the function name.

extglob: off

[STEP 107] # shopt -u extglob
[STEP 108] # echo @()
bash: syntax error near unexpected token `('
[STEP 109] # function @() { shopt extglob; }
[STEP 110] # @
extglob         off
[STEP 111] #

When extglob off, function @() {} is in the function NAME() {} syntax and so @ is the function name.

Chet's explanation in the bug-bash mailing list:

A shell function name is a WORD, though POSIX mode restricts it to a NAME.
  It does not undergo any expansions.

When extglob is enabled, @() is part of a WORD, since it's a valid extended
  glob pattern, and glob patterns can be contained in a WORD.  This is one
  example of the differing parser behavior when extglob is enabled. So
  there's no problem with defining a function named @().  When extglob is
  not enabled, @() is not a valid pattern, and the parens are parsed as
  separate operators. In this case they happen to make sense, and define a
  function named @.

When you try to execute it, since it's not quoted, it undergoes the normal
  word expansions, one of which is filename generation.  It doesn't match
  anything, so it's left intact, and the function named @() executes.  When
  nullglob is enabled, the pattern still doesn't match anything, and is
  removed. This leaves you with the null command, which also executes, and
  returns a status of 0.


问:
Python find first occurrence of character after index
I am trying to get the index of the first occurrence of a character that occurs in a string after a specified index. For example:

```<code>string = 'This + is + a + string'

# The 'i' in 'is' is at the 7th index, find the next occurrence of '+'
string.find_after_index(7, '+')

# Return 10, the index of the next '+' character
>>> 10
</code>```

答:
```<code>for i in range(index, len(string)):
    if string[i] == char:
         print(i)
</code>```

The above code will loop through from the index you provide index to the length of the string len(string). Then if the index of the string is equal to the character, char, that you are looking for then it will print the index.

You could put this in a function and pass in the, string, index and character and then return i.

Body:
I am trying to get the index of the first occurrence of a character that occurs in a string after a specified index. For example:

string = 'This + is + a + string'

# The 'i' in 'is' is at the 7th index, find the next occurrence of '+'
string.find_after_index(7, '+')

# Return 10, the index of the next '+' character
>>> 10

Body:
for i in range(index, len(string)):
    if string[i] == char:
         print(i)

The above code will loop through from the index you provide index to the length of the string len(string). Then if the index of the string is equal to the character, char, that you are looking for then it will print the index.

You could put this in a function and pass in the, string, index and character and then return i.


问:
Jquery Ajax is neither passing data to PHP nor returning anything on success()
I am trying to pass the jquery variable to PHP with Ajax but the receiving php file is returning error " Undefined index" Code is:

```<code>  <div class="img">
    <a href="ss.php">
       <img id="theme_bg" src="images/themes/theme1.jpg">
    </a></div>

$(document).ready(function($){
    $('.img').on('click','img',function(){
        var imgsrc = $(this).attr('src');
        alert(imgsrc);       //this is returning the img src correctly
$.ajax({
    type: "POST",
    url: 'ss.php',
    dataType: 'json',
    data: {imgpath:imgsrc },
    success: function(response) {
    content.html(response);    // i tried alert here but it shows nothing
    }
});
});});
</code>```

receiving PHP file code is:

```<code> <?php
    $imagepath = $_POST['imgpath'];
    echo $imagepath;
 ?>
</code>```

I tried it with GET also but same error.. I haven't used Ajax before this. I checked other responses here on similar questions but none of them was has anything majorly different from mine code. so dont know what's the error..

updated Screen shots of code both files

updated screen shots of output

答:
You have dataType set to json

so PHP should php <?php echo json_encode([$imagepath])

The better solution would be dataType: text instead of JSON

Note that in $.ajax  the dataType is for response not request

Check $.ajax manual http://api.jquery.com/jquery.ajax/

Body:
I am trying to pass the jquery variable to PHP with Ajax but the receiving php file is returning error " Undefined index" Code is:

$(document).ready(function($){
    $('.img').on('click','img',function(){
        var imgsrc = $(this).attr('src');
        alert(imgsrc);       //this is returning the img src correctly
$.ajax({
    type: "POST",
    url: 'ss.php',
    dataType: 'json',
    data: {imgpath:imgsrc },
    success: function(response) {
    content.html(response);    // i tried alert here but it shows nothing
    }
});
});});

receiving PHP file code is:

 <?php
    $imagepath = $_POST['imgpath'];
    echo $imagepath;
 ?>

I tried it with GET also but same error.. I haven't used Ajax before this. I checked other responses here on similar questions but none of them was has anything majorly different from mine code. so dont know what's the error..

updated Screen shots of code both files

updated screen shots of output


问:
From a container running on Docker for Windows, how can I access a port on the host?
I'm running a CentOS-based container on Docker for Windows and trying to connect to an http service running on port 8545 of my host environment.

I've tried this, attempting a variety of suspected host names and IP addresses:

curl http://localhost:8545

But the error message I get is "curl: (7) Failed connect to localhost:8545; Connection refused"

How should I figure out what IP Address to use? Is there anything I need to configure as far as allowing the port number to be accessed from inside the container?

答:
Localhost is not working yet I think with Docker for Windows.
There is few things you can try. First you can add EXPOSE 'portnumber' in the dockerfile so the container will listen on this port. You can also use docker run with -p 8545:8545, it will map the port of the container and the host.

To get the Ip address of the container you can use:

```<code>docker inspect -f "{{ .NetworkSettings.Networks.nat.IPAddress }}" containername
</code>```

Body:
Localhost is not working yet I think with Docker for Windows.
There is few things you can try. First you can add EXPOSE 'portnumber' in the dockerfile so the container will listen on this port. You can also use docker run with -p 8545:8545, it will map the port of the container and the host.

To get the Ip address of the container you can use:

docker inspect -f "{{ .NetworkSettings.Networks.nat.IPAddress }}" containername


问:
Reading specific columns in Excel Sheet
I have an Excel spreadsheet, but now my problem is that I want to be able to read only specific columns, the columns in the spreadsheet are more than 20, I need to read only 3 columns.</p>

```<code>procedure TForm1.sh1(SheetIndex: integer);
Var
  Xlapp1,Xlrange, Sheet:Variant ;
  MaxRow, MaxCol,X, Y:integer ;
  str:string;
  arrData:Variant;
begin
 try
  Str:=trim(form1.OpenDialog1.FileName);

  XLApp1 := createoleobject('excel.application');
  XLApp1.Workbooks.open(Str) ;

  Sheet := XLApp1.WorkSheets[SheetIndex] ;

  MaxRow := Sheet.Usedrange.EntireRow.count ;
  MaxCol := sheet.Usedrange.EntireColumn.count;

  arrData:= Sheet.UsedRange.Value;

  stringgrid1.RowCount:=maxRow+1;
  StringGrid1.ColCount:=maxCol+1;

  for x := 1 to maxCol do
    for y := 1 to maxRow do
     stringgrid1.Cells[x,y]:=arrData[y, x];

  XLApp1.Workbooks.close;
 Except
  on E : Exception do begin
  XLApp1.Workbooks.close;
   ShowMessage(E.Message);
  end;
 end;
end;
</code>```

答:
Here's an example of dynamically retrieving the content of three entire columns (H, I and J) from an Excel spreadsheet. While it's not tailored to your specific example, it should give you the basic concepts of doing so (and cleaning up properly afterward) that you can adapt to your specific needs. I've commented the code to make clear what it's doing.

procedure TForm1.Button1Click(Sender: TObject);
var
  Excel, Book, Sheet, Range1: OleVariant;
  i, j: Integer;
  Data: Variant;
const
  // Obtained at https://msdn.microsoft.com/en-us/library/office/ff820880.aspx
  xlDown = -4121;
begin
  Excel := CreateOleObject('Excel.Application');
  try
    Book := Excel.WorkBooks.Open('E:\TempFiles\Test.xlsx');
    Sheet := Book.Worksheets.Item['Sheet1'];

    // Get tne range we want to extract, in this case all rows of columns H-J.
    // .End(xlDown) finds the last used cell in the indicated column
    Range1 := Sheet.Range['H1', Sheet.Range['J1'].End[xlDown]];
    Data := Range1.Value;

    // Get the number of columns and rows from the array itself. The addition
    // of 1 is for the fixed row and column, and to synch up with the Data
    // array being 1 based instead of 0
    StringGrid1.ColCount := VarArrayHighBound(Data, 2) + 1;
    StringGrid1.RowCount := VarArrayHighBound(Data, 1) + 1;

    // Get the number of columns and rows from the array itself.
    // We know that what is being returned is a two dimensional array
    // (rows and columns).
    //
    // Add 1 to allow for the fixed row and column, and to synch up with the Data,
    // where the arrays are 1 based instead of 0
    //
    for i := 1 to StringGrid1.ColCount - 1 do
      for j := 1 to StringGrid1.RowCount - 1 do
        StringGrid1.Cells[i, j] := Data[j, i];

  finally
    // Clean up all references so Excel will close cleanly
    Range1 := Unassigned;
    Sheet := Unassigned;
    Book := Unassigned;
    Excel.Quit;
    Excel := Unassigned;
  end;
end;
```

ContentLicense: CC BY-SA 4.0

Title: Reading specific columns in Excel Sheet

Body:
I have an Excel spreadsheet, but now my problem is that I want to be able to read only specific columns, the columns in the spreadsheet are more than 20, I need to read only 3 columns.

procedure TForm1.sh1(SheetIndex: integer);
Var
  Xlapp1,Xlrange, Sheet:Variant ;
  MaxRow, MaxCol,X, Y:integer ;
  str:string;
  arrData:Variant;
begin
 try
  Str:=trim(form1.OpenDialog1.FileName);

  XLApp1 := createoleobject('excel.application');
  XLApp1.Workbooks.open(Str) ;

  Sheet := XLApp1.WorkSheets[SheetIndex] ;

  MaxRow := Sheet.Usedrange.EntireRow.count ;
  MaxCol := sheet.Usedrange.EntireColumn.count;

  arrData:= Sheet.UsedRange.Value;

  stringgrid1.RowCount:=maxRow+1;
  StringGrid1.ColCount:=maxCol+1;

  for x := 1 to maxCol do
    for y := 1 to maxRow do
     stringgrid1.Cells[x,y]:=arrData[y, x];

  XLApp1.Workbooks.close;
 Except
  on E : Exception do begin
  XLApp1.Workbooks.close;
   ShowMessage(E.Message);
  end;
 end;
end;


问:
scikit-learn, linearsvc - how to get support vectors from the trained SVM?
I am using LinearSVC from scikit-learn library and I wonder if it is possible to somehow pull out the vectors which my model uses after training to make predictions. Tried to google it for some time but without any luck. Anyone knows?</p>

答:
I am not sure if it helps, but I was searching for something similar and the conclusion was that when:

```<code>clf = svm.LinearSVC()
</code>```

Then this:

```<code>clf.decision_function(x)
</code>```

Is equal to this:

```<code>clf.coef_.dot(x) + clf.intercept_
</code>```

Body:
I am not sure if it helps, but I was searching for something similar and the conclusion was that when:

clf = svm.LinearSVC()

Then this:

clf.decision_function(x)

Is equal to this:

clf.coef_.dot(x) + clf.intercept_


问:
Aspose.Word - Adding rows to an existing table in VB.Net
In a Word template document, I have a table header defined and would like to add data (Multiple rows) to the same table programmatically using aspose and having hard time in doing this.

I found few posts on online for doing this but all of them are written JAVA and functions that are used in these posts are not available in VB.Net.

https://www.aspose.com/community/forums/thread/648997/reg-adding-rows-dynamically-to-the-existing-table-in-the-document.aspx

getLastRow() function doesn't exists in Table Class.(from above post).

Can some one point me to right documentation or provide a solution for my problem.

Thanks in Advance!

答:
Please use LastRow method to get last row of table in VB using Aspose.Words for .NET 17.3. Please check complete code as following.

I am Tilal Ahmad, developer evangelist at Aspose.

```<code>Dim doc As New Document("input.docx")
' Retrieve the first table in the document.
Dim table As Table = DirectCast(doc.GetChild(NodeType.Table, 0, True), Table)
table.FirstRow.RowFormat.HeadingFormat = True
For i As Integer = 1 To 15
' Clone the last row in the table.
Dim clonedRow As Row = DirectCast(table.LastRow.Clone(True), Row)
clonedRow.RowFormat.HeadingFormat = False
' Remove all content from the cloned row's cells. This makes the row ready for
' new content to be inserted into.
For Each cell As Cell In clonedRow.Cells
    cell.FirstParagraph.Runs.Clear()
    cell.CellFormat.ClearFormatting()
    cell.FirstParagraph.AppendChild(New Run(doc, "hello text"))
Next

' Add the row to the end of the table.

table.AppendChild(clonedRow)
Next

doc.Save("Table.AddCloneRowToTable Out.doc")
</code>```

Body:
Please use LastRow method to get last row of table in VB using Aspose.Words for .NET 17.3. Please check complete code as following.

I am Tilal Ahmad, developer evangelist at Aspose.

Dim doc As New Document("input.docx")
' Retrieve the first table in the document.
Dim table As Table = DirectCast(doc.GetChild(NodeType.Table, 0, True), Table)
table.FirstRow.RowFormat.HeadingFormat = True
For i As Integer = 1 To 15
' Clone the last row in the table.
Dim clonedRow As Row = DirectCast(table.LastRow.Clone(True), Row)
clonedRow.RowFormat.HeadingFormat = False
' Remove all content from the cloned row's cells. This makes the row ready for
' new content to be inserted into.
For Each cell As Cell In clonedRow.Cells
    cell.FirstParagraph.Runs.Clear()
    cell.CellFormat.ClearFormatting()
    cell.FirstParagraph.AppendChild(New Run(doc, "hello text"))
Next

' Add the row to the end of the table.

table.AppendChild(clonedRow)
Next

doc.Save("Table.AddCloneRowToTable Out.doc")


问:
C# Use an array to blacklist what someone has input
```<code>        string name;
        string[] Blacklist;
        Blacklist = new string[10];

        Blacklist[1] = "Example1";
        Blacklist[2] = "Example2";
        Blacklist[3] = "Example3";
        Blacklist[4] = "Example4";
        Blacklist[5] = "Example5";
        Blacklist[6] = "Example6";
        Blacklist[7] = "Example7";
        Blacklist[8] = "Example8";
        Blacklist[9] = "Example9";
        Blacklist[10] = "Example10";

        Console.WriteLine("Enter your name:");
        name = Console.ReadLine();
        if (name = Blacklist[])
                            ^^
</code>```

<p>This is where I'm stuck
I want to make the name blacklisted to all the values in the array
So I can use this to filter all the names that are inappropriate </p>

答:
Hi maybe you want to use contains.

```<code>for (int i = 0; i < Blacklist.lenght(); i++)
 if(Blacklist[i].Contains(name) )
</code>```

you can also convert all for lower and then compare

Body:
        string name;
        string[] Blacklist;
        Blacklist = new string[10];

        Blacklist[1] = "Example1";
        Blacklist[2] = "Example2";
        Blacklist[3] = "Example3";
        Blacklist[4] = "Example4";
        Blacklist[5] = "Example5";
        Blacklist[6] = "Example6";
        Blacklist[7] = "Example7";
        Blacklist[8] = "Example8";
        Blacklist[9] = "Example9";
        Blacklist[10] = "Example10";

        Console.WriteLine("Enter your name:");
        name = Console.ReadLine();
        if (name = Blacklist[])
                            ^^

This is where I'm stuck
I want to make the name blacklisted to all the values in the array
So I can use this to filter all the names that are inappropriate

Body:
Hi maybe you want to use contains.

for (int i = 0; i < Blacklist.lenght(); i++)
 if(Blacklist[i].Contains(name) )

you can also convert all for lower and then compare


问:
Angular js - Error: [$injector:unpr] Unknown provider: $uibmodalProvider <- $uibmodal
I am new to Angular and trying to use $uibmodal but getting the below error while running:
Error: [$injector:unpr] Unknown provider: $uibmodalProvider <- $uibmodal

I am using the below versions:
Angular version: 1.5.11
Angular Bootstrap version: 2.5.0.

I think there is some compatibility issue between the versions.

Any help is highly appreciated.

答: By looking at error it seems like you made typo in dependency name, it should be $uibModal instead of $uibmodal


问:
Wrong RVM location in PATH with new user on macOS
I had a working RVM installation on my macOS machine. After the latest upgrade to Sierra I started to see this error whenever I try to run RVM:

```<code>cat: /Users/flast/.rvm/VERSION: No such file or directory
Warning! PATH is not properly set up, '/Users/flast/.rvm/gems/ruby-2.0.0-p195/bin' is not at first place.
         Usually this is caused by shell initialization files. Search for 'PATH=...' entries.
         You can also re-add RVM to your profile by running: 'rvm get stable --auto-dotfiles'.
         To fix it temporarily in this shell session run: 'rvm use ruby-2.0.0-p195'.
         To ignore this error add rvm_silence_path_mismatch_check_flag=1 to your ~/.rvmrc file.
-bash: /Users/flast/.rvm/scripts/base: No such file or directory
-bash: /Users/flast/.rvm/scripts/help: No such file or directory
</code>```

There is no such file or directory as user "flast" hasn't existed for a while and it is now "first.last". But in my $PATH it is still calling for "flast"

Here is what is in my PATH:

```<code>/usr/local/sbin
/Library/Frameworks/Python.framework/Versions/3.5/bin
/Users/flast/.rvm/gems/ruby-2.0.0-p195/bin
/Users/flast/.rvm/gems/ruby-2.0.0-p195@global/bin
/Users/flast/.rvm/rubies/ruby-2.0.0-p195/bin
/Users/flast/.rvm/bin
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
/opt/X11/bin
/usr/local/share/dotnet
/usr/local/git/bin
/Applications/Postgres.app/Contents/Versions/9.4/bin
/Users/first.last/.rvm/bin
</code>```

I don't know how to remove the old entries from my PATH permanently, and even when I manually reset my PATH for the current session I still get the above error when I run RVM even when the old user path is not present in the PATH file.

Here is ~/.bashrc

```<code>PATH=$PATH:$HOME/.rvm/bin # Add RVM to PATH for scripting
</code>```

here is ~/.bash_profile

```<code>export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.4/bin
[[ -s "/Users/first.last/.rvm/scripts/rvm" ]] && source "/Users/first.last/.rvm/scripts/rvm"

# Setting PATH for Python 3.5
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.5/bin:${PATH}"
export PATH
export PATH="/usr/local/sbin:$PATH"
</code>```

What am I doing wrong here? What needs to be done so that RVM knows where to look?

答:
Turns out the path was being set by RVM in /Users/first.last/.rvm/environments

The first line in each of the environment files is

```<code>export PATH; PATH="/Users/flast/.rvm" ...yada yada
</code>```

Changed that and I still get the PATH warning, but RVM and all the gems contained within work as expected.

Body:
I had a working RVM installation on my macOS machine. After the latest upgrade to Sierra I started to see this error whenever I try to run RVM:

cat: /Users/flast/.rvm/VERSION: No such file or directory
Warning! PATH is not properly set up, '/Users/flast/.rvm/gems/ruby-2.0.0-p195/bin' is not at first place.
         Usually this is caused by shell initialization files. Search for 'PATH=...' entries.
         You can also re-add RVM to your profile by running: 'rvm get stable --auto-dotfiles'.
         To fix it temporarily in this shell session run: 'rvm use ruby-2.0.0-p195'.
         To ignore this error add rvm_silence_path_mismatch_check_flag=1 to your ~/.rvmrc file.
-bash: /Users/flast/.rvm/scripts/base: No such file or directory
-bash: /Users/flast/.rvm/scripts/help: No such file or directory

There is no such file or directory as user "flast" hasn't existed for a while and it is now "first.last". But in my $PATH it is still calling for "flast"

Here is what is in my PATH:

/usr/local/sbin
/Library/Frameworks/Python.framework/Versions/3.5/bin
/Users/flast/.rvm/gems/ruby-2.0.0-p195/bin
/Users/flast/.rvm/gems/ruby-2.0.0-p195@global/bin
/Users/flast/.rvm/rubies/ruby-2.0.0-p195/bin
/Users/flast/.rvm/bin
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
/opt/X11/bin
/usr/local/share/dotnet
/usr/local/git/bin
/Applications/Postgres.app/Contents/Versions/9.4/bin
/Users/first.last/.rvm/bin

I don't know how to remove the old entries from my PATH permanently, and even when I manually reset my PATH for the current session I still get the above error when I run RVM even when the old user path is not present in the PATH file.

Here is ~/.bashrc

PATH=$PATH:$HOME/.rvm/bin # Add RVM to PATH for scripting

here is ~/.bash_profile

export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.4/bin
[[ -s "/Users/first.last/.rvm/scripts/rvm" ]] && source "/Users/first.last/.rvm/scripts/rvm"

# Setting PATH for Python 3.5
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.5/bin:${PATH}"
export PATH
export PATH="/usr/local/sbin:$PATH"

What am I doing wrong here? What needs to be done so that RVM knows where to look?

Body:
Turns out the path was being set by RVM in /Users/first.last/.rvm/environments

The first line in each of the environment files is

export PATH; PATH="/Users/flast/.rvm" ...yada yada

Changed that and I still get the PATH warning, but RVM and all the gems contained within work as expected.


问:
Set number of products in a row according to screen width
I want to set my number of products in a row according to the screen width.i.e on normal screen it would be 3 in a row .then on large screen it would be 4 on extra large screen it would be 5 and so on.I have checked a couple of solution but they did't work some are Stackoverflow1 stackoverflow2
outer container width is fixed i.e 1328 px.I am using bootstrap.

```<code><div class="container">
    <div class="col-md-12">
       <div class="col-md-2">
          //categories sidebar
       </div>
       <div class="col-md-8">
          //categories sidebar
       </div>
       <div class="col-md-2">
           //categories sidebar
       </div>
     </div>
</div>
</code>```

Thanks in advance.

答:
If you don't mind using multiples of 12, that's easy with bootstrap:

http://www.bootply.com/F5yisSxsQm

```<code><div class="container">
<div class="row">
  <div class="col-sm-6 col-md-4 col-lg-3">Text</div>
  <div class="col-sm-6 col-md-4 col-lg-3">Text</div>
  <div class="col-sm-6 col-md-4 col-lg-3">Text</div>
  <div class="col-sm-6 col-md-4 col-lg-3">Text</div>
  </div>
</div>
</code>```

Make sure to use a .row class between the .container and .col-md-* so you don't have margin issues.

Body:
I want to set my number of products in a row according to the screen width.i.e on normal screen it would be 3 in a row .then on large screen it would be 4 on extra large screen it would be 5 and so on.I have checked a couple of solution but they did't work some are Stackoverflow1 stackoverflow2
outer container width is fixed i.e 1328 px.I am using bootstrap.

          //categories sidebar

          //categories sidebar

           //categories sidebar

Thanks in advance.

Body:
If you don't mind using multiples of 12, that's easy with bootstrap:

http://www.bootply.com/F5yisSxsQm

<div class="container">
<div class="row">
  <div class="col-sm-6 col-md-4 col-lg-3">Text</div>
  <div class="col-sm-6 col-md-4 col-lg-3">Text</div>
  <div class="col-sm-6 col-md-4 col-lg-3">Text</div>
  <div class="col-sm-6 col-md-4 col-lg-3">Text</div>
  </div>
</div>

Make sure to use a .row class between the .container and .col-md-* so you don't have margin issues.


问:
Passing keys of object to directive
I have created a directive as a wrapper for md-autocomplete so that it's easier to re-use. In the parent controller, I have an object. I want to pass the keys of the object to my custom directive, but I'm having trouble. Simplified code, without md-autocomplete:

Here's the script

```<code>var app = angular.module('myApp',[])
.controller('parentController', function(){
  var parent = this;
  parent.things = {item1: {color: "blue"}, item2: {color: "red"}};
})
.directive('childDirective',function(){
  return {
    scope: {},
    bindToController: {
       items:'&'
    },
    controller: childController,
    controllerAs: 'child',
    template: '```{{child.items | JSON}}```' //should be [item1,item1]
  }

  function childController(){
    //Just a dummy controller for now
  }
})
</code>```

HTML

```<code><div ng-app="myApp" ng-controller="parentController as parent">
    <my-directive items="Object.keys(parent.things)">
    </my-directive>
</div>
</code>```

TL;DR: How do I pass the keys of an object defined in the parent controller to a child directive? I need to pass just the keys, not the object itself, because my directive is designed to deal with an array of strings.

答:
I'm marking @Igor's answer as correct, because ultimately it led me to the right place. However, I wanted to provide my final solution, which is too big for a comment.

The search for the answer to this question led me to create a directive that is more flexible, and can take several different types of input.

The real key (and my actual answer to the original question) was to bind the items parameter to a proxy getter/setter object in the directive. The basic setup is:

```<code>app.directive('myDirective',function(){
  return {
    ...
      controller: localControl,
      bindToController: {
        items: '<' //note one-way binding
      }
    ...
  }
  function localControl(){
    var child = this;
    child._items = [],

    Object.defineProperties(child,{
       items: {
         get: function(){return child._items},
         set: function(x){child._items = Object.keys(x)}
       }
    });
  }
});
</code>```

HTML

```<code><my-directive items="parent.items">
  <!-- where parent.items is {item1:{}, item2:{}...} -->
</my-directive>
</code>```

Ultimately, I decided I wanted my directive to be able to accept a variety of formats, and came up with this plunk as a demonstration.

Please feel free to offer comments/suggestions on improving my code. Thanks!

Title: Passing keys of object to directive

Body:
I have created a directive as a wrapper for md-autocomplete so that it's easier to re-use. In the parent controller, I have an object. I want to pass the keys of the object to my custom directive, but I'm having trouble. Simplified code, without md-autocomplete:

Here's the script

var app = angular.module('myApp',[])
.controller('parentController', function(){
  var parent = this;
  parent.things = {item1: {color: "blue"}, item2: {color: "red"}};
})
.directive('childDirective',function(){
  return {
    scope: {},
    bindToController: {
       items:'&'
    },
    controller: childController,
    controllerAs: 'child',
    template: '
{{child.items | JSON}}
' //should be [item1,item1]
  }

  function childController(){
    //Just a dummy controller for now
  }
})

HTML

    <my-directive items="Object.keys(parent.things)">
    </my-directive>

TL;DR: How do I pass the keys of an object defined in the parent controller to a child directive? I need to pass just the keys, not the object itself, because my directive is designed to deal with an array of strings.

Body:
I'm marking @Igor's answer as correct, because ultimately it led me to the right place. However, I wanted to provide my final solution, which is too big for a comment.

The search for the answer to this question led me to create a directive that is more flexible, and can take several different types of input.

The real key (and my actual answer to the original question) was to bind the items parameter to a proxy getter/setter object in the directive. The basic setup is:

app.directive('myDirective',function(){
  return {
    ...
      controller: localControl,
      bindToController: {
        items: '<' //note one-way binding
      }
    ...
  }
  function localControl(){
    var child = this;
    child._items = [],

    Object.defineProperties(child,{
       items: {
         get: function(){return child._items},
         set: function(x){child._items = Object.keys(x)}
       }
    });
  }
});

HTML

<my-directive items="parent.items">
  <!-- where parent.items is {item1:{}, item2:{}...} -->
</my-directive>

Ultimately, I decided I wanted my directive to be able to accept a variety of formats, and came up with this plunk as a demonstration.

Please feel free to offer comments/suggestions on improving my code. Thanks!


问:
How to print the first n lines of file?
I'm sure I'm missing something obvious and probably asked before but I can't seem to get the right combination of keywords together to give me an answer.

How can I write out the first n lines of a file (in effect, the opposite of file.readlines()[0:10])?

e.g. I have a function that takes in an input file, and needs to process information from the latter part, throwing out a header. However I want to keep the multi-line header, to be put back in to an output file.

```<code>def readInfile(infile):

    with open(infile, 'r') as ifh:
        # Skip exta info at top of file
        header = ifh.readline()[0:10] # Keep the header for later?

        noheader = ifh.readlines()[11:]
        for line in noheader:
        # Do the useful stuff
            usefulstuff = foo()

return usefulstuff, header
</code>```

Then later I want to write out in the format of the input file, using their header:

```<code>print(header)
for thing in usefulstuff:
   print(thing)
</code>```

Is there a method I'm missing, or is readlines no good for this as it returns a list?

I assumed

```<code>for line in header:
     print(line)
</code>```

would work, but it doesn't seem to in this case - so I must be doing something wrong?

EDIT

Why does trying to use readlines()[] twice fail for the second range?

I fixed the code as @pbuck pointed out, that the header line should have been readlines() not readline but now the noheader variable is empty? Do I really have to open the file twice?!

答:
Careful there, readline() returns a string, so ifh.readline()[0:10] is giving you the first few characters of the first line, and noheader = ifh.readline()[11:] gives you part of the next line.

What you could do is use loops like so:

```<code>header = ""
for i in range(10):
  header += ifh.readline()
</code>```

Or as @pbuck suggests in their comment, use readlines() (note the s), which returns a list containing each line in your file, which looks more like what you were trying to do.

Title: How to print the first n lines of file?

Body:
I'm sure I'm missing something obvious and probably asked before but I can't seem to get the right combination of keywords together to give me an answer.

How can I write out the first n lines of a file (in effect, the opposite of file.readlines()[0:10])?

e.g. I have a function that takes in an input file, and needs to process information from the latter part, throwing out a header. However I want to keep the multi-line header, to be put back in to an output file.

def readInfile(infile):

    with open(infile, 'r') as ifh:
        # Skip exta info at top of file
        header = ifh.readline()[0:10] # Keep the header for later?

        noheader = ifh.readlines()[11:]
        for line in noheader:
        # Do the useful stuff
            usefulstuff = foo()

return usefulstuff, header

Then later I want to write out in the format of the input file, using their header:

print(header)
for thing in usefulstuff:
   print(thing)

Is there a method I'm missing, or is readlines no good for this as it returns a list?

I assumed

for line in header:
     print(line)

would work, but it doesn't seem to in this case - so I must be doing something wrong?

EDIT

Why does trying to use readlines()[] twice fail for the second range?

I fixed the code as @pbuck pointed out, that the header line should have been readlines() not readline but now the noheader variable is empty? Do I really have to open the file twice?!

Body:
Careful there, readline() returns a string, so ifh.readline()[0:10] is giving you the first few characters of the first line, and noheader = ifh.readline()[11:] gives you part of the next line.

What you could do is use loops like so:

header = ""
for i in range(10):
  header += ifh.readline()

Or as @pbuck suggests in their comment, use readlines() (note the s), which returns a list containing each line in your file, which looks more like what you were trying to do.


问:
How to select latest 4 dates
I'm trying to write a query to select last 4 dates from the table for each person. I know that i can use max(date) to select the most recent date but how to select last 4 dates starting from starting from the most recent one for each person.

What I tried was (as below) but this only gives me most recent date of event.

```<code>select user, max(date)
from users
group by user
</code>```

The result i would like to see is:

user | date

John | 30/03/2017

John | 27/03/2017

John | 21/02/2017

John | 04/01/2017

Andy | 29/03/2017

Andy | 27/02/2017

Andy | 21/02/2017

Andy | 01/01/2017

答:
Shot in the dark:</p>

```<code>select t.person, o.date
from table t
outer apply (
select top 4 t2.date
from table2 t2
where t.personID = t2.personID
Order by t2.date desc
) o
</code>```

Title: How to select latest 4 dates

Body:
I'm trying to write a query to select last 4 dates from the table for each person. I know that i can use max(date) to select the most recent date but how to select last 4 dates starting from starting from the most recent one for each person.

What I tried was (as below) but this only gives me most recent date of event.

select user, max(date)
from users
group by user

The result i would like to see is:

user | date

John | 30/03/2017

John | 27/03/2017

John | 21/02/2017

John | 04/01/2017

Andy | 29/03/2017

Andy | 27/02/2017

Andy | 21/02/2017

Andy | 01/01/2017

Body:
Shot in the dark:

select t.person, o.date
from table t
outer apply (
select top 4 t2.date
from table2 t2
where t.personID = t2.personID
Order by t2.date desc
) o


问:
Is there a hex editor component for recent Delphi versions?
I've been able to find a few hex controls by searching online, but none that will compile under Unicode.  Does anyone know if there is one available?</p>

答: Alexey Torgashin's ATBinHex and ATViewer . Did not tried it with unicode delphi versions, but it supports Delphi 2009.</p>


问:
Reorder form controls using Mozilla React form
I am trying to play around with react-jsonschema form of Mozilla.

I have my jsonschema as

```<code>{
  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "state": {
          "type": "string"
        }
      },
      "required": [
        "street_address",
        "city",
        "state"
      ]
    },
    "node": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "children": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/node"
          }
        }
      }
    }
  },
  "type": "object",
  "properties": {
    "billing_address": {
      "title": "Billing address",
      "$ref": "#/definitions/address"
    },
    "shipping_address": {
      "title": "Shipping address",
      "$ref": "#/definitions/address"
    },
    "tree": {
      "title": "Recursive references",
      "$ref": "#/definitions/node"
    }
  }
}
</code>```

UiSchema as

```<code>{
  "ui:order": [
    "shipping_address",
    "billing_address",
    "tree"
  ]
}
</code>```

Using reorder I can control the order of controls on the ui, but as shipping address has street address,city and state. How can I control the ui:order of these controls, consider I want city to appear first within shipping address, how can I do that using Mozilla React jsonschema form.

答:
You can add order at the shipping address level.</p>

```<code>{
  "shipping_address": {
    "ui:order": [
      "city",
      "*"
    ]
  },
  "ui:order": [
    "shipping_address",
    "billing_address",
    "tree"
  ]
}
</code>```

Body:
I am trying to play around with react-jsonschema form of Mozilla.

I have my jsonschema as

{
  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "state": {
          "type": "string"
        }
      },
      "required": [
        "street_address",
        "city",
        "state"
      ]
    },
    "node": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "children": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/node"
          }
        }
      }
    }
  },
  "type": "object",
  "properties": {
    "billing_address": {
      "title": "Billing address",
      "$ref": "#/definitions/address"
    },
    "shipping_address": {
      "title": "Shipping address",
      "$ref": "#/definitions/address"
    },
    "tree": {
      "title": "Recursive references",
      "$ref": "#/definitions/node"
    }
  }
}

UiSchema as

{
  "ui:order": [
    "shipping_address",
    "billing_address",
    "tree"
  ]
}

Using reorder I can control the order of controls on the ui, but as shipping address has street address,city and state. How can I control the ui:order of these controls, consider I want city to appear first within shipping address, how can I do that using Mozilla React jsonschema form.

Body:
You can add order at the shipping address level.

{
  "shipping_address": {
    "ui:order": [
      "city",
      "*"
    ]
  },
  "ui:order": [
    "shipping_address",
    "billing_address",
    "tree"
  ]
}


问:
ZKEmkeeper: Events not triggering, DLL look like not working
I'm stucked for a while trying to use zkemkeeper sdk to use on a application that uses a InBios(Controller) for fingerprint. While i trying to trigger some event nothing happen, i just created a Console Application for test the SDK before start implementing on ASP.NET MVC here is my code, i first connect to the device and then i add the event OnAttTransactionEx someone can point me what i'm doing wrong.

Here is my code:

```<code>private static void Main(string[] args)
    {
        CZKEMClass zkem = new CZKEMClass();
        int idwErrorCode = 0;
        const string ipAddr = "10.0.1.240";
        bool isConnected;
        try
        {
            isConnected = zkem.Connect_Net(ipAddr, Convert.ToInt32(4370));
        }
        catch (Exception ext)
        {
            Console.WriteLine("Erro: " + ext);
            zkem.GetLastError(ref idwErrorCode);
            if (idwErrorCode != 0)
            {
                zkem.GetLastError(idwErrorCode);
            }
            else
            {
                Console.WriteLine("No data from terminal returns!");
            }
            throw new Exception();
        }

        if (isConnected)
        {
            //Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
            zkem.EnableDevice(1, true);
            zkem.RegEvent(1, 65535);
            zkem.OnAttTransactionEx += axCZKEM1_OnAttTransactionEx;

            string sdwEnrollNumber = "";
            int idwVerifyMode = 0;
            int idwInOutMode = 0;
            int idwYear = 0;
            int idwMonth = 0;
            int idwDay = 0;
            int idwHour = 0;
            int idwMinute = 0;
            int idwSecond = 0;
            int idwWorkcode = 0;

            zkem.EnableDevice(1, false); //disable the device
            if (zkem.ReadGeneralLogData(1))
            {
                //read all the attendance records to the memory
                while (zkem.SSR_GetGeneralLogData(1, out sdwEnrollNumber, out idwVerifyMode,
                    out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour,
                    out idwMinute, out idwSecond, ref idwWorkcode))
                {
                    //get records from the memory

                    DateTime datetime = new DateTime(idwYear, idwMonth, idwDay, idwHour, idwMinute, idwSecond);
                    int unixDate = (int) datetime.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                    try
                    {
                        Console.WriteLine(idwInOutMode);
                        Console.WriteLine(sdwEnrollNumber);
                        Console.WriteLine(unixDate);
                    }
                    catch (Exception ex)
                    {
                        //ignored
                    }
                    try
                    {
                        Console.WriteLine("inserted: " +
                                          $"{idwYear}/{idwMonth}/{idwDay} {idwHour}:{idwMinute}:{idwSecond}.000");
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            Console.WriteLine("Fim");
        }
        else
        {
            zkem.GetLastError(ref idwErrorCode);
            if (idwErrorCode != 0)
            {
                zkem.GetLastError(idwErrorCode);
            }
            else
            {
                Console.WriteLine("No data from terminal returns!");
            }
        }
        zkem.EnableDevice(1, true);

        Console.WriteLine("Teste");
        do
        {
            while (!Console.KeyAvailable)
            {
            }
        } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
    }

    public static void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState,
        int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
    {
        Console.WriteLine("Finger Recognized");
    }
</code>```

答:
You must use STA thread .

```<code>Thread TT = new Thread(() =>
{
    CZKEMClass zkem = new CZKEMClass();
    Application.Run();
});
TT.IsBackground = true;
TT.SetApartmentState(ApartmentState.STA);
TT.Start();
</code>```

Then create event. ZKEM events fire on STA threads.

Body:
I'm stucked for a while trying to use zkemkeeper sdk to use on a application that uses a InBios(Controller) for fingerprint. While i trying to trigger some event nothing happen, i just created a Console Application for test the SDK before start implementing on ASP.NET MVC here is my code, i first connect to the device and then i add the event OnAttTransactionEx someone can point me what i'm doing wrong.

Here is my code:

private static void Main(string[] args)
    {
        CZKEMClass zkem = new CZKEMClass();
        int idwErrorCode = 0;
        const string ipAddr = "10.0.1.240";
        bool isConnected;
        try
        {
            isConnected = zkem.Connect_Net(ipAddr, Convert.ToInt32(4370));
        }
        catch (Exception ext)
        {
            Console.WriteLine("Erro: " + ext);
            zkem.GetLastError(ref idwErrorCode);
            if (idwErrorCode != 0)
            {
                zkem.GetLastError(idwErrorCode);
            }
            else
            {
                Console.WriteLine("No data from terminal returns!");
            }
            throw new Exception();
        }

        if (isConnected)
        {
            //Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
            zkem.EnableDevice(1, true);
            zkem.RegEvent(1, 65535);
            zkem.OnAttTransactionEx += axCZKEM1_OnAttTransactionEx;

            string sdwEnrollNumber = "";
            int idwVerifyMode = 0;
            int idwInOutMode = 0;
            int idwYear = 0;
            int idwMonth = 0;
            int idwDay = 0;
            int idwHour = 0;
            int idwMinute = 0;
            int idwSecond = 0;
            int idwWorkcode = 0;

            zkem.EnableDevice(1, false); //disable the device
            if (zkem.ReadGeneralLogData(1))
            {
                //read all the attendance records to the memory
                while (zkem.SSR_GetGeneralLogData(1, out sdwEnrollNumber, out idwVerifyMode,
                    out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour,
                    out idwMinute, out idwSecond, ref idwWorkcode))
                {
                    //get records from the memory

                    DateTime datetime = new DateTime(idwYear, idwMonth, idwDay, idwHour, idwMinute, idwSecond);
                    int unixDate = (int) datetime.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                    try
                    {
                        Console.WriteLine(idwInOutMode);
                        Console.WriteLine(sdwEnrollNumber);
                        Console.WriteLine(unixDate);
                    }
                    catch (Exception ex)
                    {
                        //ignored
                    }
                    try
                    {
                        Console.WriteLine("inserted: " +
                                          $"{idwYear}/{idwMonth}/{idwDay} {idwHour}:{idwMinute}:{idwSecond}.000");
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            Console.WriteLine("Fim");
        }
        else
        {
            zkem.GetLastError(ref idwErrorCode);
            if (idwErrorCode != 0)
            {
                zkem.GetLastError(idwErrorCode);
            }
            else
            {
                Console.WriteLine("No data from terminal returns!");
            }
        }
        zkem.EnableDevice(1, true);

        Console.WriteLine("Teste");
        do
        {
            while (!Console.KeyAvailable)
            {
            }
        } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
    }

    public static void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState,
        int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
    {
        Console.WriteLine("Finger Recognized");
    }

Body:
You must use STA thread .

Thread TT = new Thread(() =>
{
    CZKEMClass zkem = new CZKEMClass();
    Application.Run();
});
TT.IsBackground = true;
TT.SetApartmentState(ApartmentState.STA);
TT.Start();

Then create event. ZKEM events fire on STA threads.


问:
JPA concurrency issue "On release of batch it still contained JDBC statements"
I have a a concurrency issue I tried to solve with a while loop that attempts to save an entity multiple times until it hits some max retry count. I'd like to avoid talking about whether or not there are other ways to solve this problem. I have other Stackoverflow posts about that. :) Long story short: there's a unique constraint on a column that is derived and includes a numeric portion that keeps incrementing to avoid collisions. In a loop, I:

select max(some_value)

increment the result

attempt to save new object with this new result

explicitly flush the entity and, if that fails because of the unique index, I catch a DataAccessException.

All of this seems to work except when the loop goes back to step 1 and tries to select, I get:

```<code>17:20:46,111 INFO  [org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl] (http-localhost/127.0.0.1:8080-3) HHH000010: On release of batch it still contained JDBC statements
17:20:46,111 INFO  [my.Class] (http-localhost/127.0.0.1:8080-3) MESSAGE="Failed to save to database. Will retry (retry count now at: 9) Exception: could not execute statement; SQL [n/a]; constraint [SCHEMA_NAME.UNIQUE_CONSTRAINT_NAME]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
</code>```

And a new Exception is caught. It seems like the first flush that causes the unique constraint violation and throws the DataAccessException doesn't clear the entity manager's batch. What's the appropriate way to deal with this? I'm using Spring with JPA and don't have direct access to the entity manager. I guess I could inject it if I need it but that's a painful solution to this problem.

答:
You cannot do that - once you flush something and it fails and an exception is thrown, the transaction will be marked as roll back. That means it doesnt matter that you catch the exception and proceed, you'll end up with a rollback.
Actually it doesnt matter at all what exception was thrown - by default Spring's transaction manager will rollback on every unchecked exception.
You can overcome it by specifically defining a noRollbackFor on the @Transactional annotation (providing you are using annotation driver transactions)

Edit - it also won't help you in case of this constraint violation, since the transaction will be probably marked as rollback at the database level.

Body:
I have a a concurrency issue I tried to solve with a while loop that attempts to save an entity multiple times until it hits some max retry count. I'd like to avoid talking about whether or not there are other ways to solve this problem. I have other Stackoverflow posts about that. :) Long story short: there's a unique constraint on a column that is derived and includes a numeric portion that keeps incrementing to avoid collisions. In a loop, I:

select max(some_value)

increment the result

attempt to save new object with this new result

explicitly flush the entity and, if that fails because of the unique index, I catch a DataAccessException.

All of this seems to work except when the loop goes back to step 1 and tries to select, I get:

17:20:46,111 INFO  [org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl] (http-localhost/127.0.0.1:8080-3) HHH000010: On release of batch it still contained JDBC statements
17:20:46,111 INFO  [my.Class] (http-localhost/127.0.0.1:8080-3) MESSAGE="Failed to save to database. Will retry (retry count now at: 9) Exception: could not execute statement; SQL [n/a]; constraint [SCHEMA_NAME.UNIQUE_CONSTRAINT_NAME]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"

And a new Exception is caught. It seems like the first flush that causes the unique constraint violation and throws the DataAccessException doesn't clear the entity manager's batch. What's the appropriate way to deal with this? I'm using Spring with JPA and don't have direct access to the entity manager. I guess I could inject it if I need it but that's a painful solution to this problem.


问:
.htaccess - Add random text after url
i make a .htaccess that can add ?example  after the url
(site.com/page1?EXAMPLE)

but i like to add random numbers or letters there
(site.com/page1?jsf6755saf)

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} !(^|&)EXAMPLE(&|$) [NC]
RewriteRule . %{REQUEST_URI}?EXAMPLE [L,QSA,R=302,NE]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code>```

how i can make this

答:
Only NOTE to the 1st answer by : Panama Jack - SO MUCH THANK YOU.

RewriteMap servers rnd:/path/to/file/map.txt

DO NOT put it in .htaccess file ( it will generate internal error ).

PLACE IT ONLY in one of your *.conf (e.g apache2.conf).

Replace %{servers:random} with ${servers:random}

ONLY THEN - it worked for me.

Documentation source :  https://httpd.apache.org/docs/current/rewrite/rewritemap.html#rnd

Title: .htaccess - Add random text after url

Body:
i make a .htaccess that can add ?example  after the url
(site.com/page1?EXAMPLE)

but i like to add random numbers or letters there
(site.com/page1?jsf6755saf)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} !(^|&)EXAMPLE(&|$) [NC]
RewriteRule . %{REQUEST_URI}?EXAMPLE [L,QSA,R=302,NE]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

how i can make this


问:
react setState does not update the state us expected
I have a react component that looks like this:

```<code>class MyComponent extends Component {
  incrementQty = () => {
    // calls this.setState({....})
  }

  setQty (qty) => {
    for (....) {
      this.incrementQty()
    }
  }
}
</code>```

My problem is that the state does not be updated until the last call in the loop, I knew that setState is asynchronous and I can't use redux here to rerender the component after an action is dispatched.

Has anyone has a solution, and thanks.

答:
You can use callback form of setState that is atomic. Demo
Docs

```<code>this.setState((prevState, props) => {
  return {myInteger: prevState.myInteger + props.step};
});
</code>```

It updates state kinda "redux" way but w/o redux.

```<code>class MyComponent extends Component {
  incrementQty = () => {
    this.setState((prevState) => {
       return {counter: prevState.counter + 1}
    })
  }

  setQty (qty) => {
    for (....) {
      this.incrementQty()
    }
  }
}
</code>```

Full example

```<code>const { Component } = React
const { render } = ReactDOM

class App extends Component {
  constructor(props, ctx) {
    super(props, ctx);

    this.state = {
      counter: 0
    }

    this.inc = this.inc.bind(this);
    this.dec = this.dec.bind(this);
  }

  // this works for multiple calls
  inc() {
    this.setState((prevState) => {
      return {
        counter: prevState.counter + 1
      }
    })
  }

  // this doesn't work on subsequent calls
  dec() {
    this.setState({
      counter: this.state.counter - 1
    })
  }

  up(qty) {
    while(qty--) {
      this.inc()
    }
  }

  down(qty) {
    while(qty--) {
      this.dec()
    }
  }

  render() {
    const { counter } = this.state

    return (
      <div>
        <div>
          <button type="button" onClick={() => this.up(10) }>+10</button>
          <button type="button" onClick={() => this.up(5) }>+5</button>
          <button type="button" onClick={this.inc}>+</button>
          <button type="button" onClick={this.dec}>-</button>
          <button type="button" onClick={() => this.down(5) }>-5</button>
          <button type="button" onClick={() => this.down(10) }>-10</button>
        </div>

        {counter}
      </div>
    )
  }
}

render(<App />, document.getElementById('content'))
</code>```

Body:
I have a react component that looks like this:

class MyComponent extends Component {
  incrementQty = () => {
    // calls this.setState({....})
  }

  setQty (qty) => {
    for (....) {
      this.incrementQty()
    }
  }
}

My problem is that the state does not be updated until the last call in the loop, I knew that setState is asynchronous and I can't use redux here to rerender the component after an action is dispatched.

Has anyone has a solution, and thanks.

Body:
You can use callback form of setState that is atomic. Demo
Docs

this.setState((prevState, props) => {
  return {myInteger: prevState.myInteger + props.step};
});

It updates state kinda "redux" way but w/o redux.

class MyComponent extends Component {
  incrementQty = () => {
    this.setState((prevState) => {
       return {counter: prevState.counter + 1}
    })
  }

  setQty (qty) => {
    for (....) {
      this.incrementQty()
    }
  }
}

Full example

const { Component } = React
const { render } = ReactDOM

class App extends Component {
  constructor(props, ctx) {
    super(props, ctx);

    this.state = {
      counter: 0
    }

    this.inc = this.inc.bind(this);
    this.dec = this.dec.bind(this);
  }

  // this works for multiple calls
  inc() {
    this.setState((prevState) => {
      return {
        counter: prevState.counter + 1
      }
    })
  }

  // this doesn't work on subsequent calls
  dec() {
    this.setState({
      counter: this.state.counter - 1
    })
  }

  up(qty) {
    while(qty--) {
      this.inc()
    }
  }

  down(qty) {
    while(qty--) {
      this.dec()
    }
  }

  render() {
    const { counter } = this.state

    return (
      <div>
        <div>
          <button type="button" onClick={() => this.up(10) }>+10</button>
          <button type="button" onClick={() => this.up(5) }>+5</button>
          <button type="button" onClick={this.inc}>+</button>
          <button type="button" onClick={this.dec}>-</button>
          <button type="button" onClick={() => this.down(5) }>-5</button>
          <button type="button" onClick={() => this.down(10) }>-10</button>
        </div>

        {counter}
      </div>
    )
  }
}

render(<App />, document.getElementById('content'))


问:
What would be an effective way to put a marker drawable on the mapview everytime the user clicks the map
I am playing around with Android MapView and have come across a requirement, where i have to put a marker at the place where the user clicks.
in my scenario, the user can pan a map , zoom in and out, and click wherever she likes.
in this case, the marker should be put wherever the user is clicking on the map.
If a previous marker was there on map, then at click event it should be cleared and be put at the new place.
This should repeat every time the case repeats.

In future, I'll be having some more drawables like range representative and a pointer to select range which can be dragged.

I am able to put the marker on the first place, but my code doesn't work when the user clicks anywhere else.

Here's the code for the class that I am using: http://pastebin.com/6idn7VwK
The full class extending MapActivity and the one extending the ItemizedOverlay can be found in the link above.

I understand that I might be doing some wrong things, so please correct me.

Thanks!

答:
You should override the onTap method for this type of functionality :</p>

```<code>    @Override
    public boolean onTap(GeoPoint point, MapView view) {
         // add your marker to the map by creating an overlayItem and calling addOverlay
    }

 public void addOverlay(OverlayItem overlay) {
     mOverlays.add(overlay);
     populate();
 }
</code>```

Body:
You should override the onTap method for this type of functionality :

    @Override
    public boolean onTap(GeoPoint point, MapView view) {
         // add your marker to the map by creating an overlayItem and calling addOverlay
    }

 public void addOverlay(OverlayItem overlay) {
     mOverlays.add(overlay);
     populate();
 }


问:
Float sum with javascript (jquery)
i have code jquery but i want a plus 0.00001 for value every second

$(document).ready(function(){

 setInterval(function()
 {
   var id = $('.id').attr('rel');
   var st = (parseFloat(id) + parseFloat('0.00001')).toFixed(1);
   $('.id').html(st);
   $('.id').attr('rel',st);

 }, 1000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
// html output
<span class='id' rel='0.00001'>0.00001</span></code>```

答:
The issue is because you're rounding to 1 decimal place using toFixed(1). Change that to toFixed(5) and your code works fine. Although note that converting a string literal to a float is a little redundant, just use the float directly in the addition:

$(document).ready(function() {
  setInterval(function() {
    var id = $('.id').attr('rel');
    var st = (parseFloat(id) + 0.00001).toFixed(5);
    $('.id').html(st).attr('rel', st);
  }, 1000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
// html output
<span class="id" rel="0.00001">0.00001</span></code>```

Title: Float sum with javascript (jquery)

Body:
i have code jquery but i want a plus 0.00001 for value every second

$(document).ready(function(){

 setInterval(function()
 {
   var id = $('.id').attr('rel');
   var st = (parseFloat(id) + parseFloat('0.00001')).toFixed(1);
   $('.id').html(st);
   $('.id').attr('rel',st);

 }, 1000);
});

// html output
0.00001

Body:
The issue is because you're rounding to 1 decimal place using toFixed(1). Change that to toFixed(5) and your code works fine. Although note that converting a string literal to a float is a little redundant, just use the float directly in the addition:

$(document).ready(function() {
  setInterval(function() {
    var id = $('.id').attr('rel');
    var st = (parseFloat(id) + 0.00001).toFixed(5);
    $('.id').html(st).attr('rel', st);
  }, 1000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
// html output
<span class="id" rel="0.00001">0.00001</span>