问:
heap usage for CPS vs non-CPS parsers in Haskell's parsec
I'm trying to write the following parser using parsec:

```<code>manyLength
  :: forall s u m a.
     Monad m
  => ParsecT s u m a -> ParsecT s u m Int
manyLength p = go 0
  where
    go :: Int -> ParsecT s u m Int
    go !i = (p *> go (i + 1)) <|> pure i
</code>```

This is like the many function, but instead of returning [a], it
returns the number of times Parser a succeeds.

This works, but I can't seem to make it run in constant heap space. This makes
sense, since the recursive call to go is not in the tail-call position.

If parsec would export the constructor to ParsecT, it would be possible to
rewrite manyLength in CPS'ed form. This is very similar to the manyAccum
function:

```<code>manyLengthCPS :: forall s u m a. ParsecT s u m a -> ParsecT s u m Int
manyLengthCPS p = ParsecT f
  where
    f
      :: forall b.
         State s u
      -> (Int -> State s u -> ParseError -> m b) -- consumed ok
      -> (ParseError -> m b)                     -- consumed err
      -> (Int -> State s u -> ParseError -> m b) -- empty ok
      -> (ParseError -> m b)                     -- empty err
      -> m b
    f s cok cerr eok _ =
      let walk :: Int -> a -> State s u -> ParseError -> m b
          walk !i _ s' _ =
            unParser p s'
              (walk $ i + 1)            -- consumed-ok
              cerr                      -- consumed-err
              manyLengthCPSErr          -- empty-ok
              (\e -> cok (i + 1) s' e)  -- empty-err
      in unParser p s (walk 0) cerr manyLengthCPSErr (\e -> eok 0 s e)
    {-# INLINE f #-}

manyLengthCPSErr :: Monad m => m a
manyLengthCPSErr =
  fail "manyLengthCPS can't be used on parser that accepts empty input"
</code>```

This manyLengthCPS function does run in constant heap space.

Here is the ParsecT constructor just for completeness:

```<code>newtype ParsecT s u m a = ParsecT
  { unParser
      :: forall b .
         State s u
      -> (a -> State s u -> ParseError -> m b) -- consumed ok
      -> (ParseError -> m b)                   -- consumed err
      -> (a -> State s u -> ParseError -> m b) -- empty ok
      -> (ParseError -> m b)                   -- empty err
      -> m b
  }
</code>```

I also tried to turn manyLengthCPS directly into a non-CPS'ed function using
the low-level mkPT function:

```<code>manyLengthLowLevel
  :: forall s u m a.
     Monad m
  => ParsecT s u m a -> ParsecT s u m Int
manyLengthLowLevel p = mkPT f
  where
    f :: State s u -> m (Consumed (m (Reply s u Int)))
    f parseState = do
      consumed <- runParsecT p parseState
      case consumed of
        Empty mReply -> do
          reply <- mReply
          case reply of
            Ok _ _ _ -> manyLengthErr
            Error parseErr -> pure . Empty . pure $ Ok 0 parseState parseErr
        Consumed mReply -> do
          reply <- mReply
          case reply of
            Ok a newState parseErr -> walk 0 a newState parseErr
            Error parseErr -> pure . Consumed . pure $ Error parseErr
      where
        walk
          :: Int
          -> a
          -> State s u
          -> ParseError
          -> m (Consumed (m (Reply s u Int)))
        walk !i _ parseState' _ = do
          consumed <- runParsecT p parseState'
          case consumed of
            Empty mReply -> do
              reply <- mReply
              case reply of
                Ok _ _ _ -> manyLengthErr
                Error parseErr ->
                  pure . Consumed . pure $ Ok (i + 1) parseState' parseErr
            Consumed mReply -> do
              reply <- mReply
              case reply of
                Ok a newState parseErr -> walk (i + 1) a newState parseErr
                Error parseErr -> pure . Consumed . pure $ Error parseErr

manyLengthErr :: Monad m => m a
manyLengthErr =
  fail "manyLengthLowLevel can't be used on parser that accepts empty input"
</code>```

Just like manyLength, manyLengthLowLevel doesn't run in constant heap space.

Is it possible to write manyLength so it runs in constant heap space even
without writing it in CPS-style? If not, why not? Is there some fundamental
reason that it is possible in CPS-style but not in non-CPS-style?

答:
This runs in constant heap space. The idea is to first try p, and explicitly perform case analysis on the result of its success to decide whether to run go or not, so that go ends up in tail call position.

```<code>manyLength
  :: Monad m
  => ParsecT s u m a -> ParsecT s u m Int
manyLength p = go 0
  where
    go :: Int -> ParsecT s u m Int
    go !i = do
      success <- (p *> pure True) <|> pure False
      if success then go (i+1) else pure i
</code>```

Body:
I'm trying to write the following parser using parsec:

manyLength
  :: forall s u m a.
     Monad m
  => ParsecT s u m a -> ParsecT s u m Int
manyLength p = go 0
  where
    go :: Int -> ParsecT s u m Int
    go !i = (p *> go (i + 1)) <|> pure i

This is like the many function, but instead of returning [a], it
returns the number of times Parser a succeeds.

This works, but I can't seem to make it run in constant heap space. This makes
sense, since the recursive call to go is not in the tail-call position.

If parsec would export the constructor to ParsecT, it would be possible to
rewrite manyLength in CPS'ed form. This is very similar to the manyAccum
function:

