问:
Check Empty and zero on PHP
I want to add subtract and other function from user data in PHP. At first, I want to check the field is empty or not.When I check empty using empty() function and I submit zero then it shows required that means it is empty.How can I input zero and it add or subtract with my second value?Thank you.My code is here

```<code><html>
<head>

</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
    $num1=$_POST['num1'];
    $num2=$_POST['num2'];
    if (empty($num1 AND $num2)){
        echo "Required";
    }else{
    if ($_POST['submit']=='Add'){
        $num1=$_POST['num1'];
        $num2=$_POST['num2'];
        $add=$num1+$num2;
        echo $add;
    }
    elseif ($_POST['submit']=='Subtract'){
        $subtract=$num1-$num2;
        echo $subtract;
    }
    elseif ($_POST['submit']=='Multiplication'){
        $multiply=$num1*$num2;
        echo $multiply;
    }
    elseif ($_POST['submit']=='Division'){
        $division=$num1/$num2;
        echo $division;
    }

    }
}
?>

<form action="" method="post">
    <input type="number" name="num1">
    <input type="number" name="num2">
    <input type="submit" name="submit" value="Add">
    <input type="submit" name="submit" value="Subtract">
    <input type="submit" name="submit" value="Multiplication">
    <input type="submit" name="submit" value="Division">
</form>

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

答:
Let's use v Sugumar's answer and make it easier:

```<code>function emp($value){
  if (isset($value) && $value>=0 )
     return true;//has value
  else
     return false;//empty
}
</code>```

Now you just have to use it:

```<code>if(emp($num1) and emp($num2)){
    //You typed a value, do something
}
</code>```

Title: Check Empty and zero on PHP

Body:
I want to add subtract and other function from user data in PHP. At first, I want to check the field is empty or not.When I check empty using empty() function and I submit zero then it shows required that means it is empty.How can I input zero and it add or subtract with my second value?Thank you.My code is here

<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
    $num1=$_POST['num1'];
    $num2=$_POST['num2'];
    if (empty($num1 AND $num2)){
        echo "Required";
    }else{
    if ($_POST['submit']=='Add'){
        $num1=$_POST['num1'];
        $num2=$_POST['num2'];
        $add=$num1+$num2;
        echo $add;
    }
    elseif ($_POST['submit']=='Subtract'){
        $subtract=$num1-$num2;
        echo $subtract;
    }
    elseif ($_POST['submit']=='Multiplication'){
        $multiply=$num1*$num2;
        echo $multiply;
    }
    elseif ($_POST['submit']=='Division'){
        $division=$num1/$num2;
        echo $division;
    }

    }
}
?>

<form action="" method="post">
    <input type="number" name="num1">
    <input type="number" name="num2">
    <input type="submit" name="submit" value="Add">
    <input type="submit" name="submit" value="Subtract">
    <input type="submit" name="submit" value="Multiplication">
    <input type="submit" name="submit" value="Division">
</form>

</html

Body:
Let's use v Sugumar's answer and make it easier:

function emp($value){
  if (isset($value) && $value>=0 )
     return true;//has value
  else
     return false;//empty
}

Now you just have to use it:

if(emp($num1) and emp($num2)){
    //You typed a value, do something
}


来源: stackexchange

问:
awk Getting ALL line but last field with the delimiters
I have to make a one-liner that renames all files in the current directory
that end in ".hola" to ".txt".

For example:

sample.hola and name.hi.hola will be renamed to sample.txt and name.hi.txt respectively

I was thinking about something like:

ls -1 *.hola | awk '{NF="";print "$0.hola $0.txt"}' (*)

And then passing the stdin to xargs mv -T with a |

But the output of (*) for the example would be sample and name hi.

How do I get the output name.hi for name.hi.hola using awk?

答:
Why would you want to involve awk in this?

```<code>$ for f in *.hola; do echo mv "$f" "${f%hola}txt"; done
mv name.hi.hola name.hi.txt
mv sample.hola sample.txt
</code>```

Remove the echo when you're happy with the output.

ContentLicense: CC BY-SA 3.0

Body:
Why would you want to involve awk in this?

$ for f in *.hola; do echo mv "$f" "${f%hola}txt"; done
mv name.hi.hola name.hi.txt
mv sample.hola sample.txt

Remove the echo when you're happy with the output.


问:
What is the difference between java.util.concurrent.SynchronousQueue and java.util.concurrent.Exchanger?
I think SynchronousQueue can contain only one object for exchange. </p>

答:
As specified by the Javadoc:

An Exchanger may be viewed as a bidirectional form of a SynchronousQueue. Exchangers may be useful in applications such as genetic algorithms and pipeline designs.


问:
Regex implementation with event driven matches?
This may sound a little odd, but it would be extremely useful to me. Are there any regex implementations (any language but preferably java, javascript, c, c++) that use an event based model for matches?

I would like to be able to register a bunch of different regular expressions I am looking for in a string via an event based model, feed the string though the regex engine, and just have the events fired off correctly. Does anything like this exist?

I realize this is bordering on the territory of a heavy duty lexer/parser, but I would prefer to stay away from that if at all possible, as my search expressions would need to be dynamic (completely).

Thanks

答:
It's really not something that's too hard to put together yourself if you can't find any existing library.

Something like this:

```<code>public class RegexNotifier {
   private final Map<Pattern, List<RegexListener>> listeners = new HashMap<Pattern, List<RegexListener>>();

   public synchronized void register(Pattern pattern, RegexListener listener) {
      List<RegexListener> list = listeners.get(pattern);
      if (list == null) {
         list = new ArrayList<RegexListener>();
         listeners.put(pattern, list);
      }
      list.add(listener);
   }

   public void process(String input) {
      for (Entry<Pattern, List<RegexListener>> entry : listeners.entrySet()) {
         if (entry.getKey().matcher(input).matches()) {
            for (RegexListener listener : entry.getValue()) {
               listener.stringMatched(input, entry.getKey());
            }
         }
      }
   }
}

interface RegexListener {
   public void stringMatched(String matched, Pattern pattern);
}
</code>```

The only shortcoming I see with this is that Pattern doesn't implement hashCode() and equals(), meaning it will be less than optimal if equal patterns using different instances are used.  But that usually doesn't happen because the factory method Pattern.compile() is good about caching patterns.

ContentLicense: CC BY-SA 2.5

Body:
It's really not something that's too hard to put together yourself if you can't find any existing library.

Something like this:

public class RegexNotifier {
   private final Map<Pattern, List<RegexListener>> listeners = new HashMap<Pattern, List<RegexListener>>();

   public synchronized void register(Pattern pattern, RegexListener listener) {
      List<RegexListener> list = listeners.get(pattern);
      if (list == null) {
         list = new ArrayList<RegexListener>();
         listeners.put(pattern, list);
      }
      list.add(listener);
   }

   public void process(String input) {
      for (Entry<Pattern, List<RegexListener>> entry : listeners.entrySet()) {
         if (entry.getKey().matcher(input).matches()) {
            for (RegexListener listener : entry.getValue()) {
               listener.stringMatched(input, entry.getKey());
            }
         }
      }
   }
}

interface RegexListener {
   public void stringMatched(String matched, Pattern pattern);
}

The only shortcoming I see with this is that Pattern doesn't implement hashCode() and equals(), meaning it will be less than optimal if equal patterns using different instances are used.  But that usually doesn't happen because the factory method Pattern.compile() is good about caching patterns.


问:
Python Random Number File Writer
This is what I have so far. It worked until I added the functions. I need to have two functions in the code and I don't know how to make this work correctly and have tried several different ways. The code needs to write X amount of random numbers to a text file.</p>

```<code>import random

random_numbers = open('ran_numbers.txt', 'w')

def main():

    getRandom()
    writeFunction()

def getRandom():
    qty_numbers = int(input('How many random numbers should be written to the file? '))

    for count in range (qty_numbers):
        number = random.randint(1,500)

def writeFunction():
    random_numbers.write(str(number)+ '\n')
    random_numbers.close()
    print('Your list of random numbers have been written to the file named')
    print('ran_numbers.txt')

main()
</code>```

答:
I think you just need to have a list of numbers that are generatred and pass them to the file_writer. Here is the change I made to your code:</p>

```<code>import random
def main():
    random_result = getRandom()
    writeFunction(random_result)
def getRandom():
    qty_numbers = int(input('How many random numbers should be written to the file? '))
    res = []
    for count in range (qty_numbers):
        res.append(random.randint(1,500))
    return res
def writeFunction(random_numbers_list):
    random_numbers = open('ran_numbers.txt', 'w')
    for number in random_numbers_list:
        random_numbers.write(str(number)+ '\n')
    random_numbers.close()
    print('Your list of random numbers have been written to the file named')
    print('ran_numbers.txt')
main()
</code>```

Title: Python Random Number File Writer

Body:
This is what I have so far. It worked until I added the functions. I need to have two functions in the code and I don't know how to make this work correctly and have tried several different ways. The code needs to write X amount of random numbers to a text file.

import random

random_numbers = open('ran_numbers.txt', 'w')

def main():

    getRandom()
    writeFunction()

def getRandom():
    qty_numbers = int(input('How many random numbers should be written to the file? '))

    for count in range (qty_numbers):
        number = random.randint(1,500)

def writeFunction():
    random_numbers.write(str(number)+ '\n')
    random_numbers.close()
    print('Your list of random numbers have been written to the file named')
    print('ran_numbers.txt')

main()

Body:
I think you just need to have a list of numbers that are generatred and pass them to the file_writer. Here is the change I made to your code:

import random
def main():
    random_result = getRandom()
    writeFunction(random_result)
def getRandom():
    qty_numbers = int(input('How many random numbers should be written to the file? '))
    res = []
    for count in range (qty_numbers):
        res.append(random.randint(1,500))
    return res
def writeFunction(random_numbers_list):
    random_numbers = open('ran_numbers.txt', 'w')
    for number in random_numbers_list:
        random_numbers.write(str(number)+ '\n')
    random_numbers.close()
    print('Your list of random numbers have been written to the file named')
    print('ran_numbers.txt')
main()


问:
windows.Environ() strings [0] and [1]
I'm confused by the first 2 strings returned by "windows.Environ()" on a Windows pro 7 system (go version go1.8 windows/amd64).  env[0] apparently has a key of "=::"; env[1] has a key "=C:".  Can anyone point me to where this is documented?  Thx in advance.</p>

```<code>str_EnvStrs := windows.Environ()
//
//    str_EnvStrs[0] == '=::=::\'
fmt.Printf("str_EnvStrs[0] == '%v'\n",str_EnvStrs[0])
//
//    str_EnvStrs[1] == '=C:=C:\Users\(WINLOGIN)\Documents\Source\go\src
//                       \github.com\(GITLOGIN)\maps_arrays_slices'
fmt.Printf("str_EnvStrs[1] == '%v'\n",str_EnvStrs[1])
</code>```

答:
The relevant Go code is:

```<code>func Environ() []string {
    s, e := GetEnvironmentStrings()
    if e != nil {
        return nil
    }
    defer FreeEnvironmentStrings(s)
    r := make([]string, 0, 50) // Empty with room to grow.
    for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(s)); true; i++ {
        if p[i] == 0 {
            // empty string marks the end
            if i <= from {
                break
            }
            r = append(r, string(utf16.Decode(p[from:i])))
            from = i + 1
        }
    }
    return r
}
</code>```

The code is using the Windows GetEnvironmentStrings function. The values come from Windows. See the Microsoft Windows documentation of environment variables. Also, see What are these strange =C: environment variables?

Title: windows.Environ() strings [0] and [1]

Body:
I'm confused by the first 2 strings returned by "windows.Environ()" on a Windows pro 7 system (go version go1.8 windows/amd64).  env[0] apparently has a key of "=::"; env[1] has a key "=C:".  Can anyone point me to where this is documented?  Thx in advance.

str_EnvStrs := windows.Environ()
//
//    str_EnvStrs[0] == '=::=::\'
fmt.Printf("str_EnvStrs[0] == '%v'\n",str_EnvStrs[0])
//
//    str_EnvStrs[1] == '=C:=C:\Users\(WINLOGIN)\Documents\Source\go\src
//                       \github.com\(GITLOGIN)\maps_arrays_slices'
fmt.Printf("str_EnvStrs[1] == '%v'\n",str_EnvStrs[1])

Body:
The relevant Go code is:

func Environ() []string {
    s, e := GetEnvironmentStrings()
    if e != nil {
        return nil
    }
    defer FreeEnvironmentStrings(s)
    r := make([]string, 0, 50) // Empty with room to grow.
    for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(s)); true; i++ {
        if p[i] == 0 {
            // empty string marks the end
            if i <= from {
                break
            }
            r = append(r, string(utf16.Decode(p[from:i])))
            from = i + 1
        }
    }
    return r
}

The code is using the Windows GetEnvironmentStrings function. The values come from Windows. See the Microsoft Windows documentation of environment variables. Also, see What are these strange =C: environment variables?


问:
Android application: How do I display users based on what they answer similarly?
I would like for a user to see other users who answered a question the same as them. The questions are not in a quiz or test format. The questions are those to get a sense of one’s personality to see who is the same as them. So far, the user logs in and is prompted to answer the questions and once they are done, they are taken to a screen where I would like to show who also answer the questions the same as them.

I have a database (MySQL) where I have a "users" table. I have the "users" table wrapped into a REST Service. I would like to know if I need to have another table in my database that would contain the questions and answers and wrap that into my REST Service as well or if it is not necessary to have that.

Thank you in advance!!!!

答:
Of course you need to store your answers in a table in your database. Otherwise, there would be no easy way to find out, what other users have answered.

Let's say you have the following structure of your MySQL database:

```<code>create table users(
    id int not null auto_increment primary key,
    ...
);

create table questions(
    id int not null auto_increment primary key,
    ...
);

create table answers(
    user_id int not null references users(id),
    question_id int not null references questions(id),
    `option` int not null,
    primary key (user_id, question_id)
);
</code>```

(Other tables and columns may be required)

In SQL a query to find similar users to a user with the id ID_of_your_user would look somewhat like this:

```<code>select
    u.id as similar_user_id,
    count(*) as same_answer_count
from users u
    join answers a on u.id = a.user_id
    join answers a2 on a.question_id = a2.question_id
where a2.user_id = ID_of_your_user and
    a2.`option` = a.`option` and
    u.id != a2.user_id
group by u.id
having same_answer_count >= threshold
order by same_answer_count desc
</code>```

Body:
Of course you need to store your answers in a table in your database. Otherwise, there would be no easy way to find out, what other users have answered.

Let's say you have the following structure of your MySQL database:

create table users(
    id int not null auto_increment primary key,
    ...
);

create table questions(
    id int not null auto_increment primary key,
    ...
);

create table answers(
    user_id int not null references users(id),
    question_id int not null references questions(id),
    `option` int not null,
    primary key (user_id, question_id)
);

(Other tables and columns may be required)

In SQL a query to find similar users to a user with the id ID_of_your_user would look somewhat like this:

select
    u.id as similar_user_id,
    count(*) as same_answer_count
from users u
    join answers a on u.id = a.user_id
    join answers a2 on a.question_id = a2.question_id
where a2.user_id = ID_of_your_user and
    a2.`option` = a.`option` and
    u.id != a2.user_id
group by u.id
having same_answer_count >= threshold
order by same_answer_count desc


答:
If you MUST have two functions then this would be a better solution. Putting the random numbers in a list and then passing it onto the writeFunction function.</p>

```<code>import random

random_numbers = open('ran_numbers.txt', 'w')

def main():

    writeFunction(getRandom())

def getRandom():
    qty_numbers = int(input('How many random numbers should be written to     the file? '))

    nums = []
    for count in range (qty_numbers):
        nums.append(random.randint(1,500))
    return nums

def writeFunction(a_list):
    random_nums = '\n'.join([str(x) for x in a_list])
    random_numbers.write(random_nums)
    random_numbers.close()
    print('Your list of random numbers have been written to the file named')
    print('ran_numbers.txt')

main()
</code>```

Title: Python Random Number File Writer

Body:
If you MUST have two functions then this would be a better solution. Putting the random numbers in a list and then passing it onto the writeFunction function.

import random

random_numbers = open('ran_numbers.txt', 'w')

def main():

    writeFunction(getRandom())

def getRandom():
    qty_numbers = int(input('How many random numbers should be written to     the file? '))

    nums = []
    for count in range (qty_numbers):
        nums.append(random.randint(1,500))
    return nums

def writeFunction(a_list):
    random_nums = '\n'.join([str(x) for x in a_list])
    random_numbers.write(random_nums)
    random_numbers.close()
    print('Your list of random numbers have been written to the file named')
    print('ran_numbers.txt')

main()


问:
How to save variable using await function and use callback when error occurs?
well I'm immigrating my code to ES7, syntaxes like arrow function and async/await. The problem is I don't get how to use call back when If I try to save variable and callback when error occurs at the same time using async/await.

Here's the code. I want to save result from request to redditJSON variable using await with rp but I want to add callback for error handling too. but I have no idea how to implement this.

rp is request-promise npm module.

```<code>let redditJSON = await rp(optForReddit)
</code>```

EDIT 1

```<code>let redditJSON;
try { redditJSON = await rp(optForReddit) }
catch(err) { console.error(err) }
</code>```

答:
Callbacks are dead in ES7 and should no longer be used. To perform error handling with the new async await pattern you should wrap the call in a try/catch block.

It should look something like this:

```<code>try {
   let redditJSON = await rp(optForReddit);
   // do some cool stuff
} catch(err) {
    console.log(err);
    // The contents of err should be what is thrown in the rp function
}
</code>```

If you are using a library such as request-promise to perform this request the error should be thrown automatically and thrown up to this try/catch block.

However, remember you can always throw errors yourself as well, like so:

```<code>async myMethod() {
    throw new Error('something went wrong');
}
</code>```

Then catch it like this:

```<code>try {
    await myMethod()
} catch (err) {
    // err = 'Something went wrong'
}
</code>```

Body:
well I'm immigrating my code to ES7, syntaxes like arrow function and async/await. The problem is I don't get how to use call back when If I try to save variable and callback when error occurs at the same time using async/await.

Here's the code. I want to save result from request to redditJSON variable using await with rp but I want to add callback for error handling too. but I have no idea how to implement this.

rp is request-promise npm module.

let redditJSON = await rp(optForReddit)

EDIT 1

let redditJSON;
try { redditJSON = await rp(optForReddit) }
catch(err) { console.error(err) }

Body:
Callbacks are dead in ES7 and should no longer be used. To perform error handling with the new async await pattern you should wrap the call in a try/catch block.

It should look something like this:

try {
   let redditJSON = await rp(optForReddit);
   // do some cool stuff
} catch(err) {
    console.log(err);
    // The contents of err should be what is thrown in the rp function
}

If you are using a library such as request-promise to perform this request the error should be thrown automatically and thrown up to this try/catch block.

However, remember you can always throw errors yourself as well, like so:

async myMethod() {
    throw new Error('something went wrong');
}

Then catch it like this:

try {
    await myMethod()
} catch (err) {
    // err = 'Something went wrong'
}


问:
Spring context files organization and best practices
We have started using Spring framework in my project. After becoming acquainted with the basic features (IoC) we have started using spring aop and spring security as well.

The problem is that we now have more than 8 different context files and I feel we didn't give enough thought for the organization of those files and their roles. New files were introduced as the project evolved.
We have different context files for: metadata, aop, authorization, services, web resources (it's a RESTful application). So when a developer wants to add a new bean it's not always clear in which file he should add it. We need methodology.

The question:

Is there a best practice for spring files organization?

Should the context files encapsulate layers (DAL , Business Logic, Web) or use cases ? or Flows?

答:
Start with applicationContext.xml and separate when there's a lot of beans which have something in common.

To give you some idea of a possible setup, in the application I'm currently working on, here's what I have in server:

applicationContext.xml

securityContext.xml

schedulingContext.xml

dataSourcecontext.xml

spring-ws-servlet.xml (Spring Web Services related beans)

For GUI clients, since this project has several, there is one folder with shared context files, and on top of that, each client has its own context folder. Shared context files:

sharedMainApplicationContext.xml

sharedGuiContext.xml

sharedSecurityContext.xml

App-specific files:

mainApplicationContext.xml and

guiContext.xml and

commandsContext.xml (menu structure)

sharedBusinessLayerContext.xml (beans for connecting to server)

OwnerDisplayName: LiorH

OwnerDisplayName: Domchi


问:
How to find a functions address to hook/detour in an EXE file?
I drove against a wall again and need your help with some low-level stuff. I already succeeded in hooking exported DLL-Functions (with this code btw.) by injecting them into my target process (e.g. I can easily detour MessageBoxW from user32.dll). Unfortunately I aim for a different scenario: I have to detour a function defined inside the executable I'm injecting my code into. The application is Open-Source so I know everything about the function I'd need for hooking it, but the binary is signed with a certificate so I can not compile my own version. Is it possible to fetch the functions' address at runtime or detour it with another technique? The target is a "normal" 32bit Windows binary btw. nothing special I thought ;)

Yours,
Nefarius

EDIT: maybe due to my lame English I was not detailed enough, so here a little sample code:

```<code>int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{
    foo();
}

BOOL foo(char* someData)
{
    return printf("%s", someData);
}
</code>```

Now I want to detour the function foo() which does not exist in a dynamic library. This is my problem. I don't know how and I'm not sure if this works like I think it does.

EDIT: Now I know it is possible, so the important question changed to: how? How do I get the information I need; the functions address?

答:
Sure, just use something like Ollydbg to set a breakpoint, and edit the assembly after the executable has loaded (and finished checking its certificate). To do it permanently is a bit more challenging, but depending on how sophisticated the certificate check is, you might just be able to bypass that bit of code by replacing it with a NOP (no operation).

EDIT: If you're running 64-bit Windows, you might have better luck with Microsoft's own Debugging Tools. I've never used them, so I have no idea how they compare to Ollydbg.

Body:
I drove against a wall again and need your help with some low-level stuff. I already succeeded in hooking exported DLL-Functions (with this code btw.) by injecting them into my target process (e.g. I can easily detour MessageBoxW from user32.dll). Unfortunately I aim for a different scenario: I have to detour a function defined inside the executable I'm injecting my code into. The application is Open-Source so I know everything about the function I'd need for hooking it, but the binary is signed with a certificate so I can not compile my own version. Is it possible to fetch the functions' address at runtime or detour it with another technique? The target is a "normal" 32bit Windows binary btw. nothing special I thought ;)

Yours,
Nefarius

EDIT: maybe due to my lame English I was not detailed enough, so here a little sample code:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{
    foo();
}

BOOL foo(char* someData)
{
    return printf("%s", someData);
}

Now I want to detour the function foo() which does not exist in a dynamic library. This is my problem. I don't know how and I'm not sure if this works like I think it does.

EDIT: Now I know it is possible, so the important question changed to: how? How do I get the information I need; the functions address?


问:
Navigating & Passing Data Between Pages Ionic 2
I'm having some issues while navigating between pages with Ionic2.

I have a List of Data, that I got from a data.json

Here is the list

I want to get details:

Example - From "A"

The data that I have on my data/Example.Json

```<code> {
  "title": "A",
  "lat": 2.323733,
  "lon": 64,546465
},
</code>```

So as soon as I click on the Title, I want to get the title, lat and lon on a new page.

app.modules.ts

```<code>    import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { MapPage } from '../pages/map/map';
import { ListPage } from '../pages/list/list';
import { DetailPage } from '../pages/detail/detail';
import { Locations } from '../providers/locations';
import { GoogleMaps } from '../providers/google-maps';
import { Connectivity } from '../providers/connectivity';
declare var google: any;

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    MapPage,
    ListPage,
    DetailPage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    MapPage,
    ListPage,
    DetailPage
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},Locations,GoogleMaps, Connectivity]
})
export class AppModule {}

    import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { MapPage } from '../pages/map/map';
import { ListPage } from '../pages/list/list';
import { DetailPage } from '../pages/detail/detail';
import { Locations } from '../providers/locations';
import { GoogleMaps } from '../providers/google-maps';
import { Connectivity } from '../providers/connectivity';
declare var google: any;

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    MapPage,
    ListPage,
    DetailPage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    MapPage,
    ListPage,
    DetailPage
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},Locations,GoogleMaps, Connectivity]
})
export class AppModule {}
</code>```

PageA.ts ( list of Data )

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Locations } from '../../providers/locations';
import { DetailPage } from '../detail/detail';

@Component({
  selector: 'page-list',
  templateUrl: 'list.html'
})
export class ListPage {

  constructor(public navCtrl: NavController, public locations: Locations) {

  }

  ionViewDidLoad() {
    console.log('Test Si marche');

  }

  viewLocation(event,location) {
    this.navCtrl.push(DetailPage, {
      "title":location.title,
      "longitude":location.longitude
    })
  }

}
</code>```

Page B ( where i want to get the detail as soon as i click on something on the list )

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {NavParams} from "ionic-angular";
import { Locations} from '../../providers/locations';
import { ListPage } from '../list/list';

@Component({
    selector: 'page-detail',
    templateUrl: 'detail.html',
    providers: [ Locations ],
    entryComponents:[ ListPage ]
})

export class DetailPage {

    title: string
    latitude: string
    navParams: NavParams

    constructor(navParams: NavParams,public navCtrl: NavController) {
        this.navParams = navParams
        this.title = this.navParams.get('title');
        this.latitude = this.navParams.get('latitude');
    }

    ionViewDidLoad(err) {
        console.log(err);

    }
    goBack() {
        this.navCtrl.pop();
    }

}
</code>```

listA.html

```<code> <ion-header>

    <ion-navbar color="secondary">
        <ion-title>List</ion-title>
    </ion-navbar>

</ion-header>

<ion-content>

    <ion-list no-lines>

        <ion-item *ngFor="let location of locations.data">

            <ion-item (click)="viewLocation($event, locations)">{{locations.title}}</ion-item>
            <ion-avatar item-left>
                <ion-icon name="pin"></ion-icon>
            </ion-avatar>
            <!--<img src="./src/pics/mus.png"/>-->
            <h2>{{location.title}}</h2>
            <p>{{location.distance*1.609}} Km</p>
        </ion-item>

    </ion-list>

</ion-content>
</code>```

data.json

```<code>  [
  { "title": "Cat", "longitude": "14,57" },
  { "title": "Bird", "longitude": "17.45" },
  { "title": "Spider", "longitude": "19,12" }
]
</code>```

答:
If you want to pass data from one page to another, you can either

1) Store your JSON data in SQL format via JSON.stringify(store) and JSON.parse(retrieving) method.

Meaning you stringify the data, before storing inside the SQL table and once retrieved from the next page, you do a JSON.parse to get back your JSON object.

You may want to read up on the following article on how to store data in SQL.
SQL Ionic 2

JSON Parse

JSON Stringify

Or either which, 2) you can make use of navController to "push" data from one page to another. One downside would be if your JSON data is huge, you will have to slowly iterate through.

A simple example would be:

```<code>this.navController.push(ThePageNameYouWannaGo, {
      firstPassed: "firstData",
      secondPassed: "secondData",
      thirdPassed: "thirdData",
});

//On the next page (at your constructor),

Constructor(....,NavParams,.....){

  this.first = navParams.get("firstPassed");
  this.second= navParams.get("secondPassed");
  this.third= navParams.get("thirdPassed");

//the value would be stored inside this.first, this.second respectively
</code>```

For your case, I would recommend method 1 as I have no clue how big is your JSON file and to make your life easier in the future when your JSON file changes.

Body:
I'm having some issues while navigating between pages with Ionic2.

I have a List of Data, that I got from a data.json

Here is the list

I want to get details:

Example - From "A"

The data that I have on my data/Example.Json

 {
  "title": "A",
  "lat": 2.323733,
  "lon": 64,546465
},

So as soon as I click on the Title, I want to get the title, lat and lon on a new page.

app.modules.ts

    import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { MapPage } from '../pages/map/map';
import { ListPage } from '../pages/list/list';
import { DetailPage } from '../pages/detail/detail';
import { Locations } from '../providers/locations';
import { GoogleMaps } from '../providers/google-maps';
import { Connectivity } from '../providers/connectivity';
declare var google: any;

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    MapPage,
    ListPage,
    DetailPage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    MapPage,
    ListPage,
    DetailPage
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},Locations,GoogleMaps, Connectivity]
})
export class AppModule {}

    import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { MapPage } from '../pages/map/map';
import { ListPage } from '../pages/list/list';
import { DetailPage } from '../pages/detail/detail';
import { Locations } from '../providers/locations';
import { GoogleMaps } from '../providers/google-maps';
import { Connectivity } from '../providers/connectivity';
declare var google: any;

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    MapPage,
    ListPage,
    DetailPage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    MapPage,
    ListPage,
    DetailPage
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},Locations,GoogleMaps, Connectivity]
})
export class AppModule {}

PageA.ts ( list of Data )

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Locations } from '../../providers/locations';
import { DetailPage } from '../detail/detail';

@Component({
  selector: 'page-list',
  templateUrl: 'list.html'
})
export class ListPage {

  constructor(public navCtrl: NavController, public locations: Locations) {

  }

  ionViewDidLoad() {
    console.log('Test Si marche');

  }

  viewLocation(event,location) {
    this.navCtrl.push(DetailPage, {
      "title":location.title,
      "longitude":location.longitude
    })
  }

}

Page B ( where i want to get the detail as soon as i click on something on the list )

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {NavParams} from "ionic-angular";
import { Locations} from '../../providers/locations';
import { ListPage } from '../list/list';

@Component({
    selector: 'page-detail',
    templateUrl: 'detail.html',
    providers: [ Locations ],
    entryComponents:[ ListPage ]
})

export class DetailPage {

    title: string
    latitude: string
    navParams: NavParams

    constructor(navParams: NavParams,public navCtrl: NavController) {
        this.navParams = navParams
        this.title = this.navParams.get('title');
        this.latitude = this.navParams.get('latitude');
    }

    ionViewDidLoad(err) {
        console.log(err);

    }
    goBack() {
        this.navCtrl.pop();
    }

}

listA.html

 <ion-header>

    <ion-navbar color="secondary">
        <ion-title>List</ion-title>
    </ion-navbar>

</ion-header>

<ion-content>

    <ion-list no-lines>

        <ion-item *ngFor="let location of locations.data">

            <ion-item (click)="viewLocation($event, locations)">{{locations.title}}</ion-item>
            <ion-avatar item-left>
                <ion-icon name="pin"></ion-icon>
            </ion-avatar>

{{location.title}}

{{location.distance*1.609}} Km

        </ion-item>

    </ion-list>

</ion-content>

data.json

  [
  { "title": "Cat", "longitude": "14,57" },
  { "title": "Bird", "longitude": "17.45" },
  { "title": "Spider", "longitude": "19,12" }
]

Body:
If you want to pass data from one page to another, you can either

1) Store your JSON data in SQL format via JSON.stringify(store) and JSON.parse(retrieving) method.

Meaning you stringify the data, before storing inside the SQL table and once retrieved from the next page, you do a JSON.parse to get back your JSON object.

You may want to read up on the following article on how to store data in SQL.
SQL Ionic 2

JSON Parse

JSON Stringify

Or either which, 2) you can make use of navController to "push" data from one page to another. One downside would be if your JSON data is huge, you will have to slowly iterate through.

A simple example would be:

this.navController.push(ThePageNameYouWannaGo, {
      firstPassed: "firstData",
      secondPassed: "secondData",
      thirdPassed: "thirdData",
});

//On the next page (at your constructor),

Constructor(....,NavParams,.....){

  this.first = navParams.get("firstPassed");
  this.second= navParams.get("secondPassed");
  this.third= navParams.get("thirdPassed");

//the value would be stored inside this.first, this.second respectively

For your case, I would recommend method 1 as I have no clue how big is your JSON file and to make your life easier in the future when your JSON file changes.


答:
How about this? Simple and straightforward:</p>

```<code>for file in *.hola; do mv "$file" "${file/%hola/txt}"; done
</code>```

Title: awk Getting ALL line but last field with the delimiters

Body:
I have to make a one-liner that renames all files in the current directory
that end in ".hola" to ".txt".

For example:

sample.hola and name.hi.hola will be renamed to sample.txt and name.hi.txt respectively

I was thinking about something like:

ls -1 *.hola | awk '{NF="";print "$0.hola $0.txt"}' (*)

And then passing the stdin to xargs mv -T with a |

But the output of (*) for the example would be sample and name hi.

How do I get the output name.hi for name.hi.hola using awk?

Body:
How about this? Simple and straightforward:

for file in *.hola; do mv "$file" "${file/%hola/txt}"; done


问:
Orchard CMS render media public URL for path in theme razor template
Looking  to add a theme setting for a site logo URL to render in the header. However, when using Azure blob storage for images, the URL is not relative and will need to ask the media library for the public URL.

Just wondering what the best way to do this is from the shape template for my header / branding?

Currently is only working with file system media storage:

```<code><a class="logo" href="@Href("~/")">
    <img width="103" height="39" alt="" src="@Href(settings.SiteLogoUrl)" >
</a>
</code>```

Prefer to sore only a relative path in the setting so that any changes to public URL of the Auzre blob storage wont break the site.

答:
Found a solution that works. In the view you can resolve the storage provider, and then use that to get the public URL</p>

```<code>@{
    var storageProvider = WorkContext.Resolve<IStorageProvider>();
}
<a class="logo" href="@Href("~/")">
    <img width="103" height="39" alt="" src="@Href(storageProvider.GetPublicUrl(settings.SiteLogoUrl))" >
</a>
</code>```

Body:
Looking  to add a theme setting for a site logo URL to render in the header. However, when using Azure blob storage for images, the URL is not relative and will need to ask the media library for the public URL.

Just wondering what the best way to do this is from the shape template for my header / branding?

Currently is only working with file system media storage:

Prefer to sore only a relative path in the setting so that any changes to public URL of the Auzre blob storage wont break the site.

Body:
Found a solution that works. In the view you can resolve the storage provider, and then use that to get the public URL

@{
    var storageProvider = WorkContext.Resolve<IStorageProvider>();
}
<a class="logo" href="@Href("~/")">
    <img width="103" height="39" alt="" src="@Href(storageProvider.GetPublicUrl(settings.SiteLogoUrl))" >
</a>


问:
How to get top down forecasts using `hts::combinef()`?
I am trying to compare forecast reconciliation methods from the hts package on previously existing forecasts.  The forecast.gts function is not available to me since there is no computationally tractable way to create a user defined function that returns the values in a forecast object.  Because of this, I am using the combinef() function in the package to redistribute the forecasts.  I have been able to work of the proper weights to get the wls and nseries methods, and the ols version is the default.  I was able to get the "bottom up" method using:

```<code># Creates sample forecasts, taken from `combinef()` example
library(hts)
h <- 12
ally <- aggts(htseg1)
allf <- matrix(NA, nrow = h, ncol = ncol(ally))
for(i in 1:ncol(ally))
    allf[,i] <- forecast(auto.arima(ally[,i]), h = h, PI = FALSE)$mean
allf <- ts(allf, start = 51)
# create the weight vector
numTS <- ncol(allf) # Get the total number of series
numBaseTS <- sum(tail(htseg1$nodes, 1)[[1]]) # Get the number of bottom level series
# Create weights of 0 for all aggregate ts and 1 for the base level
weightVals <- c(rep(0, numTS - numBaseTS), rep(1, numBaseTS))
y.f <- combinef(allf, htseg1$nodes, weights = weightVals)
</code>```

I was hoping that something like making the first weight 1 and the rest 0 might give me one of the three top down forecast, but that just results in a bunch of 0s or NaN values depending on how you try to look at it.

```<code>combinef(allf, htseg1$nodes, weights = c(1, rep(0, numTS - 1)))
</code>```

I know the top down methods aren't the hardest thing to compute manually, and I can just write a function to do that, but are there any tools in the hts package that can help with this? I'd like to keep the data format consistent to simplify my analysis.  Most specifically, I would like to get the "top down forcasted proportions" or tdfp method.

答:
The functions to reconcile the forecasts using the "top-down" method are currently not exported. Probably I should export them to make the "top-down" results as tractable as combinef() in the next version. The workaround is as follows:

```<code>hts:::TdFp(allf, nodes = htseg1$nodes)
</code>```

Hope it helps.

Body:
I am trying to compare forecast reconciliation methods from the hts package on previously existing forecasts.  The forecast.gts function is not available to me since there is no computationally tractable way to create a user defined function that returns the values in a forecast object.  Because of this, I am using the combinef() function in the package to redistribute the forecasts.  I have been able to work of the proper weights to get the wls and nseries methods, and the ols version is the default.  I was able to get the "bottom up" method using:

# Creates sample forecasts, taken from `combinef()` example
library(hts)
h <- 12
ally <- aggts(htseg1)
allf <- matrix(NA, nrow = h, ncol = ncol(ally))
for(i in 1:ncol(ally))
    allf[,i] <- forecast(auto.arima(ally[,i]), h = h, PI = FALSE)$mean
allf <- ts(allf, start = 51)
# create the weight vector
numTS <- ncol(allf) # Get the total number of series
numBaseTS <- sum(tail(htseg1$nodes, 1)[[1]]) # Get the number of bottom level series
# Create weights of 0 for all aggregate ts and 1 for the base level
weightVals <- c(rep(0, numTS - numBaseTS), rep(1, numBaseTS))
y.f <- combinef(allf, htseg1$nodes, weights = weightVals)

I was hoping that something like making the first weight 1 and the rest 0 might give me one of the three top down forecast, but that just results in a bunch of 0s or NaN values depending on how you try to look at it.

combinef(allf, htseg1$nodes, weights = c(1, rep(0, numTS - 1)))

I know the top down methods aren't the hardest thing to compute manually, and I can just write a function to do that, but are there any tools in the hts package that can help with this? I'd like to keep the data format consistent to simplify my analysis.  Most specifically, I would like to get the "top down forcasted proportions" or tdfp method.

Body:
The functions to reconcile the forecasts using the "top-down" method are currently not exported. Probably I should export them to make the "top-down" results as tractable as combinef() in the next version. The workaround is as follows:

hts:::TdFp(allf, nodes = htseg1$nodes)

Hope it helps.


问:
Using Watson AlchemyAPI on medical data
I'm trying to create a java app which uses information from a medical guideline to support the activity a doctor. The use case is that when the doctor asks a question or inputs a scenario to the system, it responds with the recommendations from the guideline that best fit the situation.
My idea is to extract name, relations and their knowledge graph from my document and use them to do some reasoning.
My questions are:

With AlchemyAPI can I extract entities using an external service? (Like a medical dictionary such as UMLS or MedlinePlus)

For those entities can I extract their knowledge graph and expand it with reasoning?

If it is not possible, would Knowledge Studio help me with this task? ( My document is a relatively small pdf, at maximum 100 pages)

This is a curiosity: Is there for Watson services some detailed Javadoc other than sdk doc, basic class tree, and tutorials?
Thank you for your help.

答:
Take a look at the Natural Language Understanding (NLU) demo and see if the results based on some text from your use case are good enough. Otherwise, you will have to train a Knowledge Studio model and use it with NLU.

Watson doesn' have a knowledge graph that you can manipulate so you will have to develop this part. Once you get the entities from (1) you will have to create the knowledge graph.

Yes, see (1).

From your answer I assume you are using Java, in any case I think you need to first read the documentation for:

Natural Language Understanding

Knowledge Graph

Discovery. I think that those 100 pages you need to analyze could be stored using this service which will help you to also run some other NLP tasks on those documents.

Title: Using Watson AlchemyAPI on medical data


问:
How to avoid Grails automatically rebuilding my project on every change?
I have an old Grails 1.1.1 project that I had to upgrade to version 1.3.5 with STS Pro.

As expected, some debris is floating around that may be causing issues, but I'm not sure that's causing the problem.

This is the problem: Every time I save a class (Java or Groovy), it automatically rebuilds the whole project and creates a war file.

Is this the normal behavior? Actually, I don't mind it that much, just because the build runs on the background. The problem is that the build sometimes locks some resources temporarily, and I am having an annoying popup that says that it could not deploy because an assertion failed.

By the way, it doesn't say what was the assertion, so I have to click "OK" every time.

This is becoming a real pain.

Help will be greatly appreciated!

Thanks,

Luis

答:
According to the reference documentation, you could do:

```<code>grails -Ddisable.auto.recompile=true run-app
</code>```

However, you'll have to restart the application every time you make a change.

Body:
According to the reference documentation, you could do:

grails -Ddisable.auto.recompile=true run-app

However, you'll have to restart the application every time you make a change.


问:
Is there any way to simply store a string or other variable permanently without the use of a DB in node?
Is there any way to store a variable in nodeJS kind of like localStorage but for the server?
For example store a JSON object as a string for a small amount of data?</p>

答:
Totally. Check out the file system module that comes with Node. You can then just write to a file and then read it/change it/etc.

```<code>let myData = {
    something: 42,
    else: "a string!"
}

fs.writeFile('db.txt', JSON.stringify(myData), (err) => {
  if (err) throw err;
  console.log('The data has been saved!');
});
</code>```

You could also consider something like redis which is technically an in-memory database but is very straight forward to use. You should leverage a client like ioredis to easily store and retrieve data.

Body:
Totally. Check out the file system module that comes with Node. You can then just write to a file and then read it/change it/etc.

let myData = {
    something: 42,
    else: "a string!"
}

fs.writeFile('db.txt', JSON.stringify(myData), (err) => {
  if (err) throw err;
  console.log('The data has been saved!');
});

You could also consider something like redis which is technically an in-memory database but is very straight forward to use. You should leverage a client like ioredis to easily store and retrieve data.


问:
How to make edge sloped on a cylinder?
I'm beginner at 3D modelling and I'm making an office chair. Now I'm stuck at wheel area as I need a sloped edge cylinder for the base of the wheel.

Concept: The wheel is attached to a cylindrical base which is attached to the foot of the chair.

Current Situation: I draw foot of chair, made a circle on it and transformed into a cylinder. The end edge of the cylinder has no Face and I want to extrude the cylinder along one edge which will make a sloped area on the open side of area. That should look like this :

But I tried manythings to do, but failed. It's obvious as I said I'm beginner. Please help me do to this.

Note: I'm using blender 2.78

答:
I found the answer. This doesn't need complex techniques. I just did
Extrude > Merge > At the First.

That's it. Now I got the shape I wanted.

Title: How to make edge sloped on a cylinder?


问:
Cobertura data file not getting updated
I am trying to find out functional code coverage for my JAVA classes.
My java classes are deployed on a server as a JAR file. (Note: It is not deployed in any application server such as tomcat). After deploying my JAR file to server I instrumented that jar file using ant task. Classes inside my jar file are now instrumented (I confimred that by decompiling the classes). When I run my application (which in turn will access my classes from JAR file) it should created a new data file (.ser file) and add code coverage information into it. But No new data file is getting created neither is old data-file getting updated.

My project structure on server is as follows

```<code>Main-Folder
|--cobertura-2.1.1
|--ccbuild.xml
|--cobertura.ser (created during instrumentation)
|--lib
    |---code.jar (This file contains my instrumented classes)
    |---other-dependency.jar (All other dependencies)
    |---cobertura.jar
</code>```

Why are my class files not generating code coverage information?

答: I had this problem while generating .ser file. My problem resolved after changing the version of one dependent lib commons-io to V2.4</p>

Title: Cobertura data file not getting updated

Body:
I am trying to find out functional code coverage for my JAVA classes.
My java classes are deployed on a server as a JAR file. (Note: It is not deployed in any application server such as tomcat). After deploying my JAR file to server I instrumented that jar file using ant task. Classes inside my jar file are now instrumented (I confimred that by decompiling the classes). When I run my application (which in turn will access my classes from JAR file) it should created a new data file (.ser file) and add code coverage information into it. But No new data file is getting created neither is old data-file getting updated.

My project structure on server is as follows

Main-Folder
|--cobertura-2.1.1
|--ccbuild.xml
|--cobertura.ser (created during instrumentation)
|--lib
    |---code.jar (This file contains my instrumented classes)
    |---other-dependency.jar (All other dependencies)
    |---cobertura.jar

Why are my class files not generating code coverage information?


问:
How to create popup windows in html
I want to know how the pop up windows integrated into websites are built. I am trying to create one for my websites but i don't really know it is created whether they are plugins or not. Any help as to how to go about it.
Below is an example of what i want to do.

答:
Beginner! To make a pop-up like the one you provided, you would need to write backend code (Node.JS, PHP, Python, etc.). But for just a simple info pop-up with a button that activates the pop-up refer to this jsfiddle I created:

https://jsfiddle.net/d706dyg7/1/

```<code>$("#whateverid").click(function(){
    //whatever code
});
</code>```

That mean when that element is clicked blah happens.

Hope that helps,
Ben A.K.A BlackSky

P.S. If you want a solution in pure javascript and not jQuery just let me know and I will edit my fiddle!

Title: How to create popup windows in html

Body:
Beginner! To make a pop-up like the one you provided, you would need to write backend code (Node.JS, PHP, Python, etc.). But for just a simple info pop-up with a button that activates the pop-up refer to this jsfiddle I created:

https://jsfiddle.net/d706dyg7/1/

$("#whateverid").click(function(){
    //whatever code
});

That mean when that element is clicked blah happens.

Hope that helps,
Ben A.K.A BlackSky

P.S. If you want a solution in pure javascript and not jQuery just let me know and I will edit my fiddle!


问:
Watson dialogue, movie find demo code: The words on the home page of this bot cannot be changed
I made the following Watson demo app code work in Bluemix cloud. Went through many files in this demo app.
https://github.com/watson-developer-cloud/conversational-agent

The working bot is here:
https://movieb4testcnvservice.mybluemix.net

Yesterday, I changed the words "Chat with Watson" on the above bot and saved the file as home.html.  But after many reloads, the words "Chat with Watson" are still in the above bot. What caused this?

答: The conversational-agent was deprecated a few months ago. There is no replacement and it was based on the Dialog service which will be discontinued in August. See: https://www.ibm.com/watson/developercloud/dialog.html


问:
How do I exclude files/folders from a .NET Core/Standard project?
In .NET Core and .NET Standard projects, if you put files and folders within the project directory, they are automatically picked up by Visual Studio; essentially they are part of the project.

What if I have files/folders in there that aren't really part of the project itself (in terms of code or content) - short of removing them altogether, is there a way I can exclude them from the project as I can with projects targeting the full .NET Framework?

答:
Open the project in Visual Studio, and right click the files and folders in Solution Explorer. Choose Exclude from Project.

That's exactly what you do for projects targeting .NET Framework.


问:
simple recursive merge sort Stack java.lang.StackOverflowError
I have a simple recursive merge sort, I am just try to sort an array list of Integers that implement Comparable. I don't under stand why I am getting an error, when it runs it prints out the ArrayList of random Integers that I created and then it prints

no error yet

no error yet

Exception in thread "main" java.lang.StackOverflowError

and then it repeats

at MergeTemplate.rMerge(MergeTemplate.java:38)

a bunch of times until it finally says

Process complete

```<code>import java.util.*;
public class MergeTemplate{
private ArrayList <Comparable> temp1=new <Comparable> ArrayList();
int num;
Random ar=new Random();
public MergeTemplate(){
    num=25;
}
  public MergeTemplate(int n){
    num=n;
  }
      public ArrayList <Comparable> fillArray(){
          ArrayList <Comparable> ar1=new <Comparable> ArrayList();
          for(int i=0;i<num; i++)
              ar1.add(ar.nextInt(11));
          screenOutput(ar1);
      return ar1;
      }
      public void screenOutput(){
          for(Comparable x: temp1)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void screenOutput(ArrayList <Comparable> temp){
          for(Comparable x: temp)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void rMerge(ArrayList <Comparable> rList){
          rMerge(rList, 0, rList.size()-1);
      }

      public void rMerge(ArrayList <Comparable> rList, int first, int last){
          if (first-last==0){
              System.out.println("no error yet");
          }
          else{
              rMerge(rList, first, last/2);
              rMerge(rList, last/2 + 1, last);
              merge(rList, first, last);
          }
      }
      public void merge(ArrayList <Comparable> a, int first, int last){
          Comparable placeHolder;
          if(a.get(first).compareTo(a.get(last))>1){
              placeHolder=a.get(first);
              a.set(first, a.get(last));
              a.set(last, placeHolder);
          }
      }
}

public class Tester {
    public static void main(String[] args) {
    MergeTemplate one=new MergeTemplate(8);
    one.rMerge(one.fillArray());
    }
}
</code>```

答:
Your error occurs in

```<code>rMerge(rList, first, last/2);
</code>```

When first equals 2 last goes to less than 2, actually last equals to 0 and keeps on calling itself. You need a check that there is 1 element.

Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted)

Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list.

from wikipedia.

Body:
I have a simple recursive merge sort, I am just try to sort an array list of Integers that implement Comparable. I don't under stand why I am getting an error, when it runs it prints out the ArrayList of random Integers that I created and then it prints

no error yet

no error yet

Exception in thread "main" java.lang.StackOverflowError

and then it repeats

at MergeTemplate.rMerge(MergeTemplate.java:38)

a bunch of times until it finally says

Process complete

import java.util.*;
public class MergeTemplate{
private ArrayList <Comparable> temp1=new <Comparable> ArrayList();
int num;
Random ar=new Random();
public MergeTemplate(){
    num=25;
}
  public MergeTemplate(int n){
    num=n;
  }
      public ArrayList <Comparable> fillArray(){
          ArrayList <Comparable> ar1=new <Comparable> ArrayList();
          for(int i=0;i<num; i++)
              ar1.add(ar.nextInt(11));
          screenOutput(ar1);
      return ar1;
      }
      public void screenOutput(){
          for(Comparable x: temp1)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void screenOutput(ArrayList <Comparable> temp){
          for(Comparable x: temp)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void rMerge(ArrayList <Comparable> rList){
          rMerge(rList, 0, rList.size()-1);
      }

      public void rMerge(ArrayList <Comparable> rList, int first, int last){
          if (first-last==0){
              System.out.println("no error yet");
          }
          else{
              rMerge(rList, first, last/2);
              rMerge(rList, last/2 + 1, last);
              merge(rList, first, last);
          }
      }
      public void merge(ArrayList <Comparable> a, int first, int last){
          Comparable placeHolder;
          if(a.get(first).compareTo(a.get(last))>1){
              placeHolder=a.get(first);
              a.set(first, a.get(last));
              a.set(last, placeHolder);
          }
      }
}

public class Tester {
    public static void main(String[] args) {
    MergeTemplate one=new MergeTemplate(8);
    one.rMerge(one.fillArray());
    }
}

Body:
Your error occurs in

rMerge(rList, first, last/2);

When first equals 2 last goes to less than 2, actually last equals to 0 and keeps on calling itself. You need a check that there is 1 element.

Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted)

Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list.

from wikipedia.


问:
Get the most precise time in Ruby
I want to get the most possible precis time using Ruby.  For example:

```<code>3.times.map do
  Thread.new do
    # Expect 3 differnt results from each thread
    p Time.now.precis_time
  end
end.each(&:join)
</code>```

However, even using the strftime, I still can not achieve the goal. So is there any other way to get this?

答:
The most precise timer available to Ruby is Process::clock_gettime. To avoid losing precision to float rounding, use :nanosecond unit:

```<code>3.times { p Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond) }
# => 1491185078101717000
# => 1491185078101741000
# => 1491185078101747000
</code>```

EDIT: This is the same time that is available by Time.now. On Linux, the two have nanosecond precision. However, there is another clock that has nanosecond precision even on OSX: CLOCK_MONOTONIC. This clock does not track time from epoch, but time from "some event", this event normally being your computer's boot time. To get the most precise time, one can take the difference between CLOCK_REALTIME and CLOCK_MONOTONIC and apply it later:

```<code>clock_diff = Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond) -
       Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)

3.times {
  nsec = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond) + clock_diff
  time = Time.at(nsec / 1_000_000_000, nsec % 1_000_000_000 / 1_000.0)
  p time.strftime("%Y-%m-%d %H:%i:%s.%N")
}
</code>```

Title: Get the most precise time in Ruby

Body:
I want to get the most possible precis time using Ruby.  For example:

3.times.map do
  Thread.new do
    # Expect 3 differnt results from each thread
    p Time.now.precis_time
  end
end.each(&:join)

However, even using the strftime, I still can not achieve the goal. So is there any other way to get this?

Body:
The most precise timer available to Ruby is Process::clock_gettime. To avoid losing precision to float rounding, use :nanosecond unit:

3.times { p Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond) }
# => 1491185078101717000
# => 1491185078101741000
# => 1491185078101747000

EDIT: This is the same time that is available by Time.now. On Linux, the two have nanosecond precision. However, there is another clock that has nanosecond precision even on OSX: CLOCK_MONOTONIC. This clock does not track time from epoch, but time from "some event", this event normally being your computer's boot time. To get the most precise time, one can take the difference between CLOCK_REALTIME and CLOCK_MONOTONIC and apply it later:

clock_diff = Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond) -
       Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)

3.times {
  nsec = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond) + clock_diff
  time = Time.at(nsec / 1_000_000_000, nsec % 1_000_000_000 / 1_000.0)
  p time.strftime("%Y-%m-%d %H:%i:%s.%N")
}


问:
How to redirect user inside vue-resource http interceptor?
I want to redirect the user when I have an 401, but I can't access the router from this context:

```<code>  Vue.http.interceptors.push(function(request, next) {
    // continue to next interceptor
    next(function(response) {
        if(response.status == 401){
            //redirect user here
            //tried: Vue.$router and Vue.$route
        }

    });
  });
</code>```

How can I make this?

Using: Vue-router and Vue-resource

答:
```<code>const router = new VueRouter({
  routes
})

Vue.http.interceptors.push(function(request, next) {
    // continue to next interceptor
    next(function(response) {
        if(response.status == 401){
            router.push(...)
        }
    });
 });
</code>```

Body:
I want to redirect the user when I have an 401, but I can't access the router from this context:

  Vue.http.interceptors.push(function(request, next) {
    // continue to next interceptor
    next(function(response) {
        if(response.status == 401){
            //redirect user here
            //tried: Vue.$router and Vue.$route
        }

    });
  });

How can I make this?

Using: Vue-router and Vue-resource


问:
Does embedded webkit browser in El Capitan support localstorage?
I have a Microsoft Word 2016 Add-in that (like all Office.js Add-ins) uses Apple's WebKit as the embedded browser.

(On Microsoft Word 2016 for Windows the browser is IE11 of all things).

On El Capitan my Add-in is throwing an error - which is nearly impossible to debug...at least given what I know. Specifically 10.11.6.

Everything works fine on Sierra.

I've traced the issue to, potentially, my use of localstorage to keep and reuse a couple of values...

Does Apple WebKit embedded support the use of localstorage? Maybe there's some sort of permission or initialization required?

Is there any way to troubleshoot embedded webkit? The solution works fine on Safari/Chrome etc.

Are there any other differences between webkit on El Capitan and Sierra?

答:
Yes, WebKit (at least for 10.11.6) supports localstorage.

I traced my problem to the use of 'const' while in 'use strict'...

I was using a code snippet from Firebase/Google (for authentication across all my apps/websites) that declared a variable using “const”.

In “use strict” this is not allowed in older versions of WebKit. It’s been fixed, which is why Sierra was okay (I guess).

See https://bugs.webkit.org/show_bug.cgi?id=161464.

But it threw an error on 10.11.6 and (I guess) earlier.

Here is the crucial bit of info: how to turn on debugging for WebKit (when used as an embedded browser):

Run the following command using terminal on your Mac:

```<code>defaults write com.Microsoft.OsfWebHost WebKitDeveloperExtras -bool true
</code>```

Body:
Yes, WebKit (at least for 10.11.6) supports localstorage.

I traced my problem to the use of 'const' while in 'use strict'...

I was using a code snippet from Firebase/Google (for authentication across all my apps/websites) that declared a variable using “const”.

In “use strict” this is not allowed in older versions of WebKit. It’s been fixed, which is why Sierra was okay (I guess).

See https://bugs.webkit.org/show_bug.cgi?id=161464.

But it threw an error on 10.11.6 and (I guess) earlier.

Here is the crucial bit of info: how to turn on debugging for WebKit (when used as an embedded browser):

Run the following command using terminal on your Mac:

defaults write com.Microsoft.OsfWebHost WebKitDeveloperExtras -bool true


问:
Google Cloud Functions enable CORS?
I just finished the Hello World Google Cloud Functions tutorial and received the following response headers:

```<code>Connection → keep-alive
Content-Length → 14
Content-Type → text/plain; charset=utf-8
Date → Mon, 29 Feb 2016 07:02:37 GMT
Execution-Id → XbT-WC9lXKL-0
Server → nginx
</code>```

How can I add the CORS headers to be able to call my function from my website?

答:
You can use the CORS express middleware.

package.json

```<code>npm install express --save
npm install cors --save
</code>```

index.js

```<code>'use strict';

const functions = require('firebase-functions');
const express = require('express');
const cors = require('cors')({origin: true});
const app = express();

app.use(cors);
app.get('*', (req, res) => {
    res.send(`Hello, world`);
});

exports.hello = functions.https.onRequest(app);
</code>```

Title: Google Cloud Functions enable CORS?

Body:
I just finished the Hello World Google Cloud Functions tutorial and received the following response headers:

Connection → keep-alive
Content-Length → 14
Content-Type → text/plain; charset=utf-8
Date → Mon, 29 Feb 2016 07:02:37 GMT
Execution-Id → XbT-WC9lXKL-0
Server → nginx

How can I add the CORS headers to be able to call my function from my website?

Body:
You can use the CORS express middleware.

package.json

npm install express --save
npm install cors --save

index.js

'use strict';

const functions = require('firebase-functions');
const express = require('express');
const cors = require('cors')({origin: true});
const app = express();

app.use(cors);
app.get('*', (req, res) => {
    res.send(`Hello, world`);
});

exports.hello = functions.https.onRequest(app);


问:
Change in date format after exporting data.frame from R as .csv
It is a simple question but I couldn't find an answer.

I have this data.frame in R

```<code>df <- data.frame(date = as.Date(c("2001-01-05", "2000-05-13", "2000-07-22", "2000-07-22", "1990-11-03")))
</code>```

I want to export it as .csv file where Month will be abbreviated (%b) and year will be year with century (%Y) as below

```<code>df1 <- df %>% mutate(date = format(as.Date(date, "%Y-%m-%d"), "%b-%Y"))
write.csv(df1, "df1.csv")
> df1
      date
1 Jan-2001
2 May-2000
3 Jul-2000
4 Jul-2000
5 Nov-1990
</code>```

After I opened the df1.csv file, I found a different format for the date as below

I couldn't find the format month(abbreviated)-YEAR. Any suggestion how to fix it?

答: This is not an R issue. Excel has "helpfully" applied its own formatting to your data. To prevent this, you need to exert more control over the CSV import. These instructions may help you with that.</p>

Body:
It is a simple question but I couldn't find an answer.

I have this data.frame in R

df <- data.frame(date = as.Date(c("2001-01-05", "2000-05-13", "2000-07-22", "2000-07-22", "1990-11-03")))

I want to export it as .csv file where Month will be abbreviated (%b) and year will be year with century (%Y) as below

df1 <- df %>% mutate(date = format(as.Date(date, "%Y-%m-%d"), "%b-%Y"))
write.csv(df1, "df1.csv")
> df1
      date
1 Jan-2001
2 May-2000
3 Jul-2000
4 Jul-2000
5 Nov-1990

After I opened the df1.csv file, I found a different format for the date as below

I couldn't find the format month(abbreviated)-YEAR. Any suggestion how to fix it?


问:
Connecting to existing Heroku Postgres DB for Sinatra app
I am using Salesforce for my CRM, but need to query data (multiple records, so no Zapier) for a Heroku based Sinatra app. Heroku provides a service that replicates Salesforce objects to Postgres tables regularly which gets my data out of Salesforce.

I've coded a Sinatra app before and hosted it on Heroku so I'm a bit familiar with the process of setting up a dev db locally then pushing it to production via the many tutorials. However, i'm running into an issue finding any information that will allow me to connect to the existing production Postgres DB that already is populated with the data I need while having no need to create and connect to a local dev db.

Heroku provides me with the following

How and where to I plug in these various credentials securely so my following files have the right information to connect to tables Venue__c and Spaces__c?

app.rb

/config

- database.yml

- environments.rb

答:
Turns out Heroku has a great tutorial that not only connects to the replicated database, but is also written for Sinatra.

https://devcenter.heroku.com/articles/getting-started-with-heroku-and-connect-without-local-dev#introduction


问:
My file can compile but I get "no such file or directory" when I try to run it
I figured that the problem was that I was not using ./a.out instead of ./filename, but that wasn't the case.

This is how I compile my program:

```<code>g++ -o -Wall -pthread filename.cpp
</code>```

Running:

```<code>./filename
</code>```

I figured that running pthread programs would be different than running a standard c++ program, but that wasn't the case.

```<code>#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct argStruct {
    int arg1;
    int arg2;

};

void *sum(void *arguments) {
    struct argStruct *args = (struct argStruct *)arguments;

    int a =  args -> arg1;
    int b =  args -> arg2;
    int c = a + b;
    printf("%d + %d = %d ",a,b,c);
    pthread_exit(NULL);

}

int main() {

    pthread_t thr1, thr2;
    struct argStruct args;
    args.arg1 = 3;
    args.arg2 = 10;

    int t1, t2;

    pthread_create(&thr1, NULL, &sum, (void *)&args);

    pthread_create(&thr2, NULL, &sum, (void *)&args);

    pthread_join(thr1, NULL);
    pthread_join(thr2, NULL);

    exit(EXIT_SUCCESS);

}
</code>```

答:
By calling

g++ -o -Wall -pthread filename.cpp
```

<p>You instruct the compiler to write the result to a file named <code>-Wall</code>.</p>

<p>You therefore want to use one of these</p>

<pre class="lang-bash prettyprint-override"><code>g++ -Wall -pthread filename.cpp
g++ -Wall -pthread -o filename filename.cpp
</code>```

The first writes the result to a.out, the second to filename.  (Also it enables the warnings)

Body:
I figured that the problem was that I was not using ./a.out instead of ./filename, but that wasn't the case.

This is how I compile my program:

g++ -o -Wall -pthread filename.cpp

Running:

./filename

I figured that running pthread programs would be different than running a standard c++ program, but that wasn't the case.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct argStruct {
    int arg1;
    int arg2;

};

void *sum(void *arguments) {
    struct argStruct *args = (struct argStruct *)arguments;

    int a =  args -> arg1;
    int b =  args -> arg2;
    int c = a + b;
    printf("%d + %d = %d ",a,b,c);
    pthread_exit(NULL);

}

int main() {

    pthread_t thr1, thr2;
    struct argStruct args;
    args.arg1 = 3;
    args.arg2 = 10;

    int t1, t2;

    pthread_create(&thr1, NULL, &sum, (void *)&args);

    pthread_create(&thr2, NULL, &sum, (void *)&args);

    pthread_join(thr1, NULL);
    pthread_join(thr2, NULL);

    exit(EXIT_SUCCESS);

}

Body:
By calling

g++ -o -Wall -pthread filename.cpp

You instruct the compiler to write the result to a file named -Wall.

You therefore want to use one of these

g++ -Wall -pthread filename.cpp
g++ -Wall -pthread -o filename filename.cpp

The first writes the result to a.out, the second to filename.  (Also it enables the warnings)


问:
Touch events on pie graph in swift 3
i am currently working on an app that involves a pie chart. And i am struggling to figure out how to make the segments of the pie graph behave as UIButtons. I have found how to do what i am looking for on bar graphs, but it doesnt seem to be the same with pie graphs.
I am using IOSCharts, I have added ChartViewDelegate to the class header, pieView.delegate = self is in the viewDidLoad().
This is the current function i am using to try and use the touchevents

func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: Highlight) {
        print("Triangle")
    }

答:
I replicated your scene of the problem with the new function:

```<code>func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
    print("Triangle")
}
</code>```

And it is working as expected, so I'm guessing your problem is not in the code.

Be sure to check for typos or that your pieView is linked correctly.

Apologies for the late answer.

Title: Touch events on pie graph in swift 3

Body:
I replicated your scene of the problem with the new function:

func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
    print("Triangle")
}

And it is working as expected, so I'm guessing your problem is not in the code.

Be sure to check for typos or that your pieView is linked correctly.

Apologies for the late answer.


问:
Connect to Azure Virtual machine from Mobile App locally
I'm using Azure Mobile App and classic Virtual Machine on Azure Portal.

There is a great tool on Mobile App - API. I use it for different tasks.
My question is -can I somehow connect to server from mobile app API using local interface?

For instance, I want to deploy web server on virtual machine and restrict connections only from local subnet? And I will use mobile app API to communicate with it.
Thank you.

答: If you want to connect Azure mobile App with Azure Virtual Machine, we have two solution. 1) VNET Intergration 2) Hybrid Connection. Of course, we can deploy mobile project to Azure Virtual Machine directly. If you want the server only be accessed by the web server, please consider the design in this article. Put the server in the backend and put the web server in the frontend. Use NSG to limit the sever so that it only be accessed by the web server.</p>


问:
Tableview item dependencies javafx
Good evening,

I am working on a project and I'm at lost at how to configure my tableviews to depend on each other.  I would like for the parts in one tableview to depend on the products in the other.  How would I go about doing that? I prefer to not use sql at the moment just to keep everything simple as possible.  The code snippet is listed below:

```<code>public class maincontroller {

private  ObservableList<Part> parts = FXCollections.observableArrayList();

 private ObservableList<Product> products = FXCollections.observableArrayList();

//code to swap between controllers

  @Override
    public void initialize(URL url, ResourceBundle rb) {

        partsID.setCellValueFactory(new PropertyValueFactory<>("partID"));
        partsName.setCellValueFactory(new PropertyValueFactory<>("name"));
        partsinvlevel.setCellValueFactory(new PropertyValueFactory<>("instock"));
        partscost.setCellValueFactory(new PropertyValueFactory<>("price"));
        parttable.setItems(parts);

        productsID.setCellValueFactory(new PropertyValueFactory<>("productID"));

        productsName.setCellValueFactory(new PropertyValueFactory<>("name"));
        productsInvlevel.setCellValueFactory(new PropertyValueFactory<>("instock"));
        productsprice.setCellValueFactory(new PropertyValueFactory<>("price"));
        producttable.setItems(products);

        parttable.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Part> observable, Part oldValue, Part newValue) -> {

        });

        producttable.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Product> observable, Product oldValue, Product newValue) -> {

        });

    }
}
</code>```

答:
I'm not too sure about the relationship between Part and Product. From the context, I would assume each specific Product would have its own list of Parts that is related to it. I would also assume that that list of Parts is stored within Product.

Product:

```<code>public class Product
{
    private final ObservableList<Part> parts = FXCollections.observableArrayList();
    public final ObservableList<Part> getParts() { return parts; }
    ........
}
</code>```

This is what you can do:

```<code>producttable.getSelectionModel().selectedItemProperty().addListener(observable, oldProduct, newProduct) ->
{
    if (newProduct != null)
    {
        parts.clear();
        parts.addAll(newProduct.getParts());
    }
});
</code>```

Title: Tableview item dependencies javafx

Body:
Good evening,

I am working on a project and I'm at lost at how to configure my tableviews to depend on each other.  I would like for the parts in one tableview to depend on the products in the other.  How would I go about doing that? I prefer to not use sql at the moment just to keep everything simple as possible.  The code snippet is listed below:

public class maincontroller {

private  ObservableList<Part> parts = FXCollections.observableArrayList();

 private ObservableList<Product> products = FXCollections.observableArrayList();

//code to swap between controllers

  @Override
    public void initialize(URL url, ResourceBundle rb) {

        partsID.setCellValueFactory(new PropertyValueFactory<>("partID"));
        partsName.setCellValueFactory(new PropertyValueFactory<>("name"));
        partsinvlevel.setCellValueFactory(new PropertyValueFactory<>("instock"));
        partscost.setCellValueFactory(new PropertyValueFactory<>("price"));
        parttable.setItems(parts);

        productsID.setCellValueFactory(new PropertyValueFactory<>("productID"));

        productsName.setCellValueFactory(new PropertyValueFactory<>("name"));
        productsInvlevel.setCellValueFactory(new PropertyValueFactory<>("instock"));
        productsprice.setCellValueFactory(new PropertyValueFactory<>("price"));
        producttable.setItems(products);

        parttable.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Part> observable, Part oldValue, Part newValue) -> {

        });

        producttable.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Product> observable, Product oldValue, Product newValue) -> {

        });

    }
}

Body:
I'm not too sure about the relationship between Part and Product. From the context, I would assume each specific Product would have its own list of Parts that is related to it. I would also assume that that list of Parts is stored within Product.

Product:

public class Product
{
    private final ObservableList<Part> parts = FXCollections.observableArrayList();
    public final ObservableList<Part> getParts() { return parts; }
    ........
}

This is what you can do:

producttable.getSelectionModel().selectedItemProperty().addListener(observable, oldProduct, newProduct) ->
{
    if (newProduct != null)
    {
        parts.clear();
        parts.addAll(newProduct.getParts());
    }
});


问:
Issue with Cross Validation
I want to use leave one out cross validation. But i am getting below error:

```<code>AttributeError                            Traceback (most recent call last)
<ipython-input-19-f15f1e522706> in <module>()
      3 loo = LeaveOneOut(num_of_examples)
      4 #loo.get_n_splits(X_train_std)
----> 5 for train, test in loo.split(X_train_std):
      6     print("%s %s" % (train, test))
</code>```

AttributeError: 'LeaveOneOut' object has no attribute 'split'

The detailed code is as follows:

```<code>from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test =
train_test_split(X, y, test_size=0.3, random_state=0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)

from sklearn.cross_validation import LeaveOneOut
num_of_examples = len(X_train_std)
loo = LeaveOneOut(num_of_examples)
for train, test in loo.split(X_train_std):
print("%s %s" % (train, test))
</code>```

答:
I think that you are using scikit-learn version below 0.18 and maybe referring some tutorials for version 0.18.

In versions prior to 0.18, the LeaveOneOut() constructor has a required parameter n which is not supplied in the above code you posted. Hence the error. You can refer to the documentation of LeaveOneOut for version 0.17 here where its mentioned that:

Parameters:    n : int Total number of elements in dataset.

Solution:

Update the scikit-learn to version 0.18

Initialize the LeaveOneOut as follows:

loo = LeaveOneOut(size of X_train_std)

Edit:

If you are using the scikit version >=0.18:

```<code>from sklearn.model_selection import LeaveOneOut
for train_index, test_index in loo.split(X):
    print("%s %s" % (train_index, test_index))
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
</code>```

Else, for versions < 0.18 use the iterations like this (Notice that here loo.split() is not used, loo is used directly):

```<code>from sklearn.cross_validation import LeaveOneOut
loo = LeaveOneOut(num_of_examples)
for train_index, test_index in loo:
    print("%s %s" % (train_index, test_index))
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
</code>```

Title: Issue with Cross Validation

Body:
I want to use leave one out cross validation. But i am getting below error:

AttributeError                            Traceback (most recent call last)
<ipython-input-19-f15f1e522706> in <module>()
      3 loo = LeaveOneOut(num_of_examples)
      4 #loo.get_n_splits(X_train_std)
----> 5 for train, test in loo.split(X_train_std):
      6     print("%s %s" % (train, test))

AttributeError: 'LeaveOneOut' object has no attribute 'split'

The detailed code is as follows:

from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test =
train_test_split(X, y, test_size=0.3, random_state=0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)

from sklearn.cross_validation import LeaveOneOut
num_of_examples = len(X_train_std)
loo = LeaveOneOut(num_of_examples)
for train, test in loo.split(X_train_std):
print("%s %s" % (train, test))

Body:
I think that you are using scikit-learn version below 0.18 and maybe referring some tutorials for version 0.18.

In versions prior to 0.18, the LeaveOneOut() constructor has a required parameter n which is not supplied in the above code you posted. Hence the error. You can refer to the documentation of LeaveOneOut for version 0.17 here where its mentioned that:

Parameters:    n : int Total number of elements in dataset.

Solution:

Update the scikit-learn to version 0.18

Initialize the LeaveOneOut as follows:

loo = LeaveOneOut(size of X_train_std)

Edit:

If you are using the scikit version >=0.18:

from sklearn.model_selection import LeaveOneOut
for train_index, test_index in loo.split(X):
    print("%s %s" % (train_index, test_index))
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

Else, for versions < 0.18 use the iterations like this (Notice that here loo.split() is not used, loo is used directly):

from sklearn.cross_validation import LeaveOneOut
loo = LeaveOneOut(num_of_examples)
for train_index, test_index in loo:
    print("%s %s" % (train_index, test_index))
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]


问:
Unable to Set Initializer for Custom UICollectionView Cell Class
I am trying to set an initializer for a custom UICollectionViewCell class and I am receiving an error. I am new to Swift and understand that a model class must have a relevant initializer in order to use items from the class. Here is my code and the error I am receiving:

答:
if your 'Key' is not optional then you need to initialize the 'key' in Init().

```<code>public required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    // do something here if you need ...
}
</code>```

The decoder is useful if you want to restore your object to customer object.For example, if you store a class object in core data and read the record from core data then you need to do encode and decode for it.

Body:
if your 'Key' is not optional then you need to initialize the 'key' in Init().

public required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    // do something here if you need ...
}

The decoder is useful if you want to restore your object to customer object.For example, if you store a class object in core data and read the record from core data then you need to do encode and decode for it.


问:
Copying array of structs from host to device cuda
Suppose I have a struct as follows:

```<code>typedef struct values{
int one, int two, int three
} values;
</code>```

Now, suppose I create an array of values on the host and populate with random data

```<code>values vals*;
__device__ values* d_vals;
int main(){
     vals = (values*)malloc(sizeof(values) * A_LARGE_NUMBER);
     PopulateWithDate(); //populates vals with random data
}
</code>```

Now I want to be able to copy the values to the device such that I can access them in my kernel like so:

```<code>__global__ void myKernel(){
     printf("%d", d_vals[0].one);//I don't really want to print, but whenever I try to access I get an error
}
</code>```

Whatever I try I get an illegal memory access was encountered error.

Here's my current attempt:

```<code>int main(){
     vals = (values*)malloc(sizeof(values) * A_LARGE_NUMBER);
     PopulateWithDate(); //populates vals with random data

     values* d_ptr;
     cudaGetSymbolAddress((void**)&d_ptr, d_vals);
     cudaMalloc((void**)&d_ptr, A_LARGE_NUMBER * sizeof(values));

     cudaMemcpyToSymbol(d_ptr, &vals, sizeof(values) * A_LARGE_NUMBER);
     cudaDeviceSynchronize();
     dim3    blocksPerGrid(2, 2);
     dim3    threadsPerBlock(16, 16);

    myKernel<< <blocksPerGrid, threadsPerBlock >> >();
}
</code>```

答:
For what you have shown so far, using a __device__ pointer variable just creates needless complexity.  Just use an ordinary dynamic allocation using cudaMalloc for device storage, and otherwise follow an approach similar to any of the CUDA sample codes such as vectorAdd.  Here is an example:

```<code>$ cat t1315.cu
#include <stdio.h>
#define A_LARGE_NUMBER 10

struct values{
int one, two, three;
};

values *vals;

__global__ void myKernel(values *d_vals){
     printf("%d\n", d_vals[0].one);
}

void PopulateWithData(){
  for (int i = 0; i < A_LARGE_NUMBER; i++){
    vals[i].one = 1;
    vals[i].two = 2;
    vals[i].three = 3;
  }
}

int main(){
     vals = (values*)malloc(sizeof(values) * A_LARGE_NUMBER);
     PopulateWithData(); //populates vals with random data

     values* d_ptr;
     cudaMalloc((void**)&d_ptr, A_LARGE_NUMBER * sizeof(values));
     cudaMemcpy(d_ptr, vals, A_LARGE_NUMBER *sizeof(values),cudaMemcpyHostToDevice);
     dim3    blocksPerGrid(1,1);
     dim3    threadsPerBlock(1, 1);

    myKernel<< <blocksPerGrid, threadsPerBlock >> >(d_ptr);
    cudaDeviceSynchronize();
}
$ nvcc -arch=sm_35 -o t1315 t1315.cu
$ cuda-memcheck ./t1315
========= CUDA-MEMCHECK
1
========= ERROR SUMMARY: 0 errors
$
</code>```

You had a variety of other basic (non-CUDA) coding errors in what you had shown, I'm not going to try and run through them all.

If you really want to retain your __device__ pointer variable, and use that to point to the device data (array of structs) then you will still need to use cudaMalloc, and the overall process takes additional steps.  You can follow the example worked out in the answer here.

Following that example, here's a set of changes to the above code to make it work with a __device__ pointer variable instead of a pointer passed as a kernel parameter:

```<code>$ cat t1315.cu
#include <stdio.h>
#define A_LARGE_NUMBER 10

struct values{
int one, two, three;
};

values *vals;
__device__ values *d_vals;

__global__ void myKernel(){
     printf("%d\n", d_vals[0].one);
}

void PopulateWithData(){
  for (int i = 0; i < A_LARGE_NUMBER; i++){
    vals[i].one = 1;
    vals[i].two = 2;
    vals[i].three = 3;
  }
}

int main(){
     vals = (values*)malloc(sizeof(values) * A_LARGE_NUMBER);
     PopulateWithData(); //populates vals with random data

     values* d_ptr;
     cudaMalloc((void**)&d_ptr, A_LARGE_NUMBER * sizeof(values));
     cudaMemcpy(d_ptr, vals, A_LARGE_NUMBER *sizeof(values),cudaMemcpyHostToDevice);
     cudaMemcpyToSymbol(d_vals, &d_ptr, sizeof(values*));
     dim3    blocksPerGrid(1,1);
     dim3    threadsPerBlock(1, 1);

    myKernel<< <blocksPerGrid, threadsPerBlock >> >();
    cudaDeviceSynchronize();
}
$ nvcc -arch=sm_35 -o t1315 t1315.cu
$ cuda-memcheck ./t1315
========= CUDA-MEMCHECK
1
========= ERROR SUMMARY: 0 errors
$
</code>```

Body:
Suppose I have a struct as follows:

typedef struct values{
int one, int two, int three
} values;

Now, suppose I create an array of values on the host and populate with random data

values vals*;
__device__ values* d_vals;
int main(){
     vals = (values*)malloc(sizeof(values) * A_LARGE_NUMBER);
     PopulateWithDate(); //populates vals with random data
}

Now I want to be able to copy the values to the device such that I can access them in my kernel like so:

__global__ void myKernel(){
     printf("%d", d_vals[0].one);//I don't really want to print, but whenever I try to access I get an error
}

Whatever I try I get an illegal memory access was encountered error.

Here's my current attempt:

int main(){
     vals = (values*)malloc(sizeof(values) * A_LARGE_NUMBER);
     PopulateWithDate(); //populates vals with random data

     values* d_ptr;
     cudaGetSymbolAddress((void**)&d_ptr, d_vals);
     cudaMalloc((void**)&d_ptr, A_LARGE_NUMBER * sizeof(values));

     cudaMemcpyToSymbol(d_ptr, &vals, sizeof(values) * A_LARGE_NUMBER);
     cudaDeviceSynchronize();
     dim3    blocksPerGrid(2, 2);
     dim3    threadsPerBlock(16, 16);

    myKernel<< <blocksPerGrid, threadsPerBlock >> >();
}

Body:
For what you have shown so far, using a __device__ pointer variable just creates needless complexity.  Just use an ordinary dynamic allocation using cudaMalloc for device storage, and otherwise follow an approach similar to any of the CUDA sample codes such as vectorAdd.  Here is an example:

$ cat t1315.cu
#include <stdio.h>
#define A_LARGE_NUMBER 10

struct values{
int one, two, three;
};

values *vals;

__global__ void myKernel(values *d_vals){
     printf("%d\n", d_vals[0].one);
}

void PopulateWithData(){
  for (int i = 0; i < A_LARGE_NUMBER; i++){
    vals[i].one = 1;
    vals[i].two = 2;
    vals[i].three = 3;
  }
}

int main(){
     vals = (values*)malloc(sizeof(values) * A_LARGE_NUMBER);
     PopulateWithData(); //populates vals with random data

     values* d_ptr;
     cudaMalloc((void**)&d_ptr, A_LARGE_NUMBER * sizeof(values));
     cudaMemcpy(d_ptr, vals, A_LARGE_NUMBER *sizeof(values),cudaMemcpyHostToDevice);
     dim3    blocksPerGrid(1,1);
     dim3    threadsPerBlock(1, 1);

    myKernel<< <blocksPerGrid, threadsPerBlock >> >(d_ptr);
    cudaDeviceSynchronize();
}
$ nvcc -arch=sm_35 -o t1315 t1315.cu
$ cuda-memcheck ./t1315
========= CUDA-MEMCHECK
1
========= ERROR SUMMARY: 0 errors
$

You had a variety of other basic (non-CUDA) coding errors in what you had shown, I'm not going to try and run through them all.

If you really want to retain your __device__ pointer variable, and use that to point to the device data (array of structs) then you will still need to use cudaMalloc, and the overall process takes additional steps.  You can follow the example worked out in the answer here.

Following that example, here's a set of changes to the above code to make it work with a __device__ pointer variable instead of a pointer passed as a kernel parameter:

$ cat t1315.cu
#include <stdio.h>
#define A_LARGE_NUMBER 10

struct values{
int one, two, three;
};

values *vals;
__device__ values *d_vals;

__global__ void myKernel(){
     printf("%d\n", d_vals[0].one);
}

void PopulateWithData(){
  for (int i = 0; i < A_LARGE_NUMBER; i++){
    vals[i].one = 1;
    vals[i].two = 2;
    vals[i].three = 3;
  }
}

int main(){
     vals = (values*)malloc(sizeof(values) * A_LARGE_NUMBER);
     PopulateWithData(); //populates vals with random data

     values* d_ptr;
     cudaMalloc((void**)&d_ptr, A_LARGE_NUMBER * sizeof(values));
     cudaMemcpy(d_ptr, vals, A_LARGE_NUMBER *sizeof(values),cudaMemcpyHostToDevice);
     cudaMemcpyToSymbol(d_vals, &d_ptr, sizeof(values*));
     dim3    blocksPerGrid(1,1);
     dim3    threadsPerBlock(1, 1);

    myKernel<< <blocksPerGrid, threadsPerBlock >> >();
    cudaDeviceSynchronize();
}
$ nvcc -arch=sm_35 -o t1315 t1315.cu
$ cuda-memcheck ./t1315
========= CUDA-MEMCHECK
1
========= ERROR SUMMARY: 0 errors
$


问:
Getting typed results from ActiveRecord raw SQL
In Sequel, I can do:

```<code>irb(main):003:0> DB["select false"].get
=> false
</code>```

Which returns a false boolean.  I'd like to be able to do something similar in ActiveRecord:

```<code>irb(main):007:0> ActiveRecord::Base.connection.select_value "select false"
=> "f"
</code>```

As you can see, it returns the string "f". Is there a way to get a false boolean with ActiveRecord? (Similarly, I might be calling a function that returns a timestamptz, an array, etc -- I'd want the returned value to have the correct type)

My use case: I'm calling a database function, want to get back a typed result instead of a string.

答:
Don't have enough reputation points to respond, but Bjorn's answer and associated replies are broken in Rails 5.  This works:</p>

```<code>res = ActiveRecord::Base.connection.select_all(sql)
res.to_a.map{|o| o.each{|k, v| o[k] = res.column_types[k].cast v}}
</code>```

Body:
In Sequel, I can do:

irb(main):003:0> DB["select false"].get
=> false

Which returns a false boolean.  I'd like to be able to do something similar in ActiveRecord:

irb(main):007:0> ActiveRecord::Base.connection.select_value "select false"
=> "f"

As you can see, it returns the string "f". Is there a way to get a false boolean with ActiveRecord? (Similarly, I might be calling a function that returns a timestamptz, an array, etc -- I'd want the returned value to have the correct type)

My use case: I'm calling a database function, want to get back a typed result instead of a string.

Body:
Don't have enough reputation points to respond, but Bjorn's answer and associated replies are broken in Rails 5.  This works:

res = ActiveRecord::Base.connection.select_all(sql)
res.to_a.map{|o| o.each{|k, v| o[k] = res.column_types[k].cast v}}