问:
how to sort values of 1st column and print only corresponding values of third column using awk
I tried to sort the file using awk '{print $0|"sort -t',' -nk1 "}' but I want to print only the third column of sorted file. Input file:

1   4   7   9
9   7   4   1
4   6   8   9
1   2   3   4
5   4   5   2

the expected output:

3
7
8
5
4

答:
Well, since I already started doing it using Gnu awk's asorti:

```<code>$ awk '
    { a[$1 "," $3]=$3 }      # get the data to a hash (*)
END { n=asorti(a)            # sort a by the index
      for(i=1;i<=n;i++) {    # for each ordered index
          split(a[i],b,",")  # split and
          print b[2]         # print the latter part
      }
}' file
3
7
8
5
4
</code>```

(*) If using only $1 as the key there will be a collision when $1=1. For this data using $1 "," $3 won't produce a collision and will sort the $3 as well. However, there could be a collision. The correct way would be to keep a count of the keys and have a sub for loop to print those out (or have keys and values in different arrays indexed with NR). That will be left as an exersize.

Body:
Well, since I already started doing it using Gnu awk's asorti:

$ awk '
    { a[$1 "," $3]=$3 }      # get the data to a hash (*)
END { n=asorti(a)            # sort a by the index
      for(i=1;i<=n;i++) {    # for each ordered index
          split(a[i],b,",")  # split and
          print b[2]         # print the latter part
      }
}' file
3
7
8
5
4

(*) If using only $1 as the key there will be a collision when $1=1. For this data using $1 "," $3 won't produce a collision and will sort the $3 as well. However, there could be a collision. The correct way would be to keep a count of the keys and have a sub for loop to print those out (or have keys and values in different arrays indexed with NR). That will be left as an exersize.


来源: stackexchange

问:
DDD, JPA and Multi-Module Maven
I'm trying to configure and Maven multi-module project with Spring / JPA. Here's the general layout. I have a root module with 5 children modules.

```
backoffice (root maven module)
|
-(maven module)-----core (this is where persistence.xml and entityManager stuff resides).
|
-(maven module)-----employee (employee related entities, controllers, etc.)
|
-(maven module)-----vendor (vendor related entities, controllers, etc.)
|
-(maven module)-----customer (customer related entities, controllers, etc.)
|
-(maven module)-----web (contains all the web stuff).
```

I have all the jpa stuff in core/src/main/resources/META-INF (persistence.xml, spring-context w/ EntityManagerFactory, dataSource, etc.). The idea is I want to share the persistence stuff across all sub-modules (employee, vendor and customer).

The problem is that when the web app starts up, it can't find the EntityMangerFactory. If I setup the JPA stuff in each sub module (employee, vendor and customer), then it works.

How do I setup all my persistence related stuff in core and then share it across the other modules?

Thanks in advance.

答:
If the employee, vendor and customer entities and controllers are so logically separate as to need them in separate modules, then I would say that clearly they should have their own entityManager.

If you want to have a single webapp, and a single entitymanager, then why do you want to have separate modules for each chunk of entities?  Just stick employees, vendors and customer in core, with the entity manager, and be done.

Or, give each one their own entitymanager, (and probably each one their own webapp)

ContentLicense: CC BY-SA 2.5

Title: DDD, JPA and Multi-Module Maven

Body:
I'm trying to configure and Maven multi-module project with Spring / JPA. Here's the general layout. I have a root module with 5 children modules.

backoffice (root maven module)
|
-(maven module)-----core (this is where persistence.xml and entityManager stuff resides).
|
-(maven module)-----employee (employee related entities, controllers, etc.)
|
-(maven module)-----vendor (vendor related entities, controllers, etc.)
|
-(maven module)-----customer (customer related entities, controllers, etc.)
|
-(maven module)-----web (contains all the web stuff).

I have all the jpa stuff in core/src/main/resources/META-INF (persistence.xml, spring-context w/ EntityManagerFactory, dataSource, etc.). The idea is I want to share the persistence stuff across all sub-modules (employee, vendor and customer).

The problem is that when the web app starts up, it can't find the EntityMangerFactory. If I setup the JPA stuff in each sub module (employee, vendor and customer), then it works.

How do I setup all my persistence related stuff in core and then share it across the other modules?

Thanks in advance.


问:
CSS Media Queries not matching max / min widths precisely
Here is the CSS:

```<code>@media only screen and (min-width : 971px) and (max-width : 1224px) {
    main #titlebox{
        height: 300px;
    }
}

@media only screen and (min-width : 785px) and (max-width : 970px) {
    main #titlebox{
        height: 250px;
    }
}

@media only screen and (max-width : 784px) {
    main #titlebox{
        height: 225px;
    }
}
</code>```

The problem is that when resizing the browser, the the media queries are not applied when expected.  For example, starting with the browser very wide (> 1300px) and then slowly decreasing the width of the browser, the first media query doesn't get applied until the  element is approx. 1209px wide.  I would expect that it would apply as soon as the width became 1224px. Likewise, the next one isn't applied until Approx 955px not 970px, and so on. I have tested this behavior in both chrome and firefox.

答:
Check your zoom-level in your browser.
In Firefox your zoom-level affects your webpage but not the displayed screen sizes in the dev-tools.</p>

ContentLicense: CC BY-SA 3.0

Body:
Here is the CSS:

@media only screen and (min-width : 971px) and (max-width : 1224px) {
    main #titlebox{
        height: 300px;
    }
}

@media only screen and (min-width : 785px) and (max-width : 970px) {
    main #titlebox{
        height: 250px;
    }
}

@media only screen and (max-width : 784px) {
    main #titlebox{
        height: 225px;
    }
}

The problem is that when resizing the browser, the the media queries are not applied when expected.  For example, starting with the browser very wide (> 1300px) and then slowly decreasing the width of the browser, the first media query doesn't get applied until the  element is approx. 1209px wide.  I would expect that it would apply as soon as the width became 1224px. Likewise, the next one isn't applied until Approx 955px not 970px, and so on. I have tested this behavior in both chrome and firefox.


问:
Unable to get route working with 2 levels of lazy loaded modules (nested)
I have been trying to create a sample cli based angular4 application with a main module and 3 product modules (product itself being a route param that loads each of the product screen's lazily).

Here is my sample - https://github.com/shankarvn/angular4lazyloading

Steps to reproduce

git clone https://github.com/shankarvn/angular4lazyloading.git

cd application

npm install

ng serve -p 4003

In the browser localhost:4003 => Should load 3 cards showing product1, product2 and product3. At this point, click on product1 and you will see the route change and the ui for product1 loads. Now click on Dashboard and you will see an error in the console

```<code>ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'product1/dashboard'
Error: Cannot match any routes. URL Segment: 'product1/dashboard'
    at ApplyRedirects.noMatchError (router.es5.js:1404) [angular]
    at CatchSubscriber.selector (router.es5.js:1379) [angular]
    at CatchSubscriber.error (catch.js:104) [angular]
</code>```

Unsure what I am doing wrong - Just that dashboard routes are loaded when the product1 module is lazily loaded. Shouldn't the routes get registered when the product1 module is loaded. Any help is appreciated.

Thanks.

答:
Youd shouldn't use pathMatch: 'full'

```<code>export const Product1Routes: Routes = [
  {
    path: '',
    component: Product1Component,
    children:[
      {
        path: 'dashboard',
        loadChildren: 'app/product1/dashboard/dashboard.module#DashboardModule'
        // or './dashboard/...
      },
      {
        path: '',
        component: Product1ViewComponent
      }
    ]
  }
];
</code>```

I also changed loadChildren path a bit. (added app/product1)

Why are you importing HttpModule for each of lazy loaded modules?

This is also redundant in lazy loaded modules

```<code>providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],
</code>```

P.S. I would create Routing modules for each of modules

```<code>app-routing.module.ts
product1-routing.module.ts
dashboard-routing.module.ts
</code>```

and so on

Body:
I have been trying to create a sample cli based angular4 application with a main module and 3 product modules (product itself being a route param that loads each of the product screen's lazily).

Here is my sample - https://github.com/shankarvn/angular4lazyloading

Steps to reproduce

git clone https://github.com/shankarvn/angular4lazyloading.git

cd application

npm install

ng serve -p 4003

In the browser localhost:4003 => Should load 3 cards showing product1, product2 and product3. At this point, click on product1 and you will see the route change and the ui for product1 loads. Now click on Dashboard and you will see an error in the console

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'product1/dashboard'
Error: Cannot match any routes. URL Segment: 'product1/dashboard'
    at ApplyRedirects.noMatchError (router.es5.js:1404) [angular]
    at CatchSubscriber.selector (router.es5.js:1379) [angular]
    at CatchSubscriber.error (catch.js:104) [angular]

Unsure what I am doing wrong - Just that dashboard routes are loaded when the product1 module is lazily loaded. Shouldn't the routes get registered when the product1 module is loaded. Any help is appreciated.

Thanks.

Body:
Youd shouldn't use pathMatch: 'full'

export const Product1Routes: Routes = [
  {
    path: '',
    component: Product1Component,
    children:[
      {
        path: 'dashboard',
        loadChildren: 'app/product1/dashboard/dashboard.module#DashboardModule'
        // or './dashboard/...
      },
      {
        path: '',
        component: Product1ViewComponent
      }
    ]
  }
];

I also changed loadChildren path a bit. (added app/product1)

Why are you importing HttpModule for each of lazy loaded modules?

This is also redundant in lazy loaded modules

providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],

P.S. I would create Routing modules for each of modules

app-routing.module.ts
product1-routing.module.ts
dashboard-routing.module.ts

and so on


问:
install4j sql script action statement with line breaks
a problem with the SQL script action: I use a script with statements including line breaks to make them more readable. I use the semicolon as a statement delimter. When the action fires, the first statement (fired vs an Oracle DB in the example) fails with a "ORA-00904: : invalid identifier" message, showing only the first line of the statement in the installation log.
The statement itself is valid.
My assumption is that install4j fires each line within an sql script, not the whole text (multiple lines) until a statement delimiter is found?
Would be a pity, since long statements tend to be not easy to read.
We are using instll4j 6.1.6 build 6352, the instaler runs under windows (x64).

Thanks a lot for your help in advance,
regards,
Alex

答:
After removing the line breaks within the sql script, it worked.
So currently no line breaks in SQL-Scripts, except they are used as statement delimiters.</p>


问:
Error in SQL Statement (basic)
I'm creating tables for a college excercise, but I keep getting an error executing the query and I can't find the error. SQL Developer is awful specifying it.

This is the SQL Developer output:

```<code>Error stating in line 58:
CREATE TABLE deportexevento(
  id_evento NUMBER NOT NULL,
  id_deporte NUMBER NOT NULL,
  CONSTRAINT pk_deportexevento PRIMARY KEY (id_evento, id_deporte),
  CONSTRAINT fk_evento_deportexevento
    FOREIGN KEY (id_evento)
    REFERENCES evento(id),
  CONSTRAINT fk_deporte_deportexevento
    FOREIGN KEY (id_deporte)
    REFERENCES deporte(id)
)

CREATE TABLE evaluador(
  cuil VARCHAR(15) NOT NULL,
  nombre VARCHAR(60) NOT NULL,
  email VARCHAR(60) NOT NULL,
  CONSTRAINT pk_evaluador PRIMARY KEY (cuil)
)
Error report -
Error SQL: ORA-00922: missing or invalid option
00922. 00000 -  "missing or invalid option"
*Cause:
*Action:
</code>```

Full SQL: https://pastebin.com/pfCz5Jwt

答:
Try a semicolon after each of your create statements, as below...</p>

```<code>CREATE TABLE deportexevento
(
    id_evento NUMBER NOT NULL,
    id_deporte NUMBER NOT NULL,
    CONSTRAINT pk_deportexevento PRIMARY KEY ( id_evento, id_deporte ),
    CONSTRAINT fk_evento_deportexevento
        FOREIGN KEY ( id_evento )
        REFERENCES evento( id ),
    CONSTRAINT fk_deporte_deportexevento
        FOREIGN KEY ( id_deporte )
        REFERENCES deporte( id )
);
CREATE TABLE evaluador
(
    cuil VARCHAR( 15 ) NOT NULL,
    nombre VARCHAR( 60 ) NOT NULL,
    email VARCHAR( 60 ) NOT NULL,
    CONSTRAINT pk_evaluador PRIMARY KEY ( cuil )
);
</code>```

Title: Error in SQL Statement (basic)

Body:
I'm creating tables for a college excercise, but I keep getting an error executing the query and I can't find the error. SQL Developer is awful specifying it.

This is the SQL Developer output:

Error stating in line 58:
CREATE TABLE deportexevento(
  id_evento NUMBER NOT NULL,
  id_deporte NUMBER NOT NULL,
  CONSTRAINT pk_deportexevento PRIMARY KEY (id_evento, id_deporte),
  CONSTRAINT fk_evento_deportexevento
    FOREIGN KEY (id_evento)
    REFERENCES evento(id),
  CONSTRAINT fk_deporte_deportexevento
    FOREIGN KEY (id_deporte)
    REFERENCES deporte(id)
)

CREATE TABLE evaluador(
  cuil VARCHAR(15) NOT NULL,
  nombre VARCHAR(60) NOT NULL,
  email VARCHAR(60) NOT NULL,
  CONSTRAINT pk_evaluador PRIMARY KEY (cuil)
)
Error report -
Error SQL: ORA-00922: missing or invalid option
00922. 00000 -  "missing or invalid option"
*Cause:
*Action:

Full SQL: https://pastebin.com/pfCz5Jwt

Body:
Try a semicolon after each of your create statements, as below...

CREATE TABLE deportexevento
(
    id_evento NUMBER NOT NULL,
    id_deporte NUMBER NOT NULL,
    CONSTRAINT pk_deportexevento PRIMARY KEY ( id_evento, id_deporte ),
    CONSTRAINT fk_evento_deportexevento
        FOREIGN KEY ( id_evento )
        REFERENCES evento( id ),
    CONSTRAINT fk_deporte_deportexevento
        FOREIGN KEY ( id_deporte )
        REFERENCES deporte( id )
);
CREATE TABLE evaluador
(
    cuil VARCHAR( 15 ) NOT NULL,
    nombre VARCHAR( 60 ) NOT NULL,
    email VARCHAR( 60 ) NOT NULL,
    CONSTRAINT pk_evaluador PRIMARY KEY ( cuil )
);


问:
Remove duplicate rows from joined table
I have following sql query

```<code>SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode
</code>```

Which provide following result

```<code>School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1
</code>```

My question is how to remove those duplicates and get only following.

```<code> School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1
</code>```

I tried with

```<code>   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School
</code>```

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."

答:
No need to make things complicated.  Just go with:

```<code>SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode
group by m.School, c.avgscore
</code>```

or

```<code>SELECT DISTINCT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode
</code>```

Title: Remove duplicate rows from joined table

Body:
I have following sql query

SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode

Which provide following result

School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1

My question is how to remove those duplicates and get only following.

 School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1

I tried with

   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."

Body:
No need to make things complicated.  Just go with:

SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode
group by m.School, c.avgscore

or

SELECT DISTINCT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode


问:
Use Idea+Gradle can't import aspectjrt and aspectweaver jar
I was learning Spring AOP ,and i write a sample use Spring AOP's Around Advice.It need the aspectjrt.jar and aspectjweaver.jar.so i add dependencies in the build.gradle file.

```<code>dependencies {

   testCompile group: 'junit', name: 'junit', version: '4.11'
   compile 'org.springframework:spring-context:4.3.6.RELEASE'
   compile group: 'org.aspectj', name: 'aspectjrt', version: '1.8.9'
   compile group: 'org.aspectj', name: 'aspectjweaver', version: '1.8.9'
}
</code>```

Refresh the gradle,but the External Libraries didn't have aspectjrt.jar and aspectweaver.jar.
Then I found this information from the file .idea/Libraries/Gradle_org_aspectj_aspectjrt_1.8.9.xml

```<code><component name="libraryTable">
  <library name="Gradle: org.aspectj:aspectjrt:1.8.9">
  <CLASSES>
     <root url="file://$PROJECT_DIR$/Could not resolve org.aspectj:aspectjrt:1.8.9." />
   </CLASSES>
  <JAVADOC />
  <SOURCES />
 </library>
</component>
</code>```

but i can find the jar from there: * ~/.gradle/caches/modules-2/files-2.1/org.aspectj/aspectjrt/1.8.9/87372d9e2323313bec24b09a325bfea8ae0eb867/aspectjrt.jar*, and if i use the string * ~/.gradle/caches/modules-2/files-2.1/org.aspectj/aspectjrt/1.8.9/87372d9e2323313bec24b09a325bfea8ae0eb867/aspectjrt.jar!/* replace the url's value in this sentence :.it will be ok .But If changing the build.gradle again, it will return back.

Can some help me ? THX!

macOS 10.12.3

IDEA 2016.3.4

Gradle 3.1

jdk 1.8.0_121-b13

答:
change the build.gradle file like this,It's work! Amazing.</p>

```<code>dependencies {

   testCompile group: 'junit', name: 'junit', version: '4.11'
   compile group: 'org.aspectj', name: 'aspectjrt', version: '1.8.9'
   compile group: 'org.aspectj', name: 'aspectjweaver', version: '1.8.9'
   compile 'org.springframework:spring-context:4.3.6.RELEASE'
}
</code>```

Body:
I was learning Spring AOP ,and i write a sample use Spring AOP's Around Advice.It need the aspectjrt.jar and aspectjweaver.jar.so i add dependencies in the build.gradle file.

dependencies {

   testCompile group: 'junit', name: 'junit', version: '4.11'
   compile 'org.springframework:spring-context:4.3.6.RELEASE'
   compile group: 'org.aspectj', name: 'aspectjrt', version: '1.8.9'
   compile group: 'org.aspectj', name: 'aspectjweaver', version: '1.8.9'
}

Refresh the gradle,but the External Libraries didn't have aspectjrt.jar and aspectweaver.jar.
Then I found this information from the file .idea/Libraries/Gradle_org_aspectj_aspectjrt_1.8.9.xml

<component name="libraryTable">
  <library name="Gradle: org.aspectj:aspectjrt:1.8.9">
  <CLASSES>
     <root url="file://$PROJECT_DIR$/Could not resolve org.aspectj:aspectjrt:1.8.9." />
   </CLASSES>
  <JAVADOC />
  <SOURCES />
 </library>
</component>

but i can find the jar from there: * ~/.gradle/caches/modules-2/files-2.1/org.aspectj/aspectjrt/1.8.9/87372d9e2323313bec24b09a325bfea8ae0eb867/aspectjrt.jar*, and if i use the string * ~/.gradle/caches/modules-2/files-2.1/org.aspectj/aspectjrt/1.8.9/87372d9e2323313bec24b09a325bfea8ae0eb867/aspectjrt.jar!/* replace the url's value in this sentence :.it will be ok .But If changing the build.gradle again, it will return back.

Can some help me ? THX!

macOS 10.12.3

IDEA 2016.3.4

Gradle 3.1

jdk 1.8.0_121-b13

Body:
change the build.gradle file like this,It's work! Amazing.

dependencies {

   testCompile group: 'junit', name: 'junit', version: '4.11'
   compile group: 'org.aspectj', name: 'aspectjrt', version: '1.8.9'
   compile group: 'org.aspectj', name: 'aspectjweaver', version: '1.8.9'
   compile 'org.springframework:spring-context:4.3.6.RELEASE'
}


问:
Detect ETX characters using Java
We have a text file with multiples paragraphs each separated by
character ETX as shown in below image. The Java program should
 read each paragraph and parse and the end of paragaraph should be
 identified by ETX.

How to make Java recognize or detect the EXT character?

答:
ETX is an ASCII character, designed to indicate the end of transmission.

It also has the unicode codepoint U+0003 and you can thus find it by searching your string for this codepoint. If you are working with 8-bit strings, search for "\x03".

Title: Detect ETX characters using Java


问:
Get line number of beginning and end of Ruby method given a ruby file
How can I find the line of the beginning and end of a Ruby method given a ruby file?

Say for example:

```<code>1 class Home
2   def initialize(color)
3     @color = color
4   end
5 end
</code>```

Given the file home.rb and the method name initialize I would like to receive (2,4) which are the beginning and end lines.

答:
I have assumed that the file contains the definition of at most one initialize method (though generalizing the method to search for others would not be difficult) and that the definition of that method contains no syntax errors. The latter assumption is probably required for any method to extract the correct line range.

The only tricky part is finding the line containing end that is the last line of the definition of the initialize method. I've used Kernel#eval to locate that line. Naturally caution must be exercised whenever that method is to be executed, though here eval is merely attempting to compile (not execute) a method.

Code

```<code>def get_start_end_offsets(fname)
  start = nil
  str = ''
  File.foreach(fname).with_index do |line, i|
    if start.nil?
      next unless line.lstrip.start_with?('def initialize')
      start = i
      str << line.lstrip.insert(4,'_')
    else
      str << line
      if line.strip == "end"
        begin
          rv = eval(str)
        rescue SyntaxError
          nil
        end
        return [start, i] unless rv.nil?
      end
    end
  end
  nil
end
</code>```

Example

Suppose we are searching a file created as follows1.

```<code>str = <<-_
class C
  def self.feline
    "cat"
  end
  def initialize(arr)
    @row_sums = arr.map do |row|
      row.reduce do |t,x|
        t+x
      end
    end
  end
  def speak(sound)
    puts sound
  end
end
_

FName = 'temp'
File.write(FName, str)
  #=> 203
</code>```

We first search for the line that begins (after stripping leading spaces) "def initialize". That is the line at index 4. The end that completes the definition of that method is at index 10. We therefore expect the method to return [4, 10].

Let's see if that's what we get.

```<code>p get_start_end_offsets(FName)
  #=> [4, 10]
</code>```

Explanation

The variable start equals the index of the line beginning def initialize (after removing leading whitespace). start is initially nil and remains nil until the "def initialize" line is found. start is then set to the index of that line.

We now look for a line line such that line.strip #=> "end". This may or may not be the end that terminates the method. To determine if it is we eval a string that contains all lines from the one that begins def initialize to the line equal to end just found. If eval raises a SyntaxError exception that end does not terminate the method. That exception is rescued and nil is returned. eval will return :_initialize (which is truthy) if that end terminates the method. In that case the method returns [start, i], where i is the index of that line. nil is returned if no initialize method is found in the file.

I've converted "initialize" to "_initialize" to suppress the warning  (eval):1: warning: redefining Object#initialize may cause infinite loop)

See both answers to this SO question to understand why SyntaxError is being rescued.

Compare indentation

If it is known that "def initialize..." is always indented the same amount as the line "end" that terminates the method definition (and no other lines "end" between the two are indented the same), we can use that fact to obtain the beginning and ending lines. There are many ways to do that; I will use Ruby's somewhat obscure flip-flop operator. This approach will tolerate syntax errors.

```<code>def get_start_end_offsets(fname)
  indent = -1
  lines = File.foreach(fname).with_index.select do |line, i|
    cond1 = line.lstrip.start_with?('def initialize')
    indent = line.size - line.lstrip.size if cond1
    cond2 = line.strip == "end" && line.size - line.lstrip.size == indent
    cond1 .. cond2 ? true : false
  end
  return nil if lines.nil?
  lines.map(&:last).minmax
end

get_start_end_offsets(FName)
  #=> [4, 10]
</code>```

1 The file need not contain only code.

Body:
How can I find the line of the beginning and end of a Ruby method given a ruby file?

Say for example:

1 class Home
2   def initialize(color)
3     @color = color
4   end
5 end

Given the file home.rb and the method name initialize I would like to receive (2,4) which are the beginning and end lines.

Body:
I have assumed that the file contains the definition of at most one initialize method (though generalizing the method to search for others would not be difficult) and that the definition of that method contains no syntax errors. The latter assumption is probably required for any method to extract the correct line range.

The only tricky part is finding the line containing end that is the last line of the definition of the initialize method. I've used Kernel#eval to locate that line. Naturally caution must be exercised whenever that method is to be executed, though here eval is merely attempting to compile (not execute) a method.

Code

def get_start_end_offsets(fname)
  start = nil
  str = ''
  File.foreach(fname).with_index do |line, i|
    if start.nil?
      next unless line.lstrip.start_with?('def initialize')
      start = i
      str << line.lstrip.insert(4,'_')
    else
      str << line
      if line.strip == "end"
        begin
          rv = eval(str)
        rescue SyntaxError
          nil
        end
        return [start, i] unless rv.nil?
      end
    end
  end
  nil
end

Example

Suppose we are searching a file created as follows1.

str = <<-_
class C
  def self.feline
    "cat"
  end
  def initialize(arr)
    @row_sums = arr.map do |row|
      row.reduce do |t,x|
        t+x
      end
    end
  end
  def speak(sound)
    puts sound
  end
end
_

FName = 'temp'
File.write(FName, str)
  #=> 203

We first search for the line that begins (after stripping leading spaces) "def initialize". That is the line at index 4. The end that completes the definition of that method is at index 10. We therefore expect the method to return [4, 10].

Let's see if that's what we get.

p get_start_end_offsets(FName)
  #=> [4, 10]

Explanation

The variable start equals the index of the line beginning def initialize (after removing leading whitespace). start is initially nil and remains nil until the "def initialize" line is found. start is then set to the index of that line.

We now look for a line line such that line.strip #=> "end". This may or may not be the end that terminates the method. To determine if it is we eval a string that contains all lines from the one that begins def initialize to the line equal to end just found. If eval raises a SyntaxError exception that end does not terminate the method. That exception is rescued and nil is returned. eval will return :_initialize (which is truthy) if that end terminates the method. In that case the method returns [start, i], where i is the index of that line. nil is returned if no initialize method is found in the file.

I've converted "initialize" to "_initialize" to suppress the warning  (eval):1: warning: redefining Object#initialize may cause infinite loop)

See both answers to this SO question to understand why SyntaxError is being rescued.

Compare indentation

If it is known that "def initialize..." is always indented the same amount as the line "end" that terminates the method definition (and no other lines "end" between the two are indented the same), we can use that fact to obtain the beginning and ending lines. There are many ways to do that; I will use Ruby's somewhat obscure flip-flop operator. This approach will tolerate syntax errors.

def get_start_end_offsets(fname)
  indent = -1
  lines = File.foreach(fname).with_index.select do |line, i|
    cond1 = line.lstrip.start_with?('def initialize')
    indent = line.size - line.lstrip.size if cond1
    cond2 = line.strip == "end" && line.size - line.lstrip.size == indent
    cond1 .. cond2 ? true : false
  end
  return nil if lines.nil?
  lines.map(&:last).minmax
end

get_start_end_offsets(FName)
  #=> [4, 10]

1 The file need not contain only code.


问:
Instantiating a C++ struct derived from a class in cython
I am trying to interface Python to the Bullet Physics C++ library using Cython. I would like to do this at C speeds, or near C speeds with minimal variable packing and unpacking from Python. I was able to use this approach to create a Cython interface to OpenGL (though OpenGL has a much simpler, non object-oriented C API, compared to Bullet Physics). My OpenGL interfaces works well but progress has been slow on interfacing with Bullet Physics.

I have read the Cython C++ tutorial and other related posts here but so far no luck.

The organization of Bullet Physics is a bit complex, but for this example hopefully it will be enough to know that btDbvtBroadphase is a struct which is derived from the btBroadphaseInterface class. As you probably know, structs can be derived from classes (inherit from them) and there isn't too much difference between the two--in C++ at least. However, Cython seems to only allow "new" to be done on classes and not on structs. I think that leads to my first problem.

The declarations in the Bullet Physics .h files look like this:

```<code>class btBroadphaseInterface
{
    ...
</code>```

and

```<code>struct  btDbvtBroadphase : btBroadphaseInterface
{
    ...
</code>```

The very simple line of C++ code I'm trying to replicate efficiently in Cython is this:

```<code>btBroadphaseInterface* broadphase = new btDbvtBroadphase();
</code>```

So, since in Cython I can't do a "new" on a btDbvtBroadphase struct as is done in C++, how do I instantiate this struct, derived from the class, so that all initializers are called and methods set up inside?

I have seen some references to limitations on inheritance within Cython.

I can obviously malloc() the space for the structure, but that doesn't help me much, I think. I can't see how any sort of casting would help.

I have the Cython ".pxd" stuff showing how I do the cdef extern from the .h file but I didn't think that would help clarify this question, so I'll omit that unless someone thinks it might be helpful.

I have tried many variants of cdefs with no luck. Here is what it looks like now:

```<code>cdef extern from "bullet/btBulletDynamicsCommon.h":
    cdef cppclass btBroadphaseInterface:
        pass

    cdef cppclass btDbvtBroadphase(btBroadphaseInterface):
        pass
</code>```

When I try to write a constructor that will do a "new" on this struct derived from a class, like this:

```<code>cdef class PbtDbvtBroadphase:
    cdef btBroadphaseInterface *bp

    def __cinit__(self):
        self.bp=<btBroadphaseInterface *> new btDbvtBroadphase()
</code>```

The compiler fails with:

Error compiling Cython file:
  ------------------------------------------------------------ ...

cdef class PbtDbvtBroadphase:
      cdef btBroadphaseInterface *bp

```<code>def __cinit__(self):
    self.bp=<btBroadphaseInterface *> new btDbvtBroadphase()
</code>```

                                             ^

fun4.pyx:173:46: new operator can only be applied to a C++ class

Edit: improved title, which I had initially entered as just a string of keywords

Edit2: added the cdefs and compiler output

I'm accepting the very patient @DavidW's answer since it demonstrated that things should work. I think what was happening was that I had a stray .pxd file named with the same basename as my .pyx file, and that was being integrated into the build even though I was not using distutils but rather just cython from the command line. The .pxd was left over from an earlier test when I thought my build method might not be giving the same results as the distutils/setup.py approach. I became convinced my build method wasn't related to the problem and went back to my preferred approach (putting cdefs in the .pyx file and just compiling and linking via a simple shell script as shown in one of my comments below) but the .pxd file was still around and silently still getting pulled in by the cython compiler without my knowledge. I discovered this when I noticed that I was getting "redeclared" errors on compilation. I missed the "redeclared" which were scrolling away and only saw the errors on the new constructor attempts.

答:
The easiest option is just to tell Cython it's a class:

```<code>cdef cppclass btDvbtBroadphase(btBroadphaseInterface):
    #etc
</code>```

The difference between struct and class in C++ is only really the default visibility of members. From Cython's point of view it behaves the same and so it doesn't matter that what you tell Cython doesn't match the C++ code.

(It may also be worth omitting telling Cython about the inheritance. If you don't use the inheritance in Cython then it doesn't need to know. It's often easier not to reproduce the full hierarchy but only the bits you need)

Edit: the following code works for me:

header.hpp:

```<code>class btBroadphaseInterface {

};

struct btDbvtBroadphase : btBroadphaseInterface {

};
</code>```

pymod.pyx:

```<code>cdef extern from "header.hpp":
    cppclass btBroadphaseInterface:
        pass

    cppclass btDbvtBroadphase(btBroadphaseInterface):
        pass

cdef class PyBroadphase:
    cdef btBroadphaseInterface* pt
    def __cinit__(self):
        self.pt = new btDbvtBroadphase()

    def __dealloc__(self):
        del self.pt
</code>```

setup.py

```<code>from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(ext_modules = cythonize(Extension(
           "pymod",                                # the extension name
           sources=["pymod.pyx",], # the Cython source and
                                                  # additional C++ source files
           language="c++",                        # generate and compile C++ code
      )))
</code>```

Body:
I am trying to interface Python to the Bullet Physics C++ library using Cython. I would like to do this at C speeds, or near C speeds with minimal variable packing and unpacking from Python. I was able to use this approach to create a Cython interface to OpenGL (though OpenGL has a much simpler, non object-oriented C API, compared to Bullet Physics). My OpenGL interfaces works well but progress has been slow on interfacing with Bullet Physics.

I have read the Cython C++ tutorial and other related posts here but so far no luck.

The organization of Bullet Physics is a bit complex, but for this example hopefully it will be enough to know that btDbvtBroadphase is a struct which is derived from the btBroadphaseInterface class. As you probably know, structs can be derived from classes (inherit from them) and there isn't too much difference between the two--in C++ at least. However, Cython seems to only allow "new" to be done on classes and not on structs. I think that leads to my first problem.

The declarations in the Bullet Physics .h files look like this:

class btBroadphaseInterface
{
    ...

and

struct  btDbvtBroadphase : btBroadphaseInterface
{
    ...

The very simple line of C++ code I'm trying to replicate efficiently in Cython is this:

btBroadphaseInterface* broadphase = new btDbvtBroadphase();

So, since in Cython I can't do a "new" on a btDbvtBroadphase struct as is done in C++, how do I instantiate this struct, derived from the class, so that all initializers are called and methods set up inside?

I have seen some references to limitations on inheritance within Cython.

I can obviously malloc() the space for the structure, but that doesn't help me much, I think. I can't see how any sort of casting would help.

I have the Cython ".pxd" stuff showing how I do the cdef extern from the .h file but I didn't think that would help clarify this question, so I'll omit that unless someone thinks it might be helpful.

I have tried many variants of cdefs with no luck. Here is what it looks like now:

cdef extern from "bullet/btBulletDynamicsCommon.h":
    cdef cppclass btBroadphaseInterface:
        pass

    cdef cppclass btDbvtBroadphase(btBroadphaseInterface):
        pass

When I try to write a constructor that will do a "new" on this struct derived from a class, like this:

cdef class PbtDbvtBroadphase:
    cdef btBroadphaseInterface *bp

    def __cinit__(self):
        self.bp=<btBroadphaseInterface *> new btDbvtBroadphase()

The compiler fails with:

Error compiling Cython file:
  ------------------------------------------------------------ ...

cdef class PbtDbvtBroadphase:
      cdef btBroadphaseInterface *bp

def __cinit__(self):
    self.bp=<btBroadphaseInterface *> new btDbvtBroadphase()

                                             ^

fun4.pyx:173:46: new operator can only be applied to a C++ class

Edit: improved title, which I had initially entered as just a string of keywords

Edit2: added the cdefs and compiler output

I'm accepting the very patient @DavidW's answer since it demonstrated that things should work. I think what was happening was that I had a stray .pxd file named with the same basename as my .pyx file, and that was being integrated into the build even though I was not using distutils but rather just cython from the command line. The .pxd was left over from an earlier test when I thought my build method might not be giving the same results as the distutils/setup.py approach. I became convinced my build method wasn't related to the problem and went back to my preferred approach (putting cdefs in the .pyx file and just compiling and linking via a simple shell script as shown in one of my comments below) but the .pxd file was still around and silently still getting pulled in by the cython compiler without my knowledge. I discovered this when I noticed that I was getting "redeclared" errors on compilation. I missed the "redeclared" which were scrolling away and only saw the errors on the new constructor attempts.

Body:
The easiest option is just to tell Cython it's a class:

cdef cppclass btDvbtBroadphase(btBroadphaseInterface):
    #etc

The difference between struct and class in C++ is only really the default visibility of members. From Cython's point of view it behaves the same and so it doesn't matter that what you tell Cython doesn't match the C++ code.

(It may also be worth omitting telling Cython about the inheritance. If you don't use the inheritance in Cython then it doesn't need to know. It's often easier not to reproduce the full hierarchy but only the bits you need)

Edit: the following code works for me:

header.hpp:

class btBroadphaseInterface {

};

struct btDbvtBroadphase : btBroadphaseInterface {

};

pymod.pyx:

cdef extern from "header.hpp":
    cppclass btBroadphaseInterface:
        pass

    cppclass btDbvtBroadphase(btBroadphaseInterface):
        pass

cdef class PyBroadphase:
    cdef btBroadphaseInterface* pt
    def __cinit__(self):
        self.pt = new btDbvtBroadphase()

    def __dealloc__(self):
        del self.pt

setup.py

from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(ext_modules = cythonize(Extension(
           "pymod",                                # the extension name
           sources=["pymod.pyx",], # the Cython source and
                                                  # additional C++ source files
           language="c++",                        # generate and compile C++ code
      )))


问:
How can I select multiple fields in the results grid in Mysql Workbench on MacOS X?
When selecting multiple fields using Command click, the whole rows are selected. </p>

<p>Tried lot of possible combinations of keys - didn't find how to select just some fields. This is possible on windows using Ctrl click. </p>

答: Due to the way the native control works on macOS it's not possible to select multiple individual cells there. On Windows we use a custom control which supports that feature.</p>

Body:
When selecting multiple fields using Command click, the whole rows are selected.

Tried lot of possible combinations of keys - didn't find how to select just some fields. This is possible on windows using Ctrl click.


问:
Why the python regex pattern fails to match when append a dollar($)?
Here's a small code, using python 3.4

```<code>import re
path_pattern=r'(([^\W]|[.~%$])+)'
re.search(path_pattern+'$','./').string
</code>```

It will report AttributeError: 'NoneType' object has no attribute 'string' on execution.

If I remove the +'$' in the code, It works,

```<code>import re
path_pattern=r'(([^\W]|[.~%$])+)'
re.search(path_pattern,'./').string
</code>```

As far as I know, $ is for matching the end of string, but why isn't it working here?

答:
If your explore your regex path_pattern at https://regex101.com/, you'll find it only matches ., so after you append $, it'll match nothing, and re.search returns None if no position in the string matches the pattern, that's why you get the error.

Check it out here:

```<code>>>> path_pattern=r'(([^\W]|[.~%$])+)'
>>> r = re.search(path_pattern + "$",'./')
>>> print(r)
None
</code>```

Body:
Here's a small code, using python 3.4

import re
path_pattern=r'(([^\W]|[.~%$])+)'
re.search(path_pattern+'$','./').string

It will report AttributeError: 'NoneType' object has no attribute 'string' on execution.

If I remove the +'$' in the code, It works,

import re
path_pattern=r'(([^\W]|[.~%$])+)'
re.search(path_pattern,'./').string

As far as I know, $ is for matching the end of string, but why isn't it working here?

Body:
If your explore your regex path_pattern at https://regex101.com/, you'll find it only matches ., so after you append $, it'll match nothing, and re.search returns None if no position in the string matches the pattern, that's why you get the error.

Check it out here:

>>> path_pattern=r'(([^\W]|[.~%$])+)'
>>> r = re.search(path_pattern + "$",'./')
>>> print(r)
None


问:
How to split lines from Windows text file (/r/n separation)
My question is quite simple. I need to get all text lines from Windows text file.
All lines are separated by \r\n symbols. I use String.Split, but its not cool, because
it only splits 'by one symbol' leaving empty string that I need to remove with options flag. Is there a better way?

My implementation

```<code>string wholefile = GetFromSomeWhere();

// now parsing
string[] lines = operationtext.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

// ok now I have lines array
</code>```

UPDATE

File.ReadAllXXX is of no use here coz GetFromSomeWhere is actually RegEx, so I've no file after this point.

答:
String.Split does accept a string (like "\r\n"). Not just a chararray.</p>

```<code>string[] lines = wholetext.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
</code>```

Body:
My question is quite simple. I need to get all text lines from Windows text file.
All lines are separated by \r\n symbols. I use String.Split, but its not cool, because
it only splits 'by one symbol' leaving empty string that I need to remove with options flag. Is there a better way?

My implementation

string wholefile = GetFromSomeWhere();

// now parsing
string[] lines = operationtext.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

// ok now I have lines array

UPDATE

File.ReadAllXXX is of no use here coz GetFromSomeWhere is actually RegEx, so I've no file after this point.

Body:
String.Split does accept a string (like "\r\n"). Not just a chararray.

string[] lines = wholetext.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);


问:
Cannot find symbol - method: variable(double)
My program is not close to being finished, but I am stuck because the compiler gives me an error message "cannot find symbol - method years(double)" in the depreciatonTable method the variable years.

-I am sure it is very obvious, but I cannot seem to figure out why the compiler comes up with an error.

```<code>import java.util.Scanner;
public class Problem1
{
public static void main(String args[])
{
    double AcquisVal, SalvageVal, years;
    Scanner scan = new Scanner(System.in);
    Problem1 val = new Problem1();

    System.out.println("Enter the Acquisition Value: ")  ;

    AcquisVal = scan.nextDouble();

    System.out.println("Enter the Salvage Value: ");

    SalvageVal = scan.nextDouble();

    System.out.println("Enter the years of useful life(in whole years): ");

    years = scan.nextDouble();

    if (AcquisVal < 0)
    {
        System.out.println("Acquisition value cannot be negative");
    }
    else if (years < 1){
        System.out.println("Years of useful life must be greater than zero");
    }
    else if (SalvageVal < 0){
        System.out.println("Salvage value cannot be negative");
    }
    else
        val.depreciationtable(AcquisVal, SalvageVal, years);
}

public double depreciationtable(double years, double AcquisVal, double SalvageVal)
{
    double depreciation, fraction, annDepreciation, AccDepreciation, BookValue;

    while (years > 0)
    {
        fraction = years / (years (years + 1)/ 2);
        years--;
    }
    depreciation = (AcquisVal - SalvageVal) * fraction;
    return depreciation;
}
}
</code>```

答:
There is something wrong in your logic at

fraction = years / (years (years + 1)/ 2). The years (years + 1) part is logically wrong.

Also, look at the Java Naming conventions to use correct variable/method names.

Body:
My program is not close to being finished, but I am stuck because the compiler gives me an error message "cannot find symbol - method years(double)" in the depreciatonTable method the variable years.

-I am sure it is very obvious, but I cannot seem to figure out why the compiler comes up with an error.

import java.util.Scanner;
public class Problem1
{
public static void main(String args[])
{
    double AcquisVal, SalvageVal, years;
    Scanner scan = new Scanner(System.in);
    Problem1 val = new Problem1();

    System.out.println("Enter the Acquisition Value: ")  ;

    AcquisVal = scan.nextDouble();

    System.out.println("Enter the Salvage Value: ");

    SalvageVal = scan.nextDouble();

    System.out.println("Enter the years of useful life(in whole years): ");

    years = scan.nextDouble();

    if (AcquisVal < 0)
    {
        System.out.println("Acquisition value cannot be negative");
    }
    else if (years < 1){
        System.out.println("Years of useful life must be greater than zero");
    }
    else if (SalvageVal < 0){
        System.out.println("Salvage value cannot be negative");
    }
    else
        val.depreciationtable(AcquisVal, SalvageVal, years);
}

public double depreciationtable(double years, double AcquisVal, double SalvageVal)
{
    double depreciation, fraction, annDepreciation, AccDepreciation, BookValue;

    while (years > 0)
    {
        fraction = years / (years (years + 1)/ 2);
        years--;
    }
    depreciation = (AcquisVal - SalvageVal) * fraction;
    return depreciation;
}
}


问:
Sporadic Error with progress dialog in async task
I have code that processes files async. From what I can tell I am opening a process dialog properly. But android says that there is an error in the pre execute function

My code

```<code>private class asyncparsefile extends AsyncTask<String, Void, Boolean> {

    int avg;
    int max;
    int min;
    int totalwords;
    int totalsentences;
    HashMap<String, Integer> words;
    HashMap<String, Integer> poscount;
    private ProgressDialog dialogp;

    /** progress dialog to show user that the backup is processing. */
    /**
     * application context.
     */
    @Override
    protected void onPreExecute() {
        if (dialogp != null){
            dialogp.dismiss();
        }
        dialogp =  new ProgressDialog(MainActivity.this);
        dialogp.setMessage("Please wait");
        dialogp.show();
    }

    @Override
    protected Boolean doInBackground(final String... args) {
        Helper help = new Helper(filepath, getApplicationContext());
        avg = help.avgsentence();
        max = help.maxsentence();
        min = help.minsentence();
        words = help.individualWordCounts();
        totalsentences = help.sentencecount();
        totalwords = help.wordcount();
        if (isCheck) {
            Languageanalytics ana = new Languageanalytics(help.getSentences(), getApplicationContext());
            poscount = ana.countPOS();

        }

        return true;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        super.onPostExecute(success);
        dialogp.dismiss();
        dialogp = null;

        //TODO Add results page, then this thing should throw to said page
        Intent intent = new Intent(getBaseContext(), ResultsActivity.class);
        intent.putExtra("Average", avg);
        intent.putExtra("Max", max);
        intent.putExtra("Min", min);
        intent.putExtra("Map_counting_of_individual_words", words);
        intent.putExtra("Sentences_in_Document", totalsentences);
        intent.putExtra("Words_in_Document", totalwords);
        if (isCheck){
            intent.putExtra("POSCount", poscount);
        }

        startActivity(intent);
    }
}
</code>```

And the error it produces. Any reason why this error doesn't seem to consistently popup? Any help would be appreciated

```<code>WindowManager: android.view.WindowLeaked: Activity textsnoop.rddigi.com.textstats.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41f322c0 V.E..... R......D 0,0-665,96} that was originally added here
                                                                             at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
                                                                             at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
                                                                             at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
                                                                             at android.app.Dialog.show(Dialog.java:286)
                                                                             at textsnoop.rddigi.com.textstats.MainActivity$asyncparsefile.onPreExecute(MainActivity.java:135)
                                                                             at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
                                                                             at android.os.AsyncTask.execute(AsyncTask.java:535)
                                                                             at textsnoop.rddigi.com.textstats.MainActivity$2.onClick(MainActivity.java:75)
                                                                             at android.view.View.performClick(View.java:4445)
                                                                             at android.view.View$PerformClick.run(View.java:18446)
                                                                             at android.os.Handler.handleCallback(Handler.java:733)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:136)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5146)
                                                                             at java.lang.reflect.Method.invokeNative(Native Method)
                                                                             at java.lang.reflect.Method.invoke(Method.java:515)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
                                                                             at dalvik.system.NativeStart.main(Native Method)
</code>```

答: As it turns out the problem was that I didn't catch a null pointer exception. Added in a try catch block and the problem was found and remedied.</p>

Body:
I have code that processes files async. From what I can tell I am opening a process dialog properly. But android says that there is an error in the pre execute function

My code

private class asyncparsefile extends AsyncTask<String, Void, Boolean> {

    int avg;
    int max;
    int min;
    int totalwords;
    int totalsentences;
    HashMap<String, Integer> words;
    HashMap<String, Integer> poscount;
    private ProgressDialog dialogp;

    /** progress dialog to show user that the backup is processing. */
    /**
     * application context.
     */
    @Override
    protected void onPreExecute() {
        if (dialogp != null){
            dialogp.dismiss();
        }
        dialogp =  new ProgressDialog(MainActivity.this);
        dialogp.setMessage("Please wait");
        dialogp.show();
    }

    @Override
    protected Boolean doInBackground(final String... args) {
        Helper help = new Helper(filepath, getApplicationContext());
        avg = help.avgsentence();
        max = help.maxsentence();
        min = help.minsentence();
        words = help.individualWordCounts();
        totalsentences = help.sentencecount();
        totalwords = help.wordcount();
        if (isCheck) {
            Languageanalytics ana = new Languageanalytics(help.getSentences(), getApplicationContext());
            poscount = ana.countPOS();

        }

        return true;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        super.onPostExecute(success);
        dialogp.dismiss();
        dialogp = null;

        //TODO Add results page, then this thing should throw to said page
        Intent intent = new Intent(getBaseContext(), ResultsActivity.class);
        intent.putExtra("Average", avg);
        intent.putExtra("Max", max);
        intent.putExtra("Min", min);
        intent.putExtra("Map_counting_of_individual_words", words);
        intent.putExtra("Sentences_in_Document", totalsentences);
        intent.putExtra("Words_in_Document", totalwords);
        if (isCheck){
            intent.putExtra("POSCount", poscount);
        }

        startActivity(intent);
    }
}

And the error it produces. Any reason why this error doesn't seem to consistently popup? Any help would be appreciated

WindowManager: android.view.WindowLeaked: Activity textsnoop.rddigi.com.textstats.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41f322c0 V.E..... R......D 0,0-665,96} that was originally added here
                                                                             at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
                                                                             at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
                                                                             at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
                                                                             at android.app.Dialog.show(Dialog.java:286)
                                                                             at textsnoop.rddigi.com.textstats.MainActivity$asyncparsefile.onPreExecute(MainActivity.java:135)
                                                                             at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
                                                                             at android.os.AsyncTask.execute(AsyncTask.java:535)
                                                                             at textsnoop.rddigi.com.textstats.MainActivity$2.onClick(MainActivity.java:75)
                                                                             at android.view.View.performClick(View.java:4445)
                                                                             at android.view.View$PerformClick.run(View.java:18446)
                                                                             at android.os.Handler.handleCallback(Handler.java:733)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:136)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5146)
                                                                             at java.lang.reflect.Method.invokeNative(Native Method)
                                                                             at java.lang.reflect.Method.invoke(Method.java:515)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
                                                                             at dalvik.system.NativeStart.main(Native Method)


问:
How to spool query results in oracle
I am trying to print query result. Here is the Oracle SQL Script:

```<code>set linesize 32767;
set pagesize 0;
set newpage 0;
set space 0;
set echo off;
set feedback off;
set verify off;
set heading off;
set sqlprompt '';
set trimspool on;
set headsep off;

spool C:\asd.tmp
SELECT PROCESSNAME FROM ACTIVEPROCESSLIST ORDER BY PROCESSID;
spool off;
</code>```

But the content of "asd.tmp" is that:

SELECT PROCESSNAME FROM ACTIVEPROCESSLIST ORDER BY PROCESSID

It prints just query text, not the result of it. How can I spool query results?

NOTE: I am using "sqldeveloper-4.0.3.16.84-x64" and it runned as administrator. Also setting properties given above may be non-sense. I have tried some combinations of them and executing just spool commands without settings.

Any other solution that I can execute in C++ is proper for me too.

答:
There is an alternative way in that link. I recommend it. It doesn't work as fast as spool solution but it works in my project at least.

There was a problem about the alternative way but the answer in this stackoverflow question works fine. I am using it now.

Title: How to spool query results in oracle

Body:
I am trying to print query result. Here is the Oracle SQL Script:

set linesize 32767;
set pagesize 0;
set newpage 0;
set space 0;
set echo off;
set feedback off;
set verify off;
set heading off;
set sqlprompt '';
set trimspool on;
set headsep off;

spool C:\asd.tmp
SELECT PROCESSNAME FROM ACTIVEPROCESSLIST ORDER BY PROCESSID;
spool off;

But the content of "asd.tmp" is that:

SELECT PROCESSNAME FROM ACTIVEPROCESSLIST ORDER BY PROCESSID

It prints just query text, not the result of it. How can I spool query results?

NOTE: I am using "sqldeveloper-4.0.3.16.84-x64" and it runned as administrator. Also setting properties given above may be non-sense. I have tried some combinations of them and executing just spool commands without settings.

Any other solution that I can execute in C++ is proper for me too.


问:
Compilation errors in simple Java program with Scanner
```<code>import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}
</code>```

<p>I dont know why im getting 2 errors on strings cannot converted to int. </p>

答:
As others have stated you can use </p>

```<code>int first = keyboard.nextInt();
</code>```

<p>but you can also use the next() method along with a parseInt, which can have the handy benefit of showing an error message if you'd like. </p>

```<code>import java.util.*;
public class myClass {
public static void main (String [] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Type your first integer: ");
    String firstStr = keyboard.next();
    System.out.println("Type your seconds integer : ");
    String secondStr = keyboard.next();
    int first = -1; //assuming only positive integers
    int second = -1;
     do{
      try{
      first = Integer.parseInt(firstStr);
      second = Integer.parseInt(secondStr);
      int sum = first + second;
      System.out.println("The sum of your two integers are: " + sum);
     } catch (NumberFormatException exception) {
      System.out.println("Integers only.");
     }
  } while (first=-1 && second=-1);
 }
}
</code>```

Body:
import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}

I dont know why im getting 2 errors on strings cannot converted to int.

Body:
As others have stated you can use

int first = keyboard.nextInt();

but you can also use the next() method along with a parseInt, which can have the handy benefit of showing an error message if you'd like.

import java.util.*;
public class myClass {
public static void main (String [] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Type your first integer: ");
    String firstStr = keyboard.next();
    System.out.println("Type your seconds integer : ");
    String secondStr = keyboard.next();
    int first = -1; //assuming only positive integers
    int second = -1;
     do{
      try{
      first = Integer.parseInt(firstStr);
      second = Integer.parseInt(secondStr);
      int sum = first + second;
      System.out.println("The sum of your two integers are: " + sum);
     } catch (NumberFormatException exception) {
      System.out.println("Integers only.");
     }
  } while (first=-1 && second=-1);
 }
}


问:
Position of a point in a circle
Hello again first part is working like a charm, thank you everyone.

But I've another question...

As I've no interface, is there a way to do the same thing with out not knowing the radius of the circle?

Should have refresh the page CodeMonkey solution is exactly what I was looking for...

Thank you again.

============================

First I'm not a developer, I'm a simple woodworker that left school far too early...

I'm trying to make one of my tool to work with an autonomous robot.
I made them communicate by reading a lot of tutorials.

But I have one problem I cant figure out.

Robot expect position of the tool as (X,Y) but tool's output is (A,B,C)
A is the distance from tool to north
B distance to east
C distance at 120 degree clockwise from east axe

the border is a circle, radius may change, and may or may not be something I know.

I've been on that for 1 month, and I can't find a way to transform those value into the position.

I made a test with 3 nails on a circle I draw on wood, and if I have the distance there is only one position possible, so I guess its possible.
But how?

Also, if someone as an answer I'd love pseudo code not code so I can practice.

If there is a tool to make a drawing I can use to make it clearer can you point it out to me?

Thank you.

hope it helps :

X, Y are coordinate from center, Da,Db, Dc are known.

Trying to make it more clear (sorry its so clear in my head).

X,Y are the coordinate of the point where is the tool (P).
Center is at 0,0

A is the point where vertical line cut the circle from P, with Da distance P to A;

B is the point where horizontal line cuts the circle fom P, with Db distance P to B.

C is the point where the line at 120 clockwise from horizontal cuts the circle from P, with Dc distance P to C.

Output from tool is an array of int (unit mm): A=123, B=114, C=89
Those are the only informations I have

thanks for all the ideas I'll try them at home later,
Hope it works :)

答:
Let's a=Da, b=Db. The we can write a system for points A and B at the circumference:

```<code>(x+b)^2 + y^2 = r^2
(y+a)^2 + x^2 = r^2
</code>```

After transformations we have quadratic equation

```<code>y^2 * (4*b^2+4*a^2) + y * (4*a^3+4*a*b^2) + b^4-4*b^2*r^2+a^4+2*a^2*b^2 = 0
or
AA * y^2  + BB * y + CC = 0
where coefficients are
AA = (4*b^2+4*a^2)
BB = (4*a^3+4*a*b^2)
CC = b^4-4*b^2*r^2+a^4+2*a^2*b^2
</code>```

So calculate AA, BB, CC coefficients, find solutions y1,y2 of quadratic eqiation, then get corresponding x1, x2 values using

```<code> x = (a^2 - b^2 + 2 * a * y) / (2 * b)
</code>```

and choose real solution pair (where coordinate is inside the circle)

Quick checking:

a=1,b=1,r=1 gives coordinates 0,0, as expected (and false 1,-1 outside the circle)

a=3,b=4,r=5 gives coordinates (rough) 0.65, 1.96 at the picture, distances are about 3 and 4.

Delphi code (does not check all possible errors) outputs x: 0.5981  y: 1.9641

```<code>var
  a, b, r, a2, b2: Double;
  aa, bb, cc, dis, y1, y2, x1, x2: Double;
begin
  a := 3;
  b := 4;
  r := 5;
  a2 := a * a;
  b2:= b * b;
  aa := 4 * (b2 + a2);
  bb := 4 * a * (a2 + b2);
  cc := b2 * b2 - 4 * b2 * r * r + a2 * a2 + 2 * a2 * b2;
  dis := bb * bb - 4 * aa * cc;
  if Dis < 0 then begin
    ShowMessage('no solutions');
    Exit;
  end;

  y1 := (- bb - Sqrt(Dis)) / (2 * aa);
  y2 := (- bb + Sqrt(Dis)) / (2 * aa);
  x1 := (a2 - b2 + 2 * a * y1) / (2 * b);
  x2 := (a2 - b2 + 2 * a * y2) / (2 * b);

  if x1 * x1 + y1 * y1 <= r * r then
    Memo1.Lines.Add(Format('x: %6.4f  y: %6.4f', [x1, y1]))
  else
  if x2 * x2 + y2 * y2 <= r * r then
    Memo1.Lines.Add(Format('x: %6.4f  y: %6.4f', [x2, y2]));
</code>```

Title: Position of a point in a circle

Body:
Let's a=Da, b=Db. The we can write a system for points A and B at the circumference:

(x+b)^2 + y^2 = r^2
(y+a)^2 + x^2 = r^2

After transformations we have quadratic equation

y^2 * (4*b^2+4*a^2) + y * (4*a^3+4*a*b^2) + b^4-4*b^2*r^2+a^4+2*a^2*b^2 = 0
or
AA * y^2  + BB * y + CC = 0
where coefficients are
AA = (4*b^2+4*a^2)
BB = (4*a^3+4*a*b^2)
CC = b^4-4*b^2*r^2+a^4+2*a^2*b^2

So calculate AA, BB, CC coefficients, find solutions y1,y2 of quadratic eqiation, then get corresponding x1, x2 values using

 x = (a^2 - b^2 + 2 * a * y) / (2 * b)

and choose real solution pair (where coordinate is inside the circle)

Quick checking:

a=1,b=1,r=1 gives coordinates 0,0, as expected (and false 1,-1 outside the circle)

a=3,b=4,r=5 gives coordinates (rough) 0.65, 1.96 at the picture, distances are about 3 and 4.

Delphi code (does not check all possible errors) outputs x: 0.5981  y: 1.9641

var
  a, b, r, a2, b2: Double;
  aa, bb, cc, dis, y1, y2, x1, x2: Double;
begin
  a := 3;
  b := 4;
  r := 5;
  a2 := a * a;
  b2:= b * b;
  aa := 4 * (b2 + a2);
  bb := 4 * a * (a2 + b2);
  cc := b2 * b2 - 4 * b2 * r * r + a2 * a2 + 2 * a2 * b2;
  dis := bb * bb - 4 * aa * cc;
  if Dis < 0 then begin
    ShowMessage('no solutions');
    Exit;
  end;

  y1 := (- bb - Sqrt(Dis)) / (2 * aa);
  y2 := (- bb + Sqrt(Dis)) / (2 * aa);
  x1 := (a2 - b2 + 2 * a * y1) / (2 * b);
  x2 := (a2 - b2 + 2 * a * y2) / (2 * b);

  if x1 * x1 + y1 * y1 <= r * r then
    Memo1.Lines.Add(Format('x: %6.4f  y: %6.4f', [x1, y1]))
  else
  if x2 * x2 + y2 * y2 <= r * r then
    Memo1.Lines.Add(Format('x: %6.4f  y: %6.4f', [x2, y2]));


问:
Why JDBC connections needs to close in finally block?
```<code>Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
    conn = geting the connection object ( using DriverManager.getConnection() method or using connection pool)
    stmt = conn.createStatement ("select ...");
   // some other logic here
}
catch (SQLException e)
{
    // handling the exceptions
}
finally
{

}
</code>```

Here my question is while closing the connection object in the following cases what are the problems it will come.

Assume if there is no exception occurred, in try block there it self closing the connection object.

```<code>try {
     // same above code
     stmt.close();
     conn.close();
} catch(Exception ex) {
    // handling the exceptions
} finally {

}
</code>```

If some exception is occured so it will goes to catch block, there it self closing the connection object.

```<code>try {
     // same above code

} catch(Exception ex) {
    // handling the exceptions
    stmt.close();
    conn.close();
} finally {

}
</code>```

Closing the connection object in finally block.

```<code>try {
     // same above code

} catch(Exception ex) {
    // handling the exceptions

} finally {
    stmt.close();
    conn.close();
}
</code>```

Difference between closing the connection object using close() method and closing the pooled connection using close().

Note: Please don't say closing the connection object in finally block is good. I know that one. If i keep the close connection in try block, catch block is there any problems please explain.

答:
Answer is that 'We must close the connection after using it.' But the actual question is why we must close the connection after using?.

1.) When we create a connection with a remote database server lets say MySQL Server, It also keeps a connection open for you. Due there is a also a limitation/configuration at database server end for number of connection allowed. If we don't close the connection from our end it will remain open and such way after a short while number of allowed connections will be exceeded at database server end and we will not be able to make further connection with that database.

2.) Auto release connections time setting at database server side.

If we don't close connection from our end and we don't execute any query for certain period of time (As I think default time setting in MySql is 28800 sec. means 8 Hrs. Although we can change it.) it will automatically release the connection from server end.

Important!  What will happen in that situation when your jdbc Connection object is really released at database server end and you think it is still connected because you never disconnected/closed it and you are trying to executing query on that connection using statement. Really critical.

That's why we must always close the connection and execute statement on connected connection object.

Body:
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
    conn = geting the connection object ( using DriverManager.getConnection() method or using connection pool)
    stmt = conn.createStatement ("select ...");
   // some other logic here
}
catch (SQLException e)
{
    // handling the exceptions
}
finally
{

}

Here my question is while closing the connection object in the following cases what are the problems it will come.

Assume if there is no exception occurred, in try block there it self closing the connection object.

try {
     // same above code
     stmt.close();
     conn.close();
} catch(Exception ex) {
    // handling the exceptions
} finally {

}

If some exception is occured so it will goes to catch block, there it self closing the connection object.

try {
     // same above code

} catch(Exception ex) {
    // handling the exceptions
    stmt.close();
    conn.close();
} finally {

}

Closing the connection object in finally block.

try {
     // same above code

} catch(Exception ex) {
    // handling the exceptions

} finally {
    stmt.close();
    conn.close();
}

Difference between closing the connection object using close() method and closing the pooled connection using close().

Note: Please don't say closing the connection object in finally block is good. I know that one. If i keep the close connection in try block, catch block is there any problems please explain.


问:
Getting "targetdir variable must be provided when invoking this installer" message
when i try to install python i'm getting the "targetdir variable must be provided when invoking this installer" whilst attempting to install python 3.5. I have used  tried to Run as admin however, I', still getting this error. </p>

答:
I met this issue also.
I find method to resolve it.
Right click the exe file and choose run as administrator.
Then it can go on installing and to be successful.</p>


问:
how to update with several conditions
In MySQL how can I Update last occurrence of rows which have a column with either 1, 4 or 5.

This is what I want to achieve: That 10% of a certain amount (from user input) be added to the AVAILABLE AMOUNT in the record of the managers whose MEMBERSHIP TYPE column is manager where they are have not make withdraw on that column.

This is my code

```<code>$superManager ="UPDATE transactions SET GETAMOUNT=GETAMOUNT+$tenpercent
WHERE loginID='1' && loginID='4' && loginID='5'
WHERE TRANSACTION STATUS='not-yet-withdrawn'";
</code>```

答:
change your where condition
you can not use two time Where key word</p>

```<code>$superManager ="UPDATE transactions SET GETAMOUNT=GETAMOUNT+$tenpercent
WHERE (loginID='1' OR loginID='4' OR loginID='5')
and STATUS='not-yet-withdrawn'";
</code>```

Title: how to update with several conditions

Body:
In MySQL how can I Update last occurrence of rows which have a column with either 1, 4 or 5.

This is what I want to achieve: That 10% of a certain amount (from user input) be added to the AVAILABLE AMOUNT in the record of the managers whose MEMBERSHIP TYPE column is manager where they are have not make withdraw on that column.

This is my code

$superManager ="UPDATE transactions SET GETAMOUNT=GETAMOUNT+$tenpercent
WHERE loginID='1' && loginID='4' && loginID='5'
WHERE TRANSACTION STATUS='not-yet-withdrawn'";

Body:
change your where condition
you can not use two time Where key word

$superManager ="UPDATE transactions SET GETAMOUNT=GETAMOUNT+$tenpercent
WHERE (loginID='1' OR loginID='4' OR loginID='5')
and STATUS='not-yet-withdrawn'";


问:
Fetch all first child elements from a table
Pretty simple I need to fetch all first type of th elements text :

```<code><html>
<body>

  <table>
  <tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
  </tr>
  <tr>
    <td>Line #1</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Line #2</td>
    <td>SLD</td>
    <td>68</td>
  </tr>
  <tr>
    <td>Line #3</td>
    <td>MDK</td>
    <td>68</td>
  </tr>
</table>

<script type="text/javascript">

console.log(document.querySelectorAll('table tr td:first-of-type'));

</script>

</body>
</html>
</code>```

I want to be able to fetch all table tr td:first-of-type innertext... small tweak needed here.

答:
I think this is what you  meant</p>

```<code>document.querySelectorAll('table tr td:first-child')
</code>```

Body:
Pretty simple I need to fetch all first type of th elements text :

    1
    2
    3

    Line #1
    Smith
    50

    Line #2
    SLD
    68

    Line #3
    MDK
    68

I want to be able to fetch all table tr td:first-of-type innertext... small tweak needed here.

Body:
I think this is what you  meant

document.querySelectorAll('table tr td:first-child')


问:
Authentication for downloading excel file from direct sharepoint link (python)
I'm trying to write some python code to download an excel file, given a direct link. The link is a sharepoint direct download link. I'm getting a 404 unauthorized error when running the code, which I know is because I need to somehow correctly put in the username and password for the sharepoint.

My code snippet looks like this:

```<code>username = 'abc'
password = '123'
url = 'http://example.com/spreadsheet.xls'
r = requests.get(url, auth=HTTPBasicAuth(username, password))
print(r)
# <Response [401]>
</code>```

I haven't even gotten to the downloading portion if I can't get the authentication right. If the code works, I should expect the value of r to be 200, but I get the value 401, which is an unauthorized error. I'm sure that my username and password are both correct.

Any help would be appreciated. Thanks!

答:
The authentication you are using could be wrong.
Replace HTTPBasicAuth with NTLM auth or HttpNegotiateAuth.</p>

```<code>from requests_ntlm import HttpNtlmAuth, HttpNtlmSspiAuth
auth = HttpNtlmSspiAuth()

from requests_negotiate_sspi import HttpNegotiateAuth
auth = HttpNegotiateAuth()
</code>```

Body:
I'm trying to write some python code to download an excel file, given a direct link. The link is a sharepoint direct download link. I'm getting a 404 unauthorized error when running the code, which I know is because I need to somehow correctly put in the username and password for the sharepoint.

My code snippet looks like this:

username = 'abc'
password = '123'
url = 'http://example.com/spreadsheet.xls'
r = requests.get(url, auth=HTTPBasicAuth(username, password))
print(r)
# <Response [401]>

I haven't even gotten to the downloading portion if I can't get the authentication right. If the code works, I should expect the value of r to be 200, but I get the value 401, which is an unauthorized error. I'm sure that my username and password are both correct.

Any help would be appreciated. Thanks!

Body:
The authentication you are using could be wrong.
Replace HTTPBasicAuth with NTLM auth or HttpNegotiateAuth.

from requests_ntlm import HttpNtlmAuth, HttpNtlmSspiAuth
auth = HttpNtlmSspiAuth()

from requests_negotiate_sspi import HttpNegotiateAuth
auth = HttpNegotiateAuth()


问:
Design Patterns for a SuperMarket system
I'm a Software Developer I who is beginning to think like a Software Developer II. I am tasked with a relatively simple Use Case for a coding challenge following as part of an interview:build a Supermarket Pricing System.

Rules and Requirements: Each item at Super Foods is identified by a
  unique four-digit code. Today, pricing schemes at Super Foods use the
  following pricing categories, but beware: prices are constantly
  changing, and the sales department is always creating new incentives
  and deals, such as buy one-get-one free.

EG: Chips and salsa (items #6732 and #4900) cost $4.99 together, but
  they cost $2.49 and $3.49 alone, respectively.

EG2: Buy two toothbrushes $1.99 each, get one free.

EG3: A bottle of wine (item #0923) costs $15.49 and is taxed an
  additional 9.25%

Having read through Design Patterns, this looks like a natural place for some form of Decorator Pattern for totaling the sales of objects. A SQLite database, with schema <ID, ObjectName, Price> will also be useful somehow, though I'm rusty on how we go about making the data access objects in all this.

I'm trying to wrap my mind around this in a full stack MVC mindset, I feel like I might be rusty on something. Is this what the Spring Framework is renowned for? Maybe an even better API for this use case can be recommended?

Thank you for anyone helping me to brainstorm the design of this system out.

答:
Decorator pattern is used to add/modify existing class's behavior without changing class itself. So that acts as a wrapper for existing class, and may be therefore you thought of it. Point is your don't have system that you're extending, you are building it from scratch!

S/w design is tough and cannot be finalized in one go. Also I'm sure your prospect employer is more interested in how you design it, than what tech stack you use. So I'll not comment on that. It's your call.

Per your requirements, these are my initial thoughts. There is room for improvement (Yes!) but at the least this should work for the scope of your assignment. This is C#. That shouldn't stop you from understanding it though.

```<code>namespace Entities {
    public class StoreItem
    {
        // Code
        // Name
        // Cost
        // Tax -> for specific items
        // MfgDate
        // ExpDate
    }

    public class StoreDeal
    {
        // Code
        // Name
        // Cost
        // Validity
        // Items (type: IList<StoreItem>) -> items participating in a deal
    }
}

namespace Domain {
    public class Cart
    {
        // Items (type: IList<CartItem>)
        // TotalAmount
        // TotalDiscount
        // FinalAmount
    }

    public class CartItem
    {
        public CartItem(string code) {
            Code = code; // assume "6732" -> Chips
        }

        public CartItem(StoreItem item) {
            MapStoreItem(item);
        }

        // declare props: Code, Name, Quantity, Cost

        public void Prepare() {
            if(Quantity > 0) {
                // Invalid operation alert and return
                // This is one time call per item type
            }
            // Sample. Retrieve item from database.
            var item = new StoreItem { Code = code, Name = "Chips", Cost = 2.49, Tax = 0 /* etc */ }
            MapStoreItem(item);
            Quantity = 1;
        }

        public void UpdateQuantity(int quantity) {
            Quantity = quantity;
            Cost = Cost * Quantity;
        }

        private void MapStoreItem(StoreItem item) {
            Code = item.Code;
            Name = item.Name;
            Cost = CalculateCost(item.Cost, item.Tax);
        }

        private static double CalculateCost(double cost, double tax) {
            // If tax > 0, apply it to cost
            // else return cost as is
        }
    }
}

public class DealService
{
    public StoreDeal GetDeal(string itemCode) {
        // Assume item to be Chips. Retrieve current deal that involve Chips.
        // Sample data. You should delegate this stuff to data access layer.
        return
            new StoreDeal {
                Code = "CS4.99",
                Name = "Chips and salsa @ $4.99",
                Cost = 4.99,
                Items = new List<StoreItem> {
                    new StoreItem { Code = "6732", Name = "Chips" },
                    new StoreItem { Code = "4900", Name = "Salsa" }
                }
            }
    }
}

public class CartService
{
    private Cart cart;
    private DealService dealService;

    // ctor - inject dependencies
    public CartService(Cart cart, DealService dealService) {
        this.cart = cart;
        this.dealService = dealService;
    }

    public void AddItem(CartItem item) {
        var found = cart.Items.Find(i => i.Code == item.Code);
        if (found != null) { // Update quantity
            found.UpdateQuantity(found.Quantity + 1);
        }
        else { // Add new item
            item.Prepare();
            cart.Items.Add(item);
        }
    }

    public void RemoveItem(string code) {
        var found = cart.Items.Find(i => i.Code)
        if (found != null) {
            cart.Items.Remove(found);
        }
    }

    public void CalculateTotal() {
        // Used for checking which items in cart have got deal applied on.
        // We don't want "CS4.99" deal applied to both Chips and Salsa, for ex. Only for one of them.
        // So this collection simply holds deal codes already applied.
        var dealsApplied = new List<string>();

        foreach(var item in cart.Items) {
            // Check deal
            StoreDeal deal = dealService.GetDeal(item.Code);
            // Apply the logic for TotalAmount, TotalDiscount, FinalAmount
        }
    }
}
</code>```

Note that, if you were to design such system for real, then there would be much more classes than above. For example, in real case "Chips" is not an item, it's a type of item and hence cannot have Code. However, "Lays Potato Chips" would be an individual item of type "Chips" with it's own Code. Also StoreItem would become abstract entity which is derived by types like EdibleItem, PersonalCareItem, HealthCareItem, CosmeticItem and anything that exists in real store where EdibleItem will specifically have Nutrition info which does not apply to other in this list.

Lastly, I just wrote this (incomplete) code, didn't test it! Code is incomplete where you see comments, and did this purposely because I don't want you to cheat interview blindly. :)

Body:
Decorator pattern is used to add/modify existing class's behavior without changing class itself. So that acts as a wrapper for existing class, and may be therefore you thought of it. Point is your don't have system that you're extending, you are building it from scratch!

S/w design is tough and cannot be finalized in one go. Also I'm sure your prospect employer is more interested in how you design it, than what tech stack you use. So I'll not comment on that. It's your call.

Per your requirements, these are my initial thoughts. There is room for improvement (Yes!) but at the least this should work for the scope of your assignment. This is C#. That shouldn't stop you from understanding it though.

namespace Entities {
    public class StoreItem
    {
        // Code
        // Name
        // Cost
        // Tax -> for specific items
        // MfgDate
        // ExpDate
    }

    public class StoreDeal
    {
        // Code
        // Name
        // Cost
        // Validity
        // Items (type: IList<StoreItem>) -> items participating in a deal
    }
}

namespace Domain {
    public class Cart
    {
        // Items (type: IList<CartItem>)
        // TotalAmount
        // TotalDiscount
        // FinalAmount
    }

    public class CartItem
    {
        public CartItem(string code) {
            Code = code; // assume "6732" -> Chips
        }

        public CartItem(StoreItem item) {
            MapStoreItem(item);
        }

        // declare props: Code, Name, Quantity, Cost

        public void Prepare() {
            if(Quantity > 0) {
                // Invalid operation alert and return
                // This is one time call per item type
            }
            // Sample. Retrieve item from database.
            var item = new StoreItem { Code = code, Name = "Chips", Cost = 2.49, Tax = 0 /* etc */ }
            MapStoreItem(item);
            Quantity = 1;
        }

        public void UpdateQuantity(int quantity) {
            Quantity = quantity;
            Cost = Cost * Quantity;
        }

        private void MapStoreItem(StoreItem item) {
            Code = item.Code;
            Name = item.Name;
            Cost = CalculateCost(item.Cost, item.Tax);
        }

        private static double CalculateCost(double cost, double tax) {
            // If tax > 0, apply it to cost
            // else return cost as is
        }
    }
}

public class DealService
{
    public StoreDeal GetDeal(string itemCode) {
        // Assume item to be Chips. Retrieve current deal that involve Chips.
        // Sample data. You should delegate this stuff to data access layer.
        return
            new StoreDeal {
                Code = "CS4.99",
                Name = "Chips and salsa @ $4.99",
                Cost = 4.99,
                Items = new List<StoreItem> {
                    new StoreItem { Code = "6732", Name = "Chips" },
                    new StoreItem { Code = "4900", Name = "Salsa" }
                }
            }
    }
}

public class CartService
{
    private Cart cart;
    private DealService dealService;

    // ctor - inject dependencies
    public CartService(Cart cart, DealService dealService) {
        this.cart = cart;
        this.dealService = dealService;
    }

    public void AddItem(CartItem item) {
        var found = cart.Items.Find(i => i.Code == item.Code);
        if (found != null) { // Update quantity
            found.UpdateQuantity(found.Quantity + 1);
        }
        else { // Add new item
            item.Prepare();
            cart.Items.Add(item);
        }
    }

    public void RemoveItem(string code) {
        var found = cart.Items.Find(i => i.Code)
        if (found != null) {
            cart.Items.Remove(found);
        }
    }

    public void CalculateTotal() {
        // Used for checking which items in cart have got deal applied on.
        // We don't want "CS4.99" deal applied to both Chips and Salsa, for ex. Only for one of them.
        // So this collection simply holds deal codes already applied.
        var dealsApplied = new List<string>();

        foreach(var item in cart.Items) {
            // Check deal
            StoreDeal deal = dealService.GetDeal(item.Code);
            // Apply the logic for TotalAmount, TotalDiscount, FinalAmount
        }
    }
}

Note that, if you were to design such system for real, then there would be much more classes than above. For example, in real case "Chips" is not an item, it's a type of item and hence cannot have Code. However, "Lays Potato Chips" would be an individual item of type "Chips" with it's own Code. Also StoreItem would become abstract entity which is derived by types like EdibleItem, PersonalCareItem, HealthCareItem, CosmeticItem and anything that exists in real store where EdibleItem will specifically have Nutrition info which does not apply to other in this list.

Lastly, I just wrote this (incomplete) code, didn't test it! Code is incomplete where you see comments, and did this purposely because I don't want you to cheat interview blindly. :)


问:
i want to add two row's value in single row
I want to add two city_name's value (HYD + HYDTC) in HYD

```
CITY_NAME    VALUE
  CCU         10
  CHI         12
  DEL         15
  HYD         20
  HYDTC       30
  MUM         10
```

I want to output in this way:-

```
CITY_NAME    VALUE
  CCU         10
  CHI         12
  DEL         15
  HYD         50
  MUM         10
```

答:
You can use a CASE expression.

Query

```<code>select t.city_name_alt as city_name, sum(t.value) as value from(
    select city_name,
    case city_name when 'HYDTC' then 'HYD' else city_name end as city_name_alt,
    value
    from your_table_name
)t
group by t.city_name_alt;
</code>```

Body:
I want to add two city_name's value (HYD + HYDTC) in HYD

CITY_NAME    VALUE
  CCU         10
  CHI         12
  DEL         15
  HYD         20
  HYDTC       30
  MUM         10

I want to output in this way:-

CITY_NAME    VALUE
  CCU         10
  CHI         12
  DEL         15
  HYD         50
  MUM         10

Body:
You can use a CASE expression.

Query

select t.city_name_alt as city_name, sum(t.value) as value from(
    select city_name,
    case city_name when 'HYDTC' then 'HYD' else city_name end as city_name_alt,
    value
    from your_table_name
)t
group by t.city_name_alt;


问:
Remove comments from text file in Java
Is there any easy way to remove the comments from the text file in Java.

```<code>now:

:-  /* #pos=1,513 */ author(A, UniqueVar1)

after:

author(A, UniqueVar1)
</code>```

I used BufferedReader and readline to read and split the lines.

Title: Remove comments from text file in Java

Body:
Is there any easy way to remove the comments from the text file in Java.

now:

:-  /* #pos=1,513 */ author(A, UniqueVar1)

after:

author(A, UniqueVar1)

I used BufferedReader and readline to read and split the lines.

Body:
try this:

line.replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)|(?::-)","");


问:
How to use BCRYPT with password_hash() in PHP
Now with password_hash() in PHP >=5.6, do we need to also use BCRYPT to make the object/password more secured?

If yes, then could any one please describe how to store a password in registration page using password_hash() AND BCRYPT, and then how to retrieve information to login user on login page?

Sorry if anyone is offended by a beginner's limited knowledge. I am confused and didn't quite get the answer.

UPDATE:

I got the idea now, there is no need to user BCRYPT/salt/pepper with password_hash() now as PHP creates its own random salt during runtime.
The easiest step is to simply hash password using password_hash($passwordVariable) and for verification simply use password_verify($passwordEntered, $hashedPassword_fromDB).
Thanks everyone.

答:
There is no need to user BCRYPT/salt/pepper with password_hash() now as PHP creates its own random salt during runtime.

The easiest step is to simply hash password using password_hash($passwordVariable) and for verification simply use password_verify($passwordEntered, $hashedPassword_fromDB)


问:
What is "this" in javascript when calling a method on a calculated object?
I know this is probably the second most asked-about thing in javascript, right after floating point arithmetic.

I generally know how this works, and how it's affected by arrow functions, .call(), .apply(), and .bind().  I thought I understood everything about it.  But I do not.

In a web browser, document.createElement("div").classList.add("c") yields undefined as expected.  However, this expression surprisingly is an error.

```<code>(true && document.createElement("div").classList.add)("c")
</code>```

I expected it to be the same, but it's

```<code>Uncaught TypeError: Illegal invocation
    at <anonymous>:1:54
</code>```

答:
What you are tryng to do doesnt make sense.
Maybe you mean

```<code>var added document.createElement("div").classList.add("c")
If (added){...….}
</code>```

In your example you have a ) too much after add

Body:
I know this is probably the second most asked-about thing in javascript, right after floating point arithmetic.

I generally know how this works, and how it's affected by arrow functions, .call(), .apply(), and .bind().  I thought I understood everything about it.  But I do not.

In a web browser, document.createElement("div").classList.add("c") yields undefined as expected.  However, this expression surprisingly is an error.

(true && document.createElement("div").classList.add)("c")

I expected it to be the same, but it's

Uncaught TypeError: Illegal invocation
    at <anonymous>:1:54

Body:
What you are tryng to do doesnt make sense.
Maybe you mean

var added document.createElement("div").classList.add("c")
If (added){...….}

In your example you have a ) too much after add


问:
Juypter notebook - connect to the same kernel session from a command line ipython?
Suppose I've a Jupyter notebook loaded in a browser. Is that possible to somehow run a command line ipython session which connect to the same kernel insance as the one used by the notebook (i.e they can see the same set of variables)? Thanks.</p>

答:
Yes! After starting/loading an IPython notebook, open up a terminal and connect a command line ipython session using the --existing parameter:

```<code>jupyter console --existing
</code>```

By default, it will connect to the latest started IPython kernel. To select a different kernel to connect to, look in the log of the Jupyter notebook for lines like these:

```<code>[I 09:47:54.462 NotebookApp] Kernel started: 06c9ffae-ae9f-4c22-93c0-4eacf23672b1
</code>```

To connect to this kernel, do:

```<code>jupyter console --existing 06c9ffae-ae9f-4c22-93c0-4eacf23672b1
</code>```

Body:
Yes! After starting/loading an IPython notebook, open up a terminal and connect a command line ipython session using the --existing parameter:

jupyter console --existing

By default, it will connect to the latest started IPython kernel. To select a different kernel to connect to, look in the log of the Jupyter notebook for lines like these:

[I 09:47:54.462 NotebookApp] Kernel started: 06c9ffae-ae9f-4c22-93c0-4eacf23672b1

To connect to this kernel, do:

jupyter console --existing 06c9ffae-ae9f-4c22-93c0-4eacf23672b1