manyLengthCPS :: forall s u m a. ParsecT s u m a -> ParsecT s u m Int
manyLengthCPS p = ParsecT f
  where
    f
      :: forall b.
         State s u
      -> (Int -> State s u -> ParseError -> m b) -- consumed ok
      -> (ParseError -> m b)                     -- consumed err
      -> (Int -> State s u -> ParseError -> m b) -- empty ok
      -> (ParseError -> m b)                     -- empty err
      -> m b
    f s cok cerr eok _ =
      let walk :: Int -> a -> State s u -> ParseError -> m b
          walk !i _ s' _ =
            unParser p s'
              (walk $ i + 1)            -- consumed-ok
              cerr                      -- consumed-err
              manyLengthCPSErr          -- empty-ok
              (\e -> cok (i + 1) s' e)  -- empty-err
      in unParser p s (walk 0) cerr manyLengthCPSErr (\e -> eok 0 s e)
    {-# INLINE f #-}

manyLengthCPSErr :: Monad m => m a
manyLengthCPSErr =
  fail "manyLengthCPS can't be used on parser that accepts empty input"

This manyLengthCPS function does run in constant heap space.

Here is the ParsecT constructor just for completeness:

newtype ParsecT s u m a = ParsecT
  { unParser
      :: forall b .
         State s u
      -> (a -> State s u -> ParseError -> m b) -- consumed ok
      -> (ParseError -> m b)                   -- consumed err
      -> (a -> State s u -> ParseError -> m b) -- empty ok
      -> (ParseError -> m b)                   -- empty err
      -> m b
  }

I also tried to turn manyLengthCPS directly into a non-CPS'ed function using
the low-level mkPT function:

manyLengthLowLevel
  :: forall s u m a.
     Monad m
  => ParsecT s u m a -> ParsecT s u m Int
manyLengthLowLevel p = mkPT f
  where
    f :: State s u -> m (Consumed (m (Reply s u Int)))
    f parseState = do
      consumed <- runParsecT p parseState
      case consumed of
        Empty mReply -> do
          reply <- mReply
          case reply of
            Ok _ _ _ -> manyLengthErr
            Error parseErr -> pure . Empty . pure $ Ok 0 parseState parseErr
        Consumed mReply -> do
          reply <- mReply
          case reply of
            Ok a newState parseErr -> walk 0 a newState parseErr
            Error parseErr -> pure . Consumed . pure $ Error parseErr
      where
        walk
          :: Int
          -> a
          -> State s u
          -> ParseError
          -> m (Consumed (m (Reply s u Int)))
        walk !i _ parseState' _ = do
          consumed <- runParsecT p parseState'
          case consumed of
            Empty mReply -> do
              reply <- mReply
              case reply of
                Ok _ _ _ -> manyLengthErr
                Error parseErr ->
                  pure . Consumed . pure $ Ok (i + 1) parseState' parseErr
            Consumed mReply -> do
              reply <- mReply
              case reply of
                Ok a newState parseErr -> walk (i + 1) a newState parseErr
                Error parseErr -> pure . Consumed . pure $ Error parseErr

manyLengthErr :: Monad m => m a
manyLengthErr =
  fail "manyLengthLowLevel can't be used on parser that accepts empty input"

Just like manyLength, manyLengthLowLevel doesn't run in constant heap space.

Is it possible to write manyLength so it runs in constant heap space even
without writing it in CPS-style? If not, why not? Is there some fundamental
reason that it is possible in CPS-style but not in non-CPS-style?

Body:
This runs in constant heap space. The idea is to first try p, and explicitly perform case analysis on the result of its success to decide whether to run go or not, so that go ends up in tail call position.

manyLength
  :: Monad m
  => ParsecT s u m a -> ParsecT s u m Int
manyLength p = go 0
  where
    go :: Int -> ParsecT s u m Int
    go !i = do
      success <- (p *> pure True) <|> pure False
      if success then go (i+1) else pure i


来源: stackexchange

问:
Piwik: how to get a list of unique domains tracked in one site
Someone had the bad idea to put the same Piwik tracking code on many different domains.

How can I compile a list of unique domain names out of Piwik?

答:
I got this answer via Twitter:

The full URL is tracked and visible in visitlog. To block those unwanted requests check this faq: https://piwik.org/faq/how-to/faq_21077/

Source: https://twitter.com/richardmastop/status/846772768922353664

ContentLicense: CC BY-SA 3.0


问:
Refreshing browser web-page not load in ui-router when locationProvider used
When I directly refresh the browser using F5 or directly hitting the url,
page not load but when I click on the button then the page gets load

I am using like this

Enable HTML5Mode using $locationProvider

```<code>var routerApp = angular.module('myApp', ['ui.router','ngCookies']);
routerApp.config(function($locationProvider){
    $locationProvider.html5Mode({
          enabled: true
    })
});
</code>```

I Added the following code to the  of your HTML file:

```<code><base href="/">
</code>```

or Simply using Syntax like that

```<code>$locationProvider.html5Mode({
          enabled: true,
          requireBase: false
    })
</code>```

I find that this is already issue on https://github.com/angular-ui/ui-router/issues/105

Can someone knows how to solve this ?
When I am not using $locationProvider for omitting '#' then it is working fine with refreshing too

答:
Try</p>

```<code>$locationProvider.html5Mode({
    enabled: true,
    requireBase: false
})
</code>```

Body:
When I directly refresh the browser using F5 or directly hitting the url,
page not load but when I click on the button then the page gets load

I am using like this

Enable HTML5Mode using $locationProvider

var routerApp = angular.module('myApp', ['ui.router','ngCookies']);
routerApp.config(function($locationProvider){
    $locationProvider.html5Mode({
          enabled: true
    })
});

I Added the following code to the  of your HTML file:

<base href="/">

or Simply using Syntax like that

$locationProvider.html5Mode({
          enabled: true,
          requireBase: false
    })

I find that this is already issue on https://github.com/angular-ui/ui-router/issues/105

Can someone knows how to solve this ?
When I am not using $locationProvider for omitting '#' then it is working fine with refreshing too

Body:
Try

$locationProvider.html5Mode({
    enabled: true,
    requireBase: false
})


问:
Can't enable focus selector with anchors in css in Safari
I'm aware that certain elements can't accept a focus selector, such as list elements, but I thought that anchors were fine. Using the following code (I'm creating a pure css responsive drop-down menu), I can't make the hidden ul appear when clicking the anchor.

HTML:

```<code><ul>
  <li class="primarylist">
    <a href="#" class='category1anchor'>Text</a>
    <ul class="menudrop">
      <li class="secondarylist">One</li>
      <li class="secondarylist">Two</li>
      <li class="secondarylist">Three</li>
    </ul>
  </li>
</ul>
</code>```

CSS:

```<code>ul.menudrop {
  display: none;
  background-color: white;
}
li.primarylist a:focus + ul.menudrop {
  display: block;
}
</code>```

jsFiddle:
https://jsfiddle.net/kx0kex7x/

Change the jsFiddle selector from focus to hover, and it works perfectly, leaving me without any reason to doubt my syntax is correct. Using active only displays the ul for the duration of the mousedown. Any pointers? (I'm on Safari 10. Seems to work in the latest Chrome and FF fine).

Update

I've tried using the target selector with partial success. If I change my a.categor1anchor links to match newly created unique ids for each ul.menudrop, I can make the ul.menudrop appear on clicking the anchor. However, this is a responsive design and I can't seem to remove the target selector at other page sizes. For example, at a larger page size, I use the hover selector instead, but the last targeted ul.menudrop from a smaller screensize remains open at larger screen sizes. I can't see any way to clear target selectors for responsive designs. Inherit and Initial displays don't affect it.

答:
Seems like that anchor tags in Safari need to have tabindex set in order to receive focus.

ul.menudrop {
  display: none;
  background-color: white;
}
li.primarylist a:focus + ul.menudrop {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li class="primarylist">
    Text
    <ul class="menudrop">
      <li class="secondarylist">One</li>
      <li class="secondarylist">Two</li>
      <li class="secondarylist">Three</li>
    </ul>
  </li>
</ul></code>```

https://jsfiddle.net/VilleKoo/dhpom1uw/

Body:
I'm aware that certain elements can't accept a focus selector, such as list elements, but I thought that anchors were fine. Using the following code (I'm creating a pure css responsive drop-down menu), I can't make the hidden ul appear when clicking the anchor.

HTML:

    Text

One

Two

Three

CSS:

ul.menudrop {
  display: none;
  background-color: white;
}
li.primarylist a:focus + ul.menudrop {
  display: block;
}

jsFiddle:
https://jsfiddle.net/kx0kex7x/

Change the jsFiddle selector from focus to hover, and it works perfectly, leaving me without any reason to doubt my syntax is correct. Using active only displays the ul for the duration of the mousedown. Any pointers? (I'm on Safari 10. Seems to work in the latest Chrome and FF fine).

Update

I've tried using the target selector with partial success. If I change my a.categor1anchor links to match newly created unique ids for each ul.menudrop, I can make the ul.menudrop appear on clicking the anchor. However, this is a responsive design and I can't seem to remove the target selector at other page sizes. For example, at a larger page size, I use the hover selector instead, but the last targeted ul.menudrop from a smaller screensize remains open at larger screen sizes. I can't see any way to clear target selectors for responsive designs. Inherit and Initial displays don't affect it.

Body:
Seems like that anchor tags in Safari need to have tabindex set in order to receive focus.

ul.menudrop {
  display: none;
  background-color: white;
}
li.primarylist a:focus + ul.menudrop {
  display: block;
}

<ul>
  <li class="primarylist">
    <a href="#" class='category1anchor' tabindex="0">Text</a>
    <ul class="menudrop">
      <li class="secondarylist">One</li>
      <li class="secondarylist">Two</li>
      <li class="secondarylist">Three</li>
    </ul>
  </li>
</ul>

https://jsfiddle.net/VilleKoo/dhpom1uw/


问:
Set null as empty string value for input field
I have an input field mapped to an entity in my controller with a ngModel 2-way binding:

<input type="text" [(ngModel)]="entity.one_attribute" />
```

<p>When I initialize my controller, I have this entity:</p>

<pre class="lang-typescript prettyprint-override"><code>{ one_attribute: null }
</code>```

If a user starts to fill in the field but does not submit the form immediately and empties the field, my entity is updated to become:

{ one_attribute: "" }
```

Is it possible to define that empty string should be changed to null automatically?

答:
After viewing a bunch of answers about ValueAccessor and HostListener solutions, I made a working solution (tested with RC1):

import {NgControl} from "@angular/common";
import {Directive, ElementRef, HostListener} from "@angular/core";

@Directive({
  selector: 'input[nullValue]'
})
export class NullDefaultValueDirective {
  constructor(private el: ElementRef, private control: NgControl) {}

  @HostListener('input', ['$event.target'])
  onEvent(target: HTMLInputElement){
    this.control.viewToModelUpdate((target.value === '') ? null : target.value);
  }
}
```

<p>Then use it that way on your input fields:</p>

<pre class="lang-html prettyprint-override"><code><input [(ngModel)]="bindedValue" nullValue/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an input field mapped to an entity in my controller with a ngModel 2-way binding:

<input type="text" [(ngModel)]="entity.one_attribute" />

When I initialize my controller, I have this entity:

{ one_attribute: null }

If a user starts to fill in the field but does not submit the form immediately and empties the field, my entity is updated to become:

{ one_attribute: "" }

Is it possible to define that empty string should be changed to null automatically?

Body:
After viewing a bunch of answers about ValueAccessor and HostListener solutions, I made a working solution (tested with RC1):

import {NgControl} from "@angular/common";
import {Directive, ElementRef, HostListener} from "@angular/core";

@Directive({
  selector: 'input[nullValue]'
})
export class NullDefaultValueDirective {
  constructor(private el: ElementRef, private control: NgControl) {}

  @HostListener('input', ['$event.target'])
  onEvent(target: HTMLInputElement){
    this.control.viewToModelUpdate((target.value === '') ? null : target.value);
  }
}

Then use it that way on your input fields:

<input [(ngModel)]="bindedValue" nullValue/>


问:
Bootstrap - Auto expanding container, row & row columns' width with content
I have following html:

```<code><div class="container">
 <div class="row">
    <div class="col-md-6">
        <ul>
            <li>Long Content 1<li>
        </ul>
    </div>
    <div class="col-md-6">
        <ul>
            <li>Long Content 2<li>
        </ul>
    </div>
 </div>
</div>
</code>```

I will be adding dynamic content into each ul element. I want col-md-* elements and their parents to expand  themselves horizontally with the content, even if they horizontally overflow the screen window. I don't mind horizontal scrolling on the screen. How can I achieve this?

答: Replace containerto container-fluid

Body:
I have following html:

Long Content 1

Long Content 2

I will be adding dynamic content into each ul element. I want col-md-* elements and their parents to expand  themselves horizontally with the content, even if they horizontally overflow the screen window. I don't mind horizontal scrolling on the screen. How can I achieve this?

Body: Replace containerto container-fluid


问:
Xcode 8.2 Code Completion Not Working
For some reason, in Xcode 8.2 my code completion has stopped working. I have cleaned my product, restarted Xcode, restarted my computer, and deleted the derived data, and still no luck. I have submitted this to Apple Support. Has anyone run into this before and been able to fix it?</p>

答: Just restarting Xcode worked for me.</p>

Title: Xcode 8.2 Code Completion Not Working

Body: Just restarting Xcode worked for me.


问:
Using delimiter on a text file
My Question is how i can use the delimiter without jumping to the next line

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadTextFile
{
    public static void main(String[] args) throws FileNotFoundException
    {
        Scanner read = new Scanner(new File("read.txt"));
        read.useDelimiter(";");

        while (read.hasNext()) {
            System.out.println(read.next());
        }
    }
}
</code>```

My text file:

```
1;1;1;1
1;1;1;1
1;1;1;1
1;1;1;1
1;hallo;1;1
1;1;1;1
1;wie;1;1
1;1;1;1
1;1;1;1
1;1;1;1
1;gehts;1;1
1;1;1;1
1;1;1;1
1;1;1;1
1;1;1;1
```

My output:

```
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
```

I want my output like a table with more columns like in the text file.

答:
Remove read.useDelimiter(";"); and use read.next().split(";"); instead.

My solution could be more simple with replacebut you asked for the output to be in columns, so I thought this was what you meant with it.

```<code>Scanner read = new Scanner(new File("read.txt"));

  while(read.hasNext()){

    String[] line = read.next().split(";");
    for(String s : line){
        System.out.print(s + "\t");
    }
        System.out.println();
  }
</code>```

Output:

```<code>1   1   1   1
1   EDC 1   1
1   1   1   1
1   AVC 1   1
1   1   1   1
1   1   1   1
</code>```

If you do note care about formatting the output, then you might want to use:

```<code>Scanner read = new Scanner(new File("read.txt"));
while(read.hasNext()){
  System.out.println(read.next().replace(";", ""));
}
</code>```

Output:

```<code>1111
1EDC11
1111
1AVC11
1111
1111
</code>```

Title: Using delimiter on a text file

Body:
My Question is how i can use the delimiter without jumping to the next line

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadTextFile
{
    public static void main(String[] args) throws FileNotFoundException
    {
        Scanner read = new Scanner(new File("read.txt"));
        read.useDelimiter(";");

        while (read.hasNext()) {
            System.out.println(read.next());
        }
    }
}

My text file:

1;1;1;1
1;1;1;1
1;1;1;1
1;1;1;1
1;hallo;1;1
1;1;1;1
1;wie;1;1
1;1;1;1
1;1;1;1
1;1;1;1
1;gehts;1;1
1;1;1;1
1;1;1;1
1;1;1;1
1;1;1;1

My output:

1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1

I want my output like a table with more columns like in the text file.

Body:
Remove read.useDelimiter(";"); and use read.next().split(";"); instead.

My solution could be more simple with replacebut you asked for the output to be in columns, so I thought this was what you meant with it.

Scanner read = new Scanner(new File("read.txt"));

  while(read.hasNext()){

    String[] line = read.next().split(";");
    for(String s : line){
        System.out.print(s + "\t");
    }
        System.out.println();
  }

Output:

1   1   1   1
1   EDC 1   1
1   1   1   1
1   AVC 1   1
1   1   1   1
1   1   1   1

If you do note care about formatting the output, then you might want to use:

Scanner read = new Scanner(new File("read.txt"));
while(read.hasNext()){
  System.out.println(read.next().replace(";", ""));
}

Output:

1111
1EDC11
1111
1AVC11
1111
1111


问:
What is the typical speed that PHP connects to MySQL?
Say I have very standard mysql connection code:

```<code>$dbhost = '192.168.1.99';
$dbuser = 'dbuser';
$dbpass = 'dbuserpass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'mydb';
mysql_select_db($dbname);
</code>```

This would connect from the web server to the database server (say the web server is at 192.168.1.98 or something). Typically, how long would the above code run? Currently, I'm seeing about 2 seconds. Is that slow?

答: Do you have lots of tables?  It may be spending time looking around after connecting.  Is the command line mysql client slow too?  Is it fast if you're connecting from localhost?</p>

Body:
Say I have very standard mysql connection code:

$dbhost = '192.168.1.99';
$dbuser = 'dbuser';
$dbpass = 'dbuserpass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'mydb';
mysql_select_db($dbname);

This would connect from the web server to the database server (say the web server is at 192.168.1.98 or something). Typically, how long would the above code run? Currently, I'm seeing about 2 seconds. Is that slow?

ContentLicense: CC BY-SA 2.5


答:
You need to change your Delimiter to \n. Using ; means that every entry is a number between those ;.

try this

```<code>public class Readtextfile {

    public static void main(String[] args) throws FileNotFoundException {

            Scanner read = new Scanner(new File("read.txt"));
            read.useDelimiter("\n"); // It is the default delimiter, you can skip this line.

            while(read.hasNext()){
                 String str= read.next().replaceAll(";","");
                 System.out.println(str));

            }

        }

    }
</code>```

Otherwise try to read by line and then use split(";") to construct your output.

Title: Using delimiter on a text file

Body:
You need to change your Delimiter to \n. Using ; means that every entry is a number between those ;.

try this

public class Readtextfile {

    public static void main(String[] args) throws FileNotFoundException {

            Scanner read = new Scanner(new File("read.txt"));
            read.useDelimiter("\n"); // It is the default delimiter, you can skip this line.

            while(read.hasNext()){
                 String str= read.next().replaceAll(";","");
                 System.out.println(str));

            }

        }

    }

Otherwise try to read by line and then use split(";") to construct your output.


问:
Show current time on output window in Visual Studio 2013 using C
I am trying to display current time on output window of Visual Studio. I need it for debugging purpose. Since printf() output doesn't print to output window of Visual Studio, i need to use OutputDebugString().

Code compiles correctly but output doesn't come out correctly. Can someone help me out here ? Thanks !

```<code>char buff[100];
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);

sprintf(buff, "[%d %d %d %d:%d:%d]", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
OutputDebugString(LPCWSTR(buff));
</code>```

OUTPUT Window of Visual Studio prints :

```<code>?‹???????]
</code>```

Expected: Date and time is printed correctly.

答:
I know, the comment from Michael has already solved your problem. But, you should know the cause of problem to avoid making the same mistake again in future. So, this answer summarizes that.

First of all, some basics::
A and W in OutputDebugStringA & OutputDebugStringW, respectively stands for Ansi and Wide characters.

Ansi chars take upto 1 byte of memory like char and Wide chars take 2 bytes of memory like wchar_t.

For more reference, you can look here:: Difference between char* and wchar_t*

Now, when you have already defined buff as char, then why are you type-casting it to LPCWSTR. For more reference on LPCWSTR, see this:: What does LPCWSTR stand for and how should it be handled with?

So, basically, you should be calling OutputDebugStringA(buff).

Another solution is, define buff as wide char array,

```<code>wchar_t buff[100];
wsprintf(buff, L"[%d %d %d %d:%d:%d]", timeinfo->tm_mday,
     timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour,
     timeinfo->tm_min, timeinfo->tm_sec);
OutputDebugStringW(buff);
</code>```

Body:
I am trying to display current time on output window of Visual Studio. I need it for debugging purpose. Since printf() output doesn't print to output window of Visual Studio, i need to use OutputDebugString().

Code compiles correctly but output doesn't come out correctly. Can someone help me out here ? Thanks !

char buff[100];
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);

sprintf(buff, "[%d %d %d %d:%d:%d]", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
OutputDebugString(LPCWSTR(buff));

OUTPUT Window of Visual Studio prints :

?‹???????]

Expected: Date and time is printed correctly.

Body:
I know, the comment from Michael has already solved your problem. But, you should know the cause of problem to avoid making the same mistake again in future. So, this answer summarizes that.

First of all, some basics::
A and W in OutputDebugStringA & OutputDebugStringW, respectively stands for Ansi and Wide characters.

Ansi chars take upto 1 byte of memory like char and Wide chars take 2 bytes of memory like wchar_t.

For more reference, you can look here:: Difference between char* and wchar_t*

Now, when you have already defined buff as char, then why are you type-casting it to LPCWSTR. For more reference on LPCWSTR, see this:: What does LPCWSTR stand for and how should it be handled with?

So, basically, you should be calling OutputDebugStringA(buff).

Another solution is, define buff as wide char array,

wchar_t buff[100];
wsprintf(buff, L"[%d %d %d %d:%d:%d]", timeinfo->tm_mday,
     timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour,
     timeinfo->tm_min, timeinfo->tm_sec);
OutputDebugStringW(buff);


问:
How do I make builds public in buildbot
I have a buildbot working and have added basic authentication following "Setting Authorized Web Users" from the manual http://docs.buildbot.net/current/tutorial/tour.html. I was hoping to restrict people who could trigger a new build.

But now the web interface shows no builds at all without login. How can I make the builds public?

My current config looks like this, minus the line giving the password details.

```<code>c['www']['authz'] = util.Authz(
        allowRules = [
                        util.AnyControlEndpointMatcher(role="admins")
                    ],
        roleMatchers = [
                        util.RolesFromUsername(roles=['admins'], usernames=['xxx'])
                    ]
)
</code>```

答:
You need to configure authentication and authorization.

Probably the simple example config is enough for your simple example
http://docs.buildbot.net/latest/manual/cfg-www.html#example-configs

Title: How do I make builds public in buildbot

Body:
I have a buildbot working and have added basic authentication following "Setting Authorized Web Users" from the manual http://docs.buildbot.net/current/tutorial/tour.html. I was hoping to restrict people who could trigger a new build.

But now the web interface shows no builds at all without login. How can I make the builds public?

My current config looks like this, minus the line giving the password details.

c['www']['authz'] = util.Authz(
        allowRules = [
                        util.AnyControlEndpointMatcher(role="admins")
                    ],
        roleMatchers = [
                        util.RolesFromUsername(roles=['admins'], usernames=['xxx'])
                    ]
)


问:
Add custom atrribute to json response
I have model something like that with custom attribute

```<code>class MyModel extends Model
{
    public function getExtraAttribute(){
        return 'some string'; //etc.
    }
}
</code>```

And for controller method i have this

```<code>return MyModel::where('user_id', Auth::user()->id)->get();
</code>```

But i don't see 'extra' attribute on json response

P.s. extra isn't column from database.

答:
Add the attribute to $appends.

```<code>class MyModel extends Model {
    ...
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['extra'];
    ...
}
</code>```

Title: Add custom atrribute to json response

Body:
I have model something like that with custom attribute

class MyModel extends Model
{
    public function getExtraAttribute(){
        return 'some string'; //etc.
    }
}

And for controller method i have this

return MyModel::where('user_id', Auth::user()->id)->get();

But i don't see 'extra' attribute on json response

P.s. extra isn't column from database.

Body:
Add the attribute to $appends.

class MyModel extends Model {
    ...
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['extra'];
    ...
}


问:
Change innertext of element dynamically inside for loop of a function
Issue : Upon entering a higher number like 10000, innertext of the new paragraph element is updated only after the for loop ends. Please help to make the innertext get updated for each number.

The increment function is called when an onchange event happens after sending a number as a input to the input element.

JAVASCRIPT :

```<code>function increment() {
    var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
    var stat = document.createElement("p");
    stat.id = "current_status";
    stat.innerText = "";
    document.body.appendChild(stat);
    stat.style.display = "block";
    for (g = 1; g < count; g++) {
        stat.innerText = Number(g + 1) + " out of " + count + " records have been processed";
    }
}
</code>```

答:
The DOM doesn't redraw until the executing thread is free. You need to introduce async delays to your code to see a progressive update.

function increment() {
  var count = document.getElementById('ac_count').value;
  var stat = document.createElement("p");
  stat.id = "current_status";
  document.body.appendChild(stat);

  var g = 1
  var itvl = setInterval(function() {
    update(g);
    g += Math.floor(Math.random() * 20) + 1
    if (g >= count) {
      clearInterval(itvl);
      update(count);
    }
  }, 10)

  function update(g) {
    stat.textContent = g + " out of " + count + " records have been processed";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=number value=10000 id=ac_count>
<button onclick="increment()">CLICK ME</button></code>```

Body:
Issue : Upon entering a higher number like 10000, innertext of the new paragraph element is updated only after the for loop ends. Please help to make the innertext get updated for each number.

The increment function is called when an onchange event happens after sending a number as a input to the input element.

JAVASCRIPT :

function increment() {
    var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
    var stat = document.createElement("p");
    stat.id = "current_status";
    stat.innerText = "";
    document.body.appendChild(stat);
    stat.style.display = "block";
    for (g = 1; g < count; g++) {
        stat.innerText = Number(g + 1) + " out of " + count + " records have been processed";
    }
}

Body:
The DOM doesn't redraw until the executing thread is free. You need to introduce async delays to your code to see a progressive update.

function increment() {
  var count = document.getElementById('ac_count').value;
  var stat = document.createElement("p");
  stat.id = "current_status";
  document.body.appendChild(stat);

  var g = 1
  var itvl = setInterval(function() {
    update(g);
    g += Math.floor(Math.random() * 20) + 1
    if (g >= count) {
      clearInterval(itvl);
      update(count);
    }
  }, 10)

  function update(g) {
    stat.textContent = g + " out of " + count + " records have been processed";
  }
}

<input type=number value=10000 id=ac_count>
<button onclick="increment()">CLICK ME</button>


问:
Sun (oracle) Java on new projects

Possible Duplicate:

  Are there reliable alternatives to Sun's JVM for desktop & enterprise development?

I'm considering a large long term Java project.

I'm seeing some negative signs in the Oracle takeover of Sun and concerned that this may affect the viability of using Sun (Oracle) on the project.

Should I consider using another Java implementation base?  If so, what looks good long term?

答:
I think whatever you think your fears are, they're unfounded.

First, if your long term project is relying on too-be-released software (i.e. stuff that isn't even out yet, like JDK 7, 8, and whatever features they may or may not bring), then you need to re-evaluate that part of your plan.

If you expect to have a reliable Java 6 implementation in the long term, then you probably shouldn't worry.

Java 6 is solid, reliable, and it's not going away. AT A MINIMUM, Oracle, as a company, is going to continue to invest and develop its applications servers and middle ware, all of which rely on Java.

It is in NO ONES interest to "cripple" Java. While you may not get "free" tech support from Oracle, Oracle will continue to provide and maintain freely available for production, and viable JVMs for the platforms they support now (notably x86 and SPARC), and they've already agreed to pick up the JVM for Mac OS.

So, in that sense, I don't see Java 6 suddenly (i.e. next 5 years) going away. Support may be deprecated and maintenance stopped to a point in lieu of J7 or J8. Consider the legs Java 5 still have, and even Java 4 in some places, still today. But I see no foreseeable end of life for Java as a whole.

Is any of this FACT? Do I have public or secret Oracle memo's committing to any of this? No.

I have no crystal balls.

But I don't see the future of Java as cloudy at all. Stirred up a bit, sure, but not cloudy. In the conservative world of corporate IT, stability is greatly treasured. Status Quo A Number One. The only thing that will "hurt Java" is something else entirely, it sure won't be Oracle.

Title: Sun (oracle) Java on new projects


问:
I try to use Kivy in nuke scripts edit but it casts 'unable to find any valuable Text provider at all'
Here is my env setting

```<code>set NUKE_PATH=T:\___TEMP\Pipeline\nuke\plugins
set PYTHONPATH=C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg;
               C:\Python27\lib\site-packages\pillow-4.0.0-py2.7-win-amd64.egg;
               C:\Windows\SYSTEM32\python27.zip;
               C:\Python27\lib;
               C:\Python27\lib\plat-win;
               C:\Python27\lib\lib-tk;
               C:\Python27\lib\site-packages;
               C:\Python27\lib\site-packages\win32;
               C:\Python27\lib\site-packages\win32\lib;
               C:\Python27\lib\site-packages\Pythonwin;
               C:\Python27\lib\site-packages\kivy\modules;
               C:\Users\Isaac\.kivy\mods
</code>```

And it always says

```<code>  sdl2  -ImportError:DLL load failed
  pil -ImportError:DLL load failed
  unable to find any valuable Text provider at all Abort
</code>```

When I type

```<code>from kivy.uix.button import Button
</code>```

The nuke just shut down

these code works fine in my Pycharm.
Have you seen this problem before?
Does Nuke scripts edit has any special rules about finding env?

答:
Kivy deps add their folders to the PATH, so I presume Nuke needs the same thing, therefore add their path manually:

```<code>set NUKE_PATH=%NUKE_PATH%;<python dir>\share\<dep>\bin
</code>```

replace with python folder and dependency names (multiple folders).

Body:
Here is my env setting

set NUKE_PATH=T:\___TEMP\Pipeline\nuke\plugins
set PYTHONPATH=C:\Python27\lib\site-packages\pip-9.0.1-py2.7.egg;
               C:\Python27\lib\site-packages\pillow-4.0.0-py2.7-win-amd64.egg;
               C:\Windows\SYSTEM32\python27.zip;
               C:\Python27\lib;
               C:\Python27\lib\plat-win;
               C:\Python27\lib\lib-tk;
               C:\Python27\lib\site-packages;
               C:\Python27\lib\site-packages\win32;
               C:\Python27\lib\site-packages\win32\lib;
               C:\Python27\lib\site-packages\Pythonwin;
               C:\Python27\lib\site-packages\kivy\modules;
               C:\Users\Isaac\.kivy\mods

And it always says

  sdl2  -ImportError:DLL load failed
  pil -ImportError:DLL load failed
  unable to find any valuable Text provider at all Abort

When I type

from kivy.uix.button import Button

The nuke just shut down

these code works fine in my Pycharm.
Have you seen this problem before?
Does Nuke scripts edit has any special rules about finding env?

Body:
Kivy deps add their folders to the PATH, so I presume Nuke needs the same thing, therefore add their path manually:

set NUKE_PATH=%NUKE_PATH%;<python dir>\share\<dep>\bin

replace with python folder and dependency names (multiple folders).


问:
Problems when scaling a YUV image using libyuv library
I'm developing a camera app based on Camera API 2 and I have found several problems using the libyuv.
I want to convert YUV_420_888 images retrieved from a ImageReader, but I'm having some problems with scaling in a reprocessable surface.

In essence: Images come out with tones of green instead of having the corresponding tones (I'm exporting the .yuv files and checking them using http://rawpixels.net/).

You can see an input example here:

And what I get after I perform scaling:

I think I am doing something wrong with strides, or providing an invalid YUV format (maybe I have to transform the image to another format?). However, I can't figure out where is the error since I don't know how to correlate the green color to the scaling algorithm.

This is the conversion code I am using, you can ignore the return NULL as there is further processing that is not related to the problem.

```<code>#include <jni.h>
#include <stdint.h>
#include <android/log.h>
#include <inc/libyuv/scale.h>
#include <inc/libyuv.h>
#include <stdio.h>

#define  LOG_TAG    "libyuv-jni"

#define unused(x) UNUSED_ ## x __attribute__((__unused__))
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS_)

struct YuvFrame {
    int width;
    int height;
    uint8_t *data;
    uint8_t *y;
    uint8_t *u;
    uint8_t *v;
};

static struct YuvFrame i420_input_frame;
static struct YuvFrame i420_output_frame;

extern "C" {

JNIEXPORT jbyteArray JNICALL
Java_com_android_camera3_camera_hardware_session_output_photo_yuv_YuvJniInterface_scale420YuvByteArray(
        JNIEnv *env, jclass /*clazz*/, jbyteArray yuvByteArray_, jint src_width, jint src_height,
        jint out_width, jint out_height) {

    jbyte *yuvByteArray = env->GetByteArrayElements(yuvByteArray_, NULL);

    //Get input and output length
    int input_size = env->GetArrayLength(yuvByteArray_);
    int out_size = out_height * out_width;

    //Generate input frame
    i420_input_frame.width = src_width;
    i420_input_frame.height = src_height;
    i420_input_frame.data = (uint8_t *) yuvByteArray;
    i420_input_frame.y = i420_input_frame.data;
    i420_input_frame.u = i420_input_frame.y + input_size;
    i420_input_frame.v = i420_input_frame.u + input_size / 4;

    //Generate output frame
    free(i420_output_frame.data);
    i420_output_frame.width = out_width;
    i420_output_frame.height = out_height;
    i420_output_frame.data = new unsigned char[out_size * 3 / 2];
    i420_output_frame.y = i420_output_frame.data;
    i420_output_frame.u = i420_output_frame.y + out_size;
    i420_output_frame.v = i420_output_frame.u + out_size / 4;
    libyuv::FilterMode mode = libyuv::FilterModeEnum::kFilterBilinear;

    int result = I420Scale(i420_input_frame.y, i420_input_frame.width,
                           i420_input_frame.u, i420_input_frame.width / 2,
                           i420_input_frame.v, i420_input_frame.width / 2,
                           i420_input_frame.width, i420_input_frame.height,
                           i420_output_frame.y, i420_output_frame.width,
                           i420_output_frame.u, i420_output_frame.width / 2,
                           i420_output_frame.v, i420_output_frame.width / 2,
                           i420_output_frame.width, i420_output_frame.height,
                           mode);
    LOGD("Image result %d", result);
    env->ReleaseByteArrayElements(yuvByteArray_, yuvByteArray, 0);
    return NULL;
}
</code>```

答:
gmetax is almost correct.

You are using the size of the entire array where you should be using the size of the Y component, which is src_width * src_height.

gmetax's answer is wrong in that he has put y_size in place of out_size when defining the output frame. The correct code snippet, I believe, would look like:

```<code>//Get input and output length
int input_size = env->GetArrayLength(yuvByteArray_);
int y_size = src_width * src_height;
int out_size = out_height * out_width;

//Generate input frame
i420_input_frame.width = src_width;
i420_input_frame.height = src_height;
i420_input_frame.data = (uint8_t *) yuvByteArray;
i420_input_frame.y = i420_input_frame.data;
i420_input_frame.u = i420_input_frame.y + y_size;
i420_input_frame.v = i420_input_frame.u + y_size / 4;

//Generate output frame
free(i420_output_frame.data);
i420_output_frame.width = out_width;
i420_output_frame.height = out_height;
i420_output_frame.data = new unsigned char[out_size * 3 / 2];
i420_output_frame.y = i420_output_frame.data;
i420_output_frame.u = i420_output_frame.y + out_size;
i420_output_frame.v = i420_output_frame.u + out_size / 4;
</code>```

Body:
I'm developing a camera app based on Camera API 2 and I have found several problems using the libyuv.
I want to convert YUV_420_888 images retrieved from a ImageReader, but I'm having some problems with scaling in a reprocessable surface.

In essence: Images come out with tones of green instead of having the corresponding tones (I'm exporting the .yuv files and checking them using http://rawpixels.net/).

You can see an input example here:

And what I get after I perform scaling:

I think I am doing something wrong with strides, or providing an invalid YUV format (maybe I have to transform the image to another format?). However, I can't figure out where is the error since I don't know how to correlate the green color to the scaling algorithm.

This is the conversion code I am using, you can ignore the return NULL as there is further processing that is not related to the problem.

#include <jni.h>
#include <stdint.h>
#include <android/log.h>
#include <inc/libyuv/scale.h>
#include <inc/libyuv.h>
#include <stdio.h>

#define  LOG_TAG    "libyuv-jni"

#define unused(x) UNUSED_ ## x __attribute__((__unused__))
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS_)

struct YuvFrame {
    int width;
    int height;
    uint8_t *data;
    uint8_t *y;
    uint8_t *u;
    uint8_t *v;
};

static struct YuvFrame i420_input_frame;
static struct YuvFrame i420_output_frame;

extern "C" {

JNIEXPORT jbyteArray JNICALL
Java_com_android_camera3_camera_hardware_session_output_photo_yuv_YuvJniInterface_scale420YuvByteArray(
        JNIEnv *env, jclass /*clazz*/, jbyteArray yuvByteArray_, jint src_width, jint src_height,
        jint out_width, jint out_height) {

    jbyte *yuvByteArray = env->GetByteArrayElements(yuvByteArray_, NULL);

    //Get input and output length
    int input_size = env->GetArrayLength(yuvByteArray_);
    int out_size = out_height * out_width;

    //Generate input frame
    i420_input_frame.width = src_width;
    i420_input_frame.height = src_height;
    i420_input_frame.data = (uint8_t *) yuvByteArray;
    i420_input_frame.y = i420_input_frame.data;
    i420_input_frame.u = i420_input_frame.y + input_size;
    i420_input_frame.v = i420_input_frame.u + input_size / 4;

    //Generate output frame
    free(i420_output_frame.data);
    i420_output_frame.width = out_width;
    i420_output_frame.height = out_height;
    i420_output_frame.data = new unsigned char[out_size * 3 / 2];
    i420_output_frame.y = i420_output_frame.data;
    i420_output_frame.u = i420_output_frame.y + out_size;
    i420_output_frame.v = i420_output_frame.u + out_size / 4;
    libyuv::FilterMode mode = libyuv::FilterModeEnum::kFilterBilinear;

    int result = I420Scale(i420_input_frame.y, i420_input_frame.width,
                           i420_input_frame.u, i420_input_frame.width / 2,
                           i420_input_frame.v, i420_input_frame.width / 2,
                           i420_input_frame.width, i420_input_frame.height,
                           i420_output_frame.y, i420_output_frame.width,
                           i420_output_frame.u, i420_output_frame.width / 2,
                           i420_output_frame.v, i420_output_frame.width / 2,
                           i420_output_frame.width, i420_output_frame.height,
                           mode);
    LOGD("Image result %d", result);
    env->ReleaseByteArrayElements(yuvByteArray_, yuvByteArray, 0);
    return NULL;
}

Body:
gmetax is almost correct.

You are using the size of the entire array where you should be using the size of the Y component, which is src_width * src_height.

gmetax's answer is wrong in that he has put y_size in place of out_size when defining the output frame. The correct code snippet, I believe, would look like:

//Get input and output length
int input_size = env->GetArrayLength(yuvByteArray_);
int y_size = src_width * src_height;
int out_size = out_height * out_width;

//Generate input frame
i420_input_frame.width = src_width;
i420_input_frame.height = src_height;
i420_input_frame.data = (uint8_t *) yuvByteArray;
i420_input_frame.y = i420_input_frame.data;
i420_input_frame.u = i420_input_frame.y + y_size;
i420_input_frame.v = i420_input_frame.u + y_size / 4;

//Generate output frame
free(i420_output_frame.data);
i420_output_frame.width = out_width;
i420_output_frame.height = out_height;
i420_output_frame.data = new unsigned char[out_size * 3 / 2];
i420_output_frame.y = i420_output_frame.data;
i420_output_frame.u = i420_output_frame.y + out_size;
i420_output_frame.v = i420_output_frame.u + out_size / 4;


问:
import big csv with lots of columns into postgreSQL
I have a csv file with 2550 columns and I want to import it into postgreSQL.

For importing csv in postgreSQL at first I should create the table and them use \copy to copy from csv to table. but what if the table has huge amount of columns like my case that I cannot create table manually.

any solution?

Update

Data structure is as following:
dZ(01) till dZ(2550) are basically between -50 to +50:

```<code>id | date    | time      | localtime | pid | dZ(0)..dZ(1)......dZ(2550)|
---|---------|-----------|-----------|-----|---------------------------|
17|11-11-2014| 16:33:21 | 1.45E+15   |2375 |0 0 0 0 0 -1 0 -1 0 -5 -10|
</code>```

CSV structure: (I used '';' delimiter)

```<code>17;13-11-2014;08:09:37;1.45E+15;4098;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -4 3 0 -2 3 -2 1 0 0 1 1 3 -2 3 4 2 -2 -2 ....
</code>```

This is one line of data.

答:
Import the dZ column into a text column and later turn it into an array:

Create the temporary table:

```<code>create table s (
    id int,
    date date,
    time time,
    localt double precision,
    pid int,
    dz text
);
</code>```

Set the date style:

```<code>set datestyle = 'DMY';
</code>```

Import into the temporary table;

```<code>\copy s from '/home/cpn/codigo/file.csv' with (format csv, delimiter ';')
</code>```

Create the definitive table merging date and time into a timestamp and turning dZ into an array:

```<code>create table t (
    id int,
    datetime timestamp,
    localt double precision,
    pid int,
    dz integer[]
);
</code>```

Populate the definitive from the temporary:

```<code>insert into t (id, datetime, localt, pid, dz)
select
    id, date + time, localt, pid,
    regexp_split_to_array(dz, '\s')::int[]
from s
</code>```

Body:
I have a csv file with 2550 columns and I want to import it into postgreSQL.

For importing csv in postgreSQL at first I should create the table and them use \copy to copy from csv to table. but what if the table has huge amount of columns like my case that I cannot create table manually.

any solution?

Update

Data structure is as following:
dZ(01) till dZ(2550) are basically between -50 to +50:

id | date    | time      | localtime | pid | dZ(0)..dZ(1)......dZ(2550)|
---|---------|-----------|-----------|-----|---------------------------|
17|11-11-2014| 16:33:21 | 1.45E+15   |2375 |0 0 0 0 0 -1 0 -1 0 -5 -10|

CSV structure: (I used '';' delimiter)

17;13-11-2014;08:09:37;1.45E+15;4098;0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -4 3 0 -2 3 -2 1 0 0 1 1 3 -2 3 4 2 -2 -2 ....

This is one line of data.

Body:
Import the dZ column into a text column and later turn it into an array:

Create the temporary table:

create table s (
    id int,
    date date,
    time time,
    localt double precision,
    pid int,
    dz text
);

Set the date style:

set datestyle = 'DMY';

Import into the temporary table;

\copy s from '/home/cpn/codigo/file.csv' with (format csv, delimiter ';')

Create the definitive table merging date and time into a timestamp and turning dZ into an array:

create table t (
    id int,
    datetime timestamp,
    localt double precision,
    pid int,
    dz integer[]
);

Populate the definitive from the temporary:

insert into t (id, datetime, localt, pid, dz)
select
    id, date + time, localt, pid,
    regexp_split_to_array(dz, '\s')::int[]
from s


问:
Font-face not loading in IE8 and IE9 when accessing web via SSL
I'm using a webfont for my website (made with Spring for an Apache Tomcat 6 server). I'm including my font in my css file with font-face as:

```<code>@font-face{
  font-family:'FontAwesome';
  src:url('fonts/fontawesome-webfont.eot?v=3.0.1');
  src:url('fonts/fontawesome-webfont.eot?#iefix&v=3.0.1') format('embedded-opentype'),
  url('fonts/fontawesome-webfont.woff?v=3.0.1') format('woff'),
  url('fonts/fontawesome-webfont.ttf?v=3.0.1') format('truetype');
  font-weight:normal;
  font-style:normal }
</code>```

This css is called in a "layout.jsp" file which is called by all the rest of jsp pages, with the following:

```<code> <link href="<c:url value='/styles/font-awesome.min.css'/>" rel="stylesheet" type="text/css"/>
</code>```

This is working for every browser when I access my website internally via http:///webSite

However, we have also an Apache server which is serving the website via SSL (using a secure certificate) in the URL https:/// which redirects to the previous URL.
When using the SSL-https config the web is working well in every browser, but the font is not loading in IE8, nor in IE9.

This is:
- via http: fonts are loading well in every browser, including IE8 and IE9
- via https: fonts are loading well in every browser, but IE8 and IE9

The font is accessible from the browser at anytime. This is, if I write the path to the file, I can download it without problems. What is more, under Developer Tools of explorer, at Network tab I can see that the font is correctly downloaded (status: 200).

I've tried to include my font completelly in my CSS using its byte64 codification, instead of the path to the file with the generator of fontSquirrel:

```<code>@font-face {
    font-family: 'fontawesomeregular';
    src: url('fonts/fontawesome-webfont.eot');
    }

@font-face {
    font-family: 'fontawesomeregular';
    src: url(data:application/x-font-woff;charset=utf-8;base64,[BYTE64_STRING]) format('woff'),
         url('fonts/fontawesome-webfont.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;

}
</code>```

Doing this, the font is loading well in IE9, but not in IE8. At first, I thought it could be caused by the limitation of 32Kb at URLs. So, I reduced the charset of the font to reduce its size to about 20kb, and still no luck in IE8.

Any help?

答:
The practical answer is,using a proxy, to hide to the browser any cache-invalidating headers.
Like "cache-control" and pragma: "no-cache" headers returned to the browser.

I used nginx like this, adding the folowing commands the https proxied location:

```<code>  proxy_hide_header Cache-Control;
  proxy_hide_header Pragma;
</code>```

See here for details with nginx.

Using apache httpd, you'll find the syntax here

Body:
I'm using a webfont for my website (made with Spring for an Apache Tomcat 6 server). I'm including my font in my css file with font-face as:

@font-face{
  font-family:'FontAwesome';
  src:url('fonts/fontawesome-webfont.eot?v=3.0.1');
  src:url('fonts/fontawesome-webfont.eot?#iefix&v=3.0.1') format('embedded-opentype'),
  url('fonts/fontawesome-webfont.woff?v=3.0.1') format('woff'),
  url('fonts/fontawesome-webfont.ttf?v=3.0.1') format('truetype');
  font-weight:normal;
  font-style:normal }

This css is called in a "layout.jsp" file which is called by all the rest of jsp pages, with the following:

 <link href="<c:url value='/styles/font-awesome.min.css'/>" rel="stylesheet" type="text/css"/>

This is working for every browser when I access my website internally via http:///webSite

However, we have also an Apache server which is serving the website via SSL (using a secure certificate) in the URL https:/// which redirects to the previous URL.
When using the SSL-https config the web is working well in every browser, but the font is not loading in IE8, nor in IE9.

This is:
- via http: fonts are loading well in every browser, including IE8 and IE9
- via https: fonts are loading well in every browser, but IE8 and IE9

The font is accessible from the browser at anytime. This is, if I write the path to the file, I can download it without problems. What is more, under Developer Tools of explorer, at Network tab I can see that the font is correctly downloaded (status: 200).

I've tried to include my font completelly in my CSS using its byte64 codification, instead of the path to the file with the generator of fontSquirrel:

@font-face {
    font-family: 'fontawesomeregular';
    src: url('fonts/fontawesome-webfont.eot');
    }

@font-face {
    font-family: 'fontawesomeregular';
    src: url(data:application/x-font-woff;charset=utf-8;base64,[BYTE64_STRING]) format('woff'),
         url('fonts/fontawesome-webfont.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;

}

Doing this, the font is loading well in IE9, but not in IE8. At first, I thought it could be caused by the limitation of 32Kb at URLs. So, I reduced the charset of the font to reduce its size to about 20kb, and still no luck in IE8.

Any help?

Body:
The practical answer is,using a proxy, to hide to the browser any cache-invalidating headers.
Like "cache-control" and pragma: "no-cache" headers returned to the browser.

I used nginx like this, adding the folowing commands the https proxied location:

  proxy_hide_header Cache-Control;
  proxy_hide_header Pragma;

See here for details with nginx.

Using apache httpd, you'll find the syntax here


问:
Hello Beacons app not detecting virtual beacon (created with Beacon Simulator app)
I have followed the ten steps outlined in the Hello Beacon app tutorial at https://codelabs.developers.google.com/codelabs/hello-beacons/. There are no errors being thrown up during build. The only issue is that the virtual beacon (using Beacon Simulator app) is not detected by the Hello Beacon app. I know the problem is not with the beacon simulator because it gets detected by the beacon tools app by Google.

I don’t think there is any issue with the code because I have followed the tutorial exactly without deviation. However there are a few areas in the code and in the google developers console where parameters have to be defined. I suspect this could be causing the issue:

I am not sure if I have defined "some_namespace", "some_type" correctly.

SubscribeOptions options = new SubscribeOptions.Builder()
 .setStrategy(Strategy.BLE_ONLY)
 .setFilter(new MessageFilter.Builder()
 .includeNamespacedType("some_namespace", "some_type").build())
 .build();

Here are a few parameters I tried –

“beacon-proximity-app”, “impdata”

“a72d91966ecd43888771” (from the Beacon Simulator app), “beacon-proximity-app/imdata” (from Beacon Tools app)

“beacon-proximity-app/impdata”, “”

“beacon-proximity-app”, “string”

“a72d91966ecd43888771” (from the Beacon Simulator app), “beacon-proximity-app/string” (from Beacon Tools app)

I also tried implementing the code with and without -

```<code> .setFilter(new MessageFilter.Builder()
 .includeNamespacedType("some_namespace", "some_type")
 .build()
</code>```

I am not sure where to run the command to generate the SHA1 fingerprint because I don’t completely understand its purpose. I have tried generating it from the .android folder, hello beacons folder and the JRE bin folder

Google Developers Console - SHA1 fingerprint / API Key

I have placed the API key created at Google Developers Console in the Android Manifest file at:

<meta-data
        android:name="com.google.android.nearby.messages.API_KEY"
        android:value="API_key_placed_here" />

I am not sure if that is the only place the API key needs to be placed.

I would appreciate any help from the community to resolve this issue.

答:
I finally got it to work. The only issue was the access restriction that was set on the API key using the package name and SHA1 fingerprint. Once that was removed, the Hello Beacons app could detect my simulated beacon.

In the optional step 10, I'm not sure what causes the error. Does it have something to do with the package name provided (com.google.android.gms.nearby.messages.samples.hellobeacons), or the SHA1 key? Difficult to say.

Hope this helps.

Body:
I have followed the ten steps outlined in the Hello Beacon app tutorial at https://codelabs.developers.google.com/codelabs/hello-beacons/. There are no errors being thrown up during build. The only issue is that the virtual beacon (using Beacon Simulator app) is not detected by the Hello Beacon app. I know the problem is not with the beacon simulator because it gets detected by the beacon tools app by Google.

I don’t think there is any issue with the code because I have followed the tutorial exactly without deviation. However there are a few areas in the code and in the google developers console where parameters have to be defined. I suspect this could be causing the issue:

I am not sure if I have defined "some_namespace", "some_type" correctly.

SubscribeOptions options = new SubscribeOptions.Builder()
 .setStrategy(Strategy.BLE_ONLY)
 .setFilter(new MessageFilter.Builder()
 .includeNamespacedType("some_namespace", "some_type").build())
 .build();

Here are a few parameters I tried –

“beacon-proximity-app”, “impdata”

“a72d91966ecd43888771” (from the Beacon Simulator app), “beacon-proximity-app/imdata” (from Beacon Tools app)

“beacon-proximity-app/impdata”, “”

“beacon-proximity-app”, “string”

“a72d91966ecd43888771” (from the Beacon Simulator app), “beacon-proximity-app/string” (from Beacon Tools app)

I also tried implementing the code with and without -

 .setFilter(new MessageFilter.Builder()
 .includeNamespacedType("some_namespace", "some_type")
 .build()

I am not sure where to run the command to generate the SHA1 fingerprint because I don’t completely understand its purpose. I have tried generating it from the .android folder, hello beacons folder and the JRE bin folder

Google Developers Console - SHA1 fingerprint / API Key

I have placed the API key created at Google Developers Console in the Android Manifest file at:

<meta-data
        android:name="com.google.android.nearby.messages.API_KEY"
        android:value="API_key_placed_here" />

I am not sure if that is the only place the API key needs to be placed.

I would appreciate any help from the community to resolve this issue.


问:
Association Extensions no longer working in Rails 2.3.10
I have an app that we just upgrade from 2.1.0 to 2.3.10.  After the upgrade, an Association Extension that previously worked causes a failure.  Here is the code on the model for the extension:

```<code>Class Classroom

  has_many :registrations

  has_many :students, :through => :registrations, :uniq => true do
    def in_group(a_group)
      if a_driver
        scoped(:conditions => ['registrations.group_id = ?', a_group])
      else
        in_no_group
      end
    end

    def in_no_group
      scoped(:conditions => 'registrations.group_id is null')
    end
  end

end
</code>```

This is a simplified model of my actual issue, but basically I used to be able to do

```<code>classroom.students.in_group(honor_students)
</code>```

This no longer works, with the following output:

```<code>classroom.students.in_group(honor_students)
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'registrations.group_id' in 'where clause': SELECT * FROM `students` WHERE (registrations.group_id = 1234)
</code>```

When I just grab the list of students, the SQL has all the expected join syntax there thats missing from the above version:

```<code>SELECT DISTINCT `students`.* FROM `students` INNER JOIN `registrations` ON `students`.id = `registrations`.student_id WHERE ((`registrations`.classroom_id = 9876))
</code>```

Why is the association extension missing all the join SQL?

答: use this Rails 2.3: How to turn this SQL statement into a named_scope on students instead of nesting it in association</p>

Body:
I have an app that we just upgrade from 2.1.0 to 2.3.10.  After the upgrade, an Association Extension that previously worked causes a failure.  Here is the code on the model for the extension:

Class Classroom

  has_many :registrations

  has_many :students, :through => :registrations, :uniq => true do
    def in_group(a_group)
      if a_driver
        scoped(:conditions => ['registrations.group_id = ?', a_group])
      else
        in_no_group
      end
    end

    def in_no_group
      scoped(:conditions => 'registrations.group_id is null')
    end
  end

end

This is a simplified model of my actual issue, but basically I used to be able to do

classroom.students.in_group(honor_students)

This no longer works, with the following output:

classroom.students.in_group(honor_students)
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'registrations.group_id' in 'where clause': SELECT * FROM `students` WHERE (registrations.group_id = 1234)

When I just grab the list of students, the SQL has all the expected join syntax there thats missing from the above version:

SELECT DISTINCT `students`.* FROM `students` INNER JOIN `registrations` ON `students`.id = `registrations`.student_id WHERE ((`registrations`.classroom_id = 9876))

Why is the association extension missing all the join SQL?


问:
ASP.Net MVC 5 Html.BeginForm onsubmit and model with required attribute
I have required attribute on my model properties but I added a "spinner" to show processing request in form onsubmit. Now, even though that it didn't submit the form, it shows the "spinner" i created, and stuck on the overlay but the textbox with required attribute is in focus.

```<code>using (Html.BeginForm("Add", "UserAccount", FormMethod.Post, new { onsubmit="spinner()"}))
{
//Html.TextBoxes for model properties with required
}
<div id="spinner" hidden="">
    <div>
        <i class="fa fa-spinner fa-spin fa-pulse" style="color: white; font-    size: 50px;"></i>
        <label style="color: white; font-size: 50px;">Processing</label>
    </div>
</div>

<script>
function spinner() {
    $("#spinner").show();
}
</script>
</code>```

Is their a way to check first if the "required" attribute is satisfied before accessing the onsubmit function?

答:
You need to add submitHandler function to validator. Here is the complete code.

```<code><script type="text/javascript">
   $(function () {

      $("form").data("validator").settings.submitHandler = function (form) {
         $("#submit-button").html("<i class=\"fa fa-spinner fa-pulse\"></i> Signing In...")
            .prop('disabled', true);
         form.submit();
      };
   });
</script>
</code>```

Body:
I have required attribute on my model properties but I added a "spinner" to show processing request in form onsubmit. Now, even though that it didn't submit the form, it shows the "spinner" i created, and stuck on the overlay but the textbox with required attribute is in focus.

using (Html.BeginForm("Add", "UserAccount", FormMethod.Post, new { onsubmit="spinner()"}))
{
//Html.TextBoxes for model properties with required
}

        Processing

Is their a way to check first if the "required" attribute is satisfied before accessing the onsubmit function?

Body:
You need to add submitHandler function to validator. Here is the complete code.

<script type="text/javascript">
   $(function () {

      $("form").data("validator").settings.submitHandler = function (form) {
         $("#submit-button").html("<i class=\"fa fa-spinner fa-pulse\"></i> Signing In...")
            .prop('disabled', true);
         form.submit();
      };
   });
</script>


问:
How to add an image to a Drawable Resource File
I have created a drawable resource file and all I need is to add an image to this drawable resource file that contains layer list which this layer list contains an item and shape like this example
resoucedrawablefile.xml</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <bitmap android:gravity="center" android:src="@drawable/remove" />

    </item>

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#20CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#30CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#50CCCCCC" />
        </shape>
    </item>

    <!-- Background -->
    <item>
        <shape>
            <solid android:color="#b5e40008" />
            <corners android:radius="10dp" />
        </shape>
    </item>
</layer-list>
</code>```

答:
We can do this</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
   <!-- adding image -->
<item android:drawable="@drawable/image_name_here" />
<!-- Drop Shadow Stack -->
<item>
    <shape>
        <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
        <corners android:radius="10dp" />
        <solid android:color="#00CCCCCC" />
    </shape>
</item>
<item>
    <shape>
        <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
        <corners android:radius="10dp" />
        <solid android:color="#10CCCCCC" />
    </shape>
</item>
<item>
    <shape>
        <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
        <corners android:radius="10dp" />
        <solid android:color="#20CCCCCC" />
    </shape>
</item>
<item>
    <shape>
        <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
        <corners android:radius="10dp" />
        <solid android:color="#30CCCCCC" />
    </shape>
</item>
<item>
    <shape>
        <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
        <corners android:radius="10dp" />
        <solid android:color="#50CCCCCC" />
    </shape>
</item>

<!-- Background -->
<item>
    <shape>
        <solid android:color="#b5e40008" /><corners android:radius="10dp" />
    </shape>
</item>
</layer-list>
</code>```

Body:
I have created a drawable resource file and all I need is to add an image to this drawable resource file that contains layer list which this layer list contains an item and shape like this example
resoucedrawablefile.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <bitmap android:gravity="center" android:src="@drawable/remove" />

    </item>

    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#20CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#30CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#50CCCCCC" />
        </shape>
    </item>

    <item>
        <shape>
            <solid android:color="#b5e40008" />
            <corners android:radius="10dp" />
        </shape>
    </item>
</layer-list>

Body:
We can do this

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
   <!-- adding image -->
<item android:drawable="@drawable/image_name_here" />
<!-- Drop Shadow Stack -->
<item>
    <shape>
        <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
        <corners android:radius="10dp" />
        <solid android:color="#00CCCCCC" />
    </shape>
</item>
<item>
    <shape>
        <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
        <corners android:radius="10dp" />
        <solid android:color="#10CCCCCC" />
    </shape>
</item>
<item>
    <shape>
        <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
        <corners android:radius="10dp" />
        <solid android:color="#20CCCCCC" />
    </shape>
</item>
<item>
    <shape>
        <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
        <corners android:radius="10dp" />
        <solid android:color="#30CCCCCC" />
    </shape>
</item>
<item>
    <shape>
        <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
        <corners android:radius="10dp" />
        <solid android:color="#50CCCCCC" />
    </shape>
</item>

<!-- Background -->
<item>
    <shape>
        <solid android:color="#b5e40008" /><corners android:radius="10dp" />
    </shape>
</item>
</layer-list>


问:
Showing images on same axes
I have a basic question about MATLAB. How I can show two images on same axes? I don't want it to be in same figure (as the following code shows) but the same axes.</p>

```<code>subplot(1,2,1), subimage(X)
subplot(1,2,2), subimage(X2)
</code>```

答:
If you want to display two images side-by-side in the same axes you'll want to modify the XData property of the second image to shift it to the right of the first image

```<code>X = rand(10);
X2 = rand(10);

figure
subimage(X)
hold on
him2 = subimage(X2);
set(him2, 'XData', get(him2, 'XData') + size(X, 2))
</code>```

Title: Showing images on same axes

Body:
I have a basic question about MATLAB. How I can show two images on same axes? I don't want it to be in same figure (as the following code shows) but the same axes.

subplot(1,2,1), subimage(X)
subplot(1,2,2), subimage(X2)

Body:
If you want to display two images side-by-side in the same axes you'll want to modify the XData property of the second image to shift it to the right of the first image

X = rand(10);
X2 = rand(10);

figure
subimage(X)
hold on
him2 = subimage(X2);
set(him2, 'XData', get(him2, 'XData') + size(X, 2))


问:
Moving HTML controls from one page to other
I am working on a project which has 4 tabbed view (separate HTML pages).Each of these views have bunch of SVG charts implemented using d3.js .Now the client wants a feature where he could cut&paste / move charts from one tabbed view to another.What is the best way to achieve this? I have already used interact.min.js for resizing & dragging/moving charts within the page limits.

This project is in a offline format i.e. There is no usage of any server side language.All your suggestions should take into this consideration.Currently all the views are launched by clicking html page from a folder present in local file system.

答:
I Think This might will Help You . You can Replace Whole HTML1 With HTML2  Tab and vice verse .

HTML

```<code><div id="div1"> HULK </div>

<div id="div2">THOR </div>

<input class="button" type="button" value="Replace THOR with HULK">
</code>```

JQUERY

```<code>$(".button").click(function(){
$('#div2').replaceWith($('#div1').html());
})
</code>```

This is just an Idea which help you i think.

JS Fiddle Demo

Body:
I Think This might will Help You . You can Replace Whole HTML1 With HTML2  Tab and vice verse .

HTML

<div id="div1"> HULK </div>

<div id="div2">THOR </div>

<input class="button" type="button" value="Replace THOR with HULK">

JQUERY

$(".button").click(function(){
$('#div2').replaceWith($('#div1').html());
})

This is just an Idea which help you i think.

JS Fiddle Demo


问:
Looking for S#arp Architecture usage without ASP.net MVC issues or gotchas
I am exploring technologies and libraries before I get started on a new project.  One that has really caught my eye is the S#arp Architecture library for ASP.net MVC.  However, I have already decide that the bulk of my web application will use Visual Web GUI as the front end, leaving only a small separate customer facing web component that will be developed in ASP.net MVC.  Bearing this in mind, based on the experiences of those of you who have a good familiarity with S#harp Architecture, or may have attempted a similar solution using S#harp, are there any issues or gotchas I should be aware of before I begin? I have also had a look at Castle Active Record, and Fluent NHibernate usage as possible options, but find myself leaning towards S#arp.

My most major goal in choosing a library are to get my data access set up using the repository pattern as quickly as possible.

答:
If your main goal is to flesh out a persistence layer quickly then S#arp Architecture is a bit overload IMO. S#arp makes use of Fluent NHibernate so I'd just go with that. FNH's auto mapping conventions should slice a big chunk off your dev time.

I wouldn't say S#arp is a library. It's more of a boilerplate for Domain Driven Design. You should be familiar with Dependency Injection (aka Inversion of Control), Test Driven Development, Rhino Mocks, and NHibernate before you start looking at S#arp (because those are the concepts and technologies used in it). Otherwise the learning curve will be quite steep.


问:
Changing class type using Jquery
I am using this code to fetch the data from startup.php.The response of the PHP file is JSON with 3 fields. One of the field in JSON response is a status message. How to change the value of div class .content based on the status message. I need to do that to change the color of the text displayed in the content DIV based on the status message. .content is the class name of the DIV

```<code>var loadinggif = '../img/loading.gif';
$(document).ready(function(){
    // set up the click event
        $('body').on('click','.btnbg', function() {
                var toLoad = '../vr/startup.php';
                $('.content').empty();
                $('.content').slideUp('slow', loadContent);
                $('#load').remove();
                $('#waiting').append('<div id="load"><img src="' + loadinggif + '" alt="Loading" /></div>');
                $('#load').fadeIn('normal');
                function loadContent() {

                    var userName = $('#userName').val();
                    var remote_addr = $('#remote_addr').val();
                    var forwarded_for = $('#forwarded_for').val();
                    var url = $('#url').val();
                    //$('#forwarded_for1').val()'';
  var _post = {'userName': userName, 'ipAddr1':remote_addr,'ipAddr2':forwarded_for, 'url':url};

   $('.content').load(toLoad, _post , function(response, status, xhr)

if (status == 'error') {
                        var msg = "Sorry but there was an error: ";
                        $(".content").html(msg + xhr.status + " " + xhr.statusText);
                    }
            }).slideDown('slow', hideLoader());
                }
                function hideLoader() {
                        $('#load').fadeOut('normal');
                }
                return false;
        });
</code>```

答:
You can use the css() function in Jquery :

```<code>$(".content").css({'background-color': 'red'});
</code>```

Edit

I red your question wrong. To change class you can use $('.content').removeClass('classOne').addClass('classTwo');

If you have a class like has-error, you can use toggleClass() to toggle it, it will remove it if it's present or add it if not :

$('.content').toggleClass('has-error');

for your if elseprobleme, simply do :

```<code>if(condition) {
   $('.content').removeClass('class2 class3').addClass('class1');
} else if(condition2) {
   $('.content').removeClass('class1 class3').addClass('class2');
} else {
   $('.content').removeClass('class1 class2').addClass('class3');
}
</code>```

Title: Changing class type using Jquery

Body:
I am using this code to fetch the data from startup.php.The response of the PHP file is JSON with 3 fields. One of the field in JSON response is a status message. How to change the value of div class .content based on the status message. I need to do that to change the color of the text displayed in the content DIV based on the status message. .content is the class name of the DIV

var loadinggif = '../img/loading.gif';
$(document).ready(function(){
    // set up the click event
        $('body').on('click','.btnbg', function() {
                var toLoad = '../vr/startup.php';
                $('.content').empty();
                $('.content').slideUp('slow', loadContent);
                $('#load').remove();
                $('#waiting').append('

');
                $('#load').fadeIn('normal');
                function loadContent() {

                    var userName = $('#userName').val();
                    var remote_addr = $('#remote_addr').val();
                    var forwarded_for = $('#forwarded_for').val();
                    var url = $('#url').val();
                    //$('#forwarded_for1').val()'';
  var _post = {'userName': userName, 'ipAddr1':remote_addr,'ipAddr2':forwarded_for, 'url':url};

   $('.content').load(toLoad, _post , function(response, status, xhr)

if (status == 'error') {
                        var msg = "Sorry but there was an error: ";
                        $(".content").html(msg + xhr.status + " " + xhr.statusText);
                    }
            }).slideDown('slow', hideLoader());
                }
                function hideLoader() {
                        $('#load').fadeOut('normal');
                }
                return false;
        });

Body:
You can use the css() function in Jquery :

$(".content").css({'background-color': 'red'});

Edit

I red your question wrong. To change class you can use $('.content').removeClass('classOne').addClass('classTwo');

If you have a class like has-error, you can use toggleClass() to toggle it, it will remove it if it's present or add it if not :

$('.content').toggleClass('has-error');

for your if elseprobleme, simply do :

if(condition) {
   $('.content').removeClass('class2 class3').addClass('class1');
} else if(condition2) {
   $('.content').removeClass('class1 class3').addClass('class2');
} else {
   $('.content').removeClass('class1 class2').addClass('class3');
}


问:
Nodejs ssl key permission denied
I am getting this error when trying to access my ssl key and cetificate from my nodejs app:

As you can see, I've added my user to hace permission on the files.. I don't know what else to do?

答:
Ok, I found the solution looking around.

Basically, LetsEncrypt is generating the certificate files in /etc/letsencrypt/live/ and /etc/letsencrypt/archive/. These two folders have permissions 744 ("owner can read, write, and execute; group and users can read"), but it is not enough: you must give permissions to read and execute:

```<code>sudo chmod 755 /etc/letsencrypt/live/
sudo chmod 755 /etc/letsencrypt/archive/
</code>```

This is of course not a good solution for security reasons, but it's the only one I found that works, and surely it's better than running the Node.js server as root!

Source: https://groups.google.com/d/msg/node-red/g8cPmNgGnh0/guWq-8szBAAJ

Title: Nodejs ssl key permission denied

Body:
Ok, I found the solution looking around.

Basically, LetsEncrypt is generating the certificate files in /etc/letsencrypt/live/ and /etc/letsencrypt/archive/. These two folders have permissions 744 ("owner can read, write, and execute; group and users can read"), but it is not enough: you must give permissions to read and execute:

sudo chmod 755 /etc/letsencrypt/live/
sudo chmod 755 /etc/letsencrypt/archive/

This is of course not a good solution for security reasons, but it's the only one I found that works, and surely it's better than running the Node.js server as root!

Source: https://groups.google.com/d/msg/node-red/g8cPmNgGnh0/guWq-8szBAAJ


问:
Moving an image using Accelerometer of android
I have read articles/tutorial about accessing the phone's accelerometer (acceleration and orientation) values. I am trying to build a simple app where I can move a ball image using the these values. Here is my code:

```<code>import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class Accelerometer extends Activity implements SensorEventListener {
    /** Called when the activity is first created. */
     CustomDrawableView mCustomDrawableView = null;
     ShapeDrawable mDrawable = new ShapeDrawable();
      int x ;
       int y ;

    private SensorManager sensorManager = null;

       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);
           // Get a reference to a SensorManager
           sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
           mCustomDrawableView = new CustomDrawableView(this);
           setContentView(mCustomDrawableView);
         //  setContentView(R.layout.main);

       }

       // This method will update the UI on new sensor events
       public void onSensorChanged(SensorEvent sensorEvent) {
         {
         if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

         int someNumber = 100;
         float xChange = someNumber * sensorEvent.values[1];
         //values[2] can be -90 to 90
         float yChange = someNumber * 2 * sensorEvent.values[2];
             x = x + (int)xChange;
             y = y + (int)yChange;

         }

         if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {

         }
        }
       }

       // I've chosen to not implement this method
       public void onAccuracyChanged(Sensor arg0, int arg1) {
     // TODO Auto-generated method stub

    }

       @Override
       protected void onResume() {
        super.onResume();
        // Register this class as a listener for the accelerometer sensor
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
        // ...and the orientation sensor
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
       }

       @Override
       protected void onStop() {
        // Unregister the listener
        sensorManager.unregisterListener(this);
        super.onStop();
       }
       public  class CustomDrawableView extends View {

           public CustomDrawableView(Context context) {
               super(context);

               int width = 50;
               int height = 50;
               mDrawable = new ShapeDrawable(new OvalShape());
               mDrawable.getPaint().setColor(0xff74AC23);
               mDrawable.setBounds(x, y, x + width, y + height);
           }
           protected void onDraw(Canvas canvas) {
               mDrawable.draw(canvas);
               invalidate();
           }
       }
}
</code>```

I am getting an oval shape displayed on the screen but nothing happens after that.

thanks

答:
use the following library instead scrolling motion

add this line in top XML view

```<code>xmlns:parallax="http://schemas.android.com/apk/res-auto"
</code>```

for Layout

```<code> <com.nvanbenschoten.motion.ParallaxImageView
            android:id="@+id/parallex"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/image_hd"
            parallax:motionTiltSensitivity="2.5" />
</code>```

for code in your onCreate() method

```<code>ParallaxImageView mBackground = (ParallaxImageView) findViewById(R.id.parallex);
</code>```

in your onResume() method

```<code>if(mBackground!=null)
mBackground.registerSensorManager();
</code>```

in your onDestroy() method

```<code>// Unregister SensorManager when exiting
mBackground.unregisterSensorManager();
</code>```

Body:
I have read articles/tutorial about accessing the phone's accelerometer (acceleration and orientation) values. I am trying to build a simple app where I can move a ball image using the these values. Here is my code:

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class Accelerometer extends Activity implements SensorEventListener {
    /** Called when the activity is first created. */
     CustomDrawableView mCustomDrawableView = null;
     ShapeDrawable mDrawable = new ShapeDrawable();
      int x ;
       int y ;

    private SensorManager sensorManager = null;

       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);
           // Get a reference to a SensorManager
           sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
           mCustomDrawableView = new CustomDrawableView(this);
           setContentView(mCustomDrawableView);
         //  setContentView(R.layout.main);

       }

       // This method will update the UI on new sensor events
       public void onSensorChanged(SensorEvent sensorEvent) {
         {
         if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

         int someNumber = 100;
         float xChange = someNumber * sensorEvent.values[1];
         //values[2] can be -90 to 90
         float yChange = someNumber * 2 * sensorEvent.values[2];
             x = x + (int)xChange;
             y = y + (int)yChange;

         }

         if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {

         }
        }
       }

       // I've chosen to not implement this method
       public void onAccuracyChanged(Sensor arg0, int arg1) {
     // TODO Auto-generated method stub

    }

       @Override
       protected void onResume() {
        super.onResume();
        // Register this class as a listener for the accelerometer sensor
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
        // ...and the orientation sensor
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
       }

       @Override
       protected void onStop() {
        // Unregister the listener
        sensorManager.unregisterListener(this);
        super.onStop();
       }
       public  class CustomDrawableView extends View {

           public CustomDrawableView(Context context) {
               super(context);

               int width = 50;
               int height = 50;
               mDrawable = new ShapeDrawable(new OvalShape());
               mDrawable.getPaint().setColor(0xff74AC23);
               mDrawable.setBounds(x, y, x + width, y + height);
           }
           protected void onDraw(Canvas canvas) {
               mDrawable.draw(canvas);
               invalidate();
           }
       }
}

I am getting an oval shape displayed on the screen but nothing happens after that.

thanks

Body:
use the following library instead scrolling motion

add this line in top XML view

xmlns:parallax="http://schemas.android.com/apk/res-auto"

for Layout

 <com.nvanbenschoten.motion.ParallaxImageView
            android:id="@+id/parallex"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/image_hd"
            parallax:motionTiltSensitivity="2.5" />

for code in your onCreate() method

ParallaxImageView mBackground = (ParallaxImageView) findViewById(R.id.parallex);

in your onResume() method

if(mBackground!=null)
mBackground.registerSensorManager();

in your onDestroy() method

// Unregister SensorManager when exiting
mBackground.unregisterSensorManager();


问:
WatchKit: Create ring graph (One ring)
I want to create circle graph on first page of Page Controller and bar graphic on second page of Page Controller. I have use WKInterfaceActivityRing, but it represent only 3 rings together.

I have 2 questions about WatchKit:

How to create standard ring graph (one ring)?

How to create standard bar graph?

What i mean:

p.s. Sorry for my English

答:
I have created a bar graph similar to the one listed by simply adding groups side by side within a containing group and setting all of their widths to say 5 pixels, and the height to zero. Set the height of the container group to say 100 pixels. Then create an outlet for each "element" group within the container and assign the height of the group to be equal to whatever value you want to display. If your scale is only 1 - 10 then calculate what percentage of 10 your value is and multiply that by 100 to tell the element group how large to be.

for example

scale is 1 - 10, value is 5 which is 50%, or .5 of 10, 100 * .5 is 50 so set your element groups height to be 50

Hope that makes sense

Title: WatchKit: Create ring graph (One ring)


问:
Refreshing browser web-page not load in ui-router when locationProvider used
When I directly refresh the browser using F5 or directly hitting the url,
page not load but when I click on the button then the page gets load

I am using like this

Enable HTML5Mode using $locationProvider

```<code>var routerApp = angular.module('myApp', ['ui.router','ngCookies']);
routerApp.config(function($locationProvider){
    $locationProvider.html5Mode({
          enabled: true
    })
});
</code>```

I Added the following code to the  of your HTML file:

```<code><base href="/">
</code>```

or Simply using Syntax like that

```<code>$locationProvider.html5Mode({
          enabled: true,
          requireBase: false
    })
</code>```

I find that this is already issue on https://github.com/angular-ui/ui-router/issues/105

Can someone knows how to solve this ?
When I am not using $locationProvider for omitting '#' then it is working fine with refreshing too

答:
Attempt this</p>

```<code>$locationProvider.html5Mode({
    enabled: true,
    requireBase: false
})
</code>```

Body:
When I directly refresh the browser using F5 or directly hitting the url,
page not load but when I click on the button then the page gets load

I am using like this

Enable HTML5Mode using $locationProvider

var routerApp = angular.module('myApp', ['ui.router','ngCookies']);
routerApp.config(function($locationProvider){
    $locationProvider.html5Mode({
          enabled: true
    })
});

I Added the following code to the  of your HTML file:

<base href="/">

or Simply using Syntax like that

$locationProvider.html5Mode({
          enabled: true,
          requireBase: false
    })

I find that this is already issue on https://github.com/angular-ui/ui-router/issues/105

Can someone knows how to solve this ?
When I am not using $locationProvider for omitting '#' then it is working fine with refreshing too

Body:
Attempt this

$locationProvider.html5Mode({
    enabled: true,
    requireBase: false
})