问:
getting org-protocol to work on Firefox Quantum -- `No server buffers remain to edit` error
So I am trying to get org-protocol to work for the first time on Firefox Quantum. I worked through a variety of blog posts and the documentation, but still cannot get past this particular error

```<code>Greedy org-protocol handler.  Killing client.
No server buffers remain to edit.
</code>```

So I am using emacs 25.3 on Ubuntu Linux x64 16.04, and the newly released Firefox Quantum.

I tried to do this in two ways.

The traditional approach of setting up org-protocol through creating a desktop entry and then setting up bookmarklets in Firefox.

Using the org-capture add-on in Firefox.

Both are giving me the same error.

For approach 1, I followed the documentation as well as a very helpful stackexchange post:

How to make org-protocol work?

There was also this useful blog post.

Here is what I did:

A. I created a desktop entry:

```<code>[Desktop Entry]
Name=org-protocol
Exec=emacsclient -n %u
Type=Application
Terminal=false
Categories=System;
MimeType=x-scheme-handler/org-protocol;
</code>```

B. added config to .spacemacs file.

I added the lines:

```<code>(server-start)
(require 'org-protocol)
</code>```

Then I setup up the capture template in my .spacemacs file:

```<code>(setq org-capture-templates
      (quote
              ("p" "org-protocol" entry (file+headline "~/Dropbox/config/org/refile/refile.org")
                "* %^{Title}\nSource: %u, %c\n #+BEGIN_QUOTE\n%:initial\n#+END_QUOTE\n\n\n%?")
              ("l" "org-protocol link" entry (file "~/Dropbox/config/org/refile/refile.org")
                "* %? [[%:link][%:description]] \nCaptured On: %U")
... Additional templates.
))
</code>```

C. Then I created the bookmarklets with the locations:

```<code>javascript:location.href='org-protocol://store-link://l/'+encodeURIComponent(location.href)

javascript:location.href='org-protocol://capture://l/'+encodeURIComponent(location.href)+'/'+encodeURIComponent(document.title)+'/'+encodeURIComponent(window.getSelection())
</code>```

After all of this, I still get the error message referenced above.

Second, I tried the org-capture add-on in Firefox. But it did not work either.

Not sure what the cause of the error is. Any help is appreciated.

In other reading people get this Greedy error when there are problems in the org-capture template, but I did not find any errors.

答:
Okay, this was a tricky solution. The problem was caused by some recent changes in the use-package emacs package. The issue is documented on github.

https://github.com/jwiegley/use-package/issues/557

Let me tell you how I found the issue in case you get other people registering similar issues.

I set up the org-capture-extension as you recommended in the README, however I keep getting the following error (posted below) in emacs Messages buffer. I am using Emacs 25.3 on Ubuntu 16.04x64 with the new Firefox Quantum browser as well as Chrome.

So I tried to manually pass a link through the emacsclient with the following command

```<code>emacsclient -n "org-protocol:///capture?url=http%3a%2f%2fduckduckgo%2ecom&title=DuckDuckGo"
</code>```

But I kept getting this strange response in the Messages buffer where there was a cycling behavior between warning349 and warning 931.

```<code>condition-case: Symbol’s value as variable is void: use-package--warning349
condition-case: Symbol’s value as variable is void: use-package--warning931
condition-case: Symbol’s value as variable is void: use-package--warning349
condition-case: Symbol’s value as variable is void: use-package--warning931
condition-case: Symbol’s value as variable is void: use-package--warning349
</code>```

The solution is documented in the github issue, but I don't think that users should manually implement the fix. Instead I think that the author will make the change and merge it into master--at which time users can redownload and install the use-package package.

Body:
So I am trying to get org-protocol to work for the first time on Firefox Quantum. I worked through a variety of blog posts and the documentation, but still cannot get past this particular error

Greedy org-protocol handler.  Killing client.
No server buffers remain to edit.

So I am using emacs 25.3 on Ubuntu Linux x64 16.04, and the newly released Firefox Quantum.

I tried to do this in two ways.

The traditional approach of setting up org-protocol through creating a desktop entry and then setting up bookmarklets in Firefox.

Using the org-capture add-on in Firefox.

Both are giving me the same error.

For approach 1, I followed the documentation as well as a very helpful stackexchange post:

How to make org-protocol work?

There was also this useful blog post.

Here is what I did:

A. I created a desktop entry:

[Desktop Entry]
Name=org-protocol
Exec=emacsclient -n %u
Type=Application
Terminal=false
Categories=System;
MimeType=x-scheme-handler/org-protocol;

B. added config to .spacemacs file.

I added the lines:

(server-start)
(require 'org-protocol)

Then I setup up the capture template in my .spacemacs file:

(setq org-capture-templates
      (quote
              ("p" "org-protocol" entry (file+headline "~/Dropbox/config/org/refile/refile.org")
                "* %^{Title}\nSource: %u, %c\n #+BEGIN_QUOTE\n%:initial\n#+END_QUOTE\n\n\n%?")
              ("l" "org-protocol link" entry (file "~/Dropbox/config/org/refile/refile.org")
                "* %? [[%:link][%:description]] \nCaptured On: %U")
... Additional templates.
))

C. Then I created the bookmarklets with the locations:

javascript:location.href='org-protocol://store-link://l/'+encodeURIComponent(location.href)

javascript:location.href='org-protocol://capture://l/'+encodeURIComponent(location.href)+'/'+encodeURIComponent(document.title)+'/'+encodeURIComponent(window.getSelection())

After all of this, I still get the error message referenced above.

Second, I tried the org-capture add-on in Firefox. But it did not work either.

Not sure what the cause of the error is. Any help is appreciated.

In other reading people get this Greedy error when there are problems in the org-capture template, but I did not find any errors.

Body:
Okay, this was a tricky solution. The problem was caused by some recent changes in the use-package emacs package. The issue is documented on github.

https://github.com/jwiegley/use-package/issues/557

Let me tell you how I found the issue in case you get other people registering similar issues.

I set up the org-capture-extension as you recommended in the README, however I keep getting the following error (posted below) in emacs Messages buffer. I am using Emacs 25.3 on Ubuntu 16.04x64 with the new Firefox Quantum browser as well as Chrome.

So I tried to manually pass a link through the emacsclient with the following command

emacsclient -n "org-protocol:///capture?url=http%3a%2f%2fduckduckgo%2ecom&title=DuckDuckGo"

But I kept getting this strange response in the Messages buffer where there was a cycling behavior between warning349 and warning 931.

condition-case: Symbol’s value as variable is void: use-package--warning349
condition-case: Symbol’s value as variable is void: use-package--warning931
condition-case: Symbol’s value as variable is void: use-package--warning349
condition-case: Symbol’s value as variable is void: use-package--warning931
condition-case: Symbol’s value as variable is void: use-package--warning349

The solution is documented in the github issue, but I don't think that users should manually implement the fix. Instead I think that the author will make the change and merge it into master--at which time users can redownload and install the use-package package.


来源: stackexchange

问:
Validate answer to exact match in Google Forms
I'm trying to limit a answer in Google Forms to exact word without it continues. What I mean:

If input is: "word" it passes, but if it is "sample","words", "worda", and etc... "word*" it does not pass.

I tried with (RegExr+?(?=\w|\d|\s)) ,   /RegExr+?(?=\w|\d|\s)/ ,RegExr+?(?=\w|\d|\s) with RegEx menu and Match option, but it gives error that the changes can not be saved.

答: You seem to be overthinking this one.  The validator accepts a regular expression without any of the delimiters you're used to in, say, sed or javascript.  The basic regex ^word$ should do what you want (it did in my tests, below)

ContentLicense: CC BY-SA 3.0


问:
a simple regexp validator
How do a I create a validator, which has these simple rules. An expression is valid if

it must start with a letter

it must end with a letter

it can contain a dash (minus sign), but not at start or end of the expression

答:
```<code>^[a-zA-Z]+-?[a-zA-Z]+$
</code>```

E.g.

```<code>def validate(whatever)
  reg = /^[a-zA-Z]+-?[a-zA-Z]+$/
return (reg.match(whatever)) ? true : false;
end
</code>```

OwnerDisplayName: new-to-rails

ContentLicense: CC BY-SA 2.5

Title: a simple regexp validator

Body:
^[a-zA-Z]+-?[a-zA-Z]+$

E.g.

def validate(whatever)
  reg = /^[a-zA-Z]+-?[a-zA-Z]+$/
return (reg.match(whatever)) ? true : false;
end


问:
Using dropbox-api-content-hasher without node
I have used dropbox-api-content-hasher (gitrepo here) within a node.js environment for an Electron project with great success, but now I need to use it in a Phonegap/cordova project and I've no idea how to replace the following:

```<code>const fs = require('fs');
const dch = require('dropbox-content-hasher');
</code>```

... with vanilla javascript so I can use it!

I have included the  but I need to access the dch variable to do the following:

```<code>const hasher = dch.create();
</code>```

and then access hasher the rest of what I need to do. I don't have the experience on how to convert it across, any ideas?

I am building in phonegap rather than cordova cli as I'm more experienced in this approach.

EDIT:

This is a fiddle of my attempt based on Alex's answer but I'm getting 'CryptoJS is not a constructor' in the web console. I don't know how to bring in the cryptojs library!

Fiddle here

答:
I just needed the same and adapted the example from the dropbox repo.
I use the crypto-js library. The code is in ES6 and is used in a quasar-framework app (which btw. might be interesting for you, due to phonegap/cordova):</p>

```<code>/**
 * Computes a hash using the same algorithm that the Dropbox API uses for the
* the "content_hash" metadata field.
*
* The `digest()` method returns a hexadecimal-encoded version
* of the digest of the hash.
* The "content_hash" field in the Dropbox API is a hexadecimal-encoded version
* of the digest.
*
* Example:
*
*     import DropboxContentHasher from 'dropboxContentHasher'
*
*     let hasher = new DropboxContentHasher()
*     hasher.update(content) // content is some string or CryptoJS.lib.WordArray
*     return hasher.digest()
*/

import cryptoJS from 'crypto-js'

const BLOCK_SIZE = 4 * 1024 * 1024

class DropboxContentHasher {
  constructor () {
    this._overallHasher = cryptoJS.algo.SHA256.create()
    this._blockHasher = cryptoJS.algo.SHA256.create()
    this._blockPos = 0
  }

  update (data) {
    let offset = 0
    while (offset < data.length) {
      if (this._blockPos === BLOCK_SIZE) {
        this._overallHasher.update(this._blockHasher.finalize())
        this._blockHasher = cryptoJS.algo.SHA256.create()
        this._blockPos = 0
      }
      let spaceInBlock = BLOCK_SIZE - this._blockPos
      let inputPartEnd = Math.min(data.length, offset + spaceInBlock)
      let inputPartLength = inputPartEnd - offset
      this._blockHasher.update(data.slice(offset, inputPartEnd))
      this._blockPos += inputPartLength
      offset = inputPartEnd
    }
  }

  digest () {
    if (this._blockPos > 0) {
      this._overallHasher.update(this._blockHasher.finalize())
      this._blockHasher = null
    }
    let r = this._overallHasher.finalize().toString()
    this._overallHasher = null // Make sure we can't use this object anymore.
    return r
  }
}

export default DropboxContentHasher
</code>```

Body:
I have used dropbox-api-content-hasher (gitrepo here) within a node.js environment for an Electron project with great success, but now I need to use it in a Phonegap/cordova project and I've no idea how to replace the following:

const fs = require('fs');
const dch = require('dropbox-content-hasher');

... with vanilla javascript so I can use it!

I have included the  but I need to access the dch variable to do the following:

const hasher = dch.create();

and then access hasher the rest of what I need to do. I don't have the experience on how to convert it across, any ideas?

I am building in phonegap rather than cordova cli as I'm more experienced in this approach.

EDIT:

This is a fiddle of my attempt based on Alex's answer but I'm getting 'CryptoJS is not a constructor' in the web console. I don't know how to bring in the cryptojs library!

Fiddle here

Body:
I just needed the same and adapted the example from the dropbox repo.
I use the crypto-js library. The code is in ES6 and is used in a quasar-framework app (which btw. might be interesting for you, due to phonegap/cordova):

/**
 * Computes a hash using the same algorithm that the Dropbox API uses for the
* the "content_hash" metadata field.
*
* The `digest()` method returns a hexadecimal-encoded version
* of the digest of the hash.
* The "content_hash" field in the Dropbox API is a hexadecimal-encoded version
* of the digest.
*
* Example:
*
*     import DropboxContentHasher from 'dropboxContentHasher'
*
*     let hasher = new DropboxContentHasher()
*     hasher.update(content) // content is some string or CryptoJS.lib.WordArray
*     return hasher.digest()
*/

import cryptoJS from 'crypto-js'

const BLOCK_SIZE = 4 * 1024 * 1024

class DropboxContentHasher {
  constructor () {
    this._overallHasher = cryptoJS.algo.SHA256.create()
    this._blockHasher = cryptoJS.algo.SHA256.create()
    this._blockPos = 0
  }

  update (data) {
    let offset = 0
    while (offset < data.length) {
      if (this._blockPos === BLOCK_SIZE) {
        this._overallHasher.update(this._blockHasher.finalize())
        this._blockHasher = cryptoJS.algo.SHA256.create()
        this._blockPos = 0
      }
      let spaceInBlock = BLOCK_SIZE - this._blockPos
      let inputPartEnd = Math.min(data.length, offset + spaceInBlock)
      let inputPartLength = inputPartEnd - offset
      this._blockHasher.update(data.slice(offset, inputPartEnd))
      this._blockPos += inputPartLength
      offset = inputPartEnd
    }
  }

  digest () {
    if (this._blockPos > 0) {
      this._overallHasher.update(this._blockHasher.finalize())
      this._blockHasher = null
    }
    let r = this._overallHasher.finalize().toString()
    this._overallHasher = null // Make sure we can't use this object anymore.
    return r
  }
}

export default DropboxContentHasher


问:
(SemanticUI + React) Changing HTML elements based on screen size best approach?
For example lets say I want to remove images when display size falls below 600px width. What would be the cleanest, fastest and most maintainable method to do that?

              Kristy

              Joined in 2013

              Kristy is an art director living in New York.

              22 Friends

```

<p>jQuery method</p>

<p><strong>EDIT</strong>: Definitely not using jQuery (it works, but read below):</p>

<blockquote>
  <p>jQuery Free</p>

  <p>jQuery is a DOM manipulation library. It reads from and writes to the
  DOM. React uses a virtual DOM (a JavaScript representation of the real
  DOM). React only writes patch updates to the DOM, but never reads from
  it.</p>

  <p>It is not feasible to keep real DOM manipulations in sync with React's
  virtual DOM. Because of this, all jQuery functionality has been
  re-implemented in React.</p>
</blockquote>

```
```

<p>SemanticUI method (Doc)</p>

```

  Contents

```

<p>Using React only?</p>

```  render() {
    let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />;
    return(

{content}

        <childComponent myWidth= {this.state.width}></childComponent >
        <childComponent2 myWidth= {this.state.width}></childComponent2 >

  )
```

答:
If your GUI changes significantly between the two versions, it may be worth it to maintain two sets of components, where appropriate. Then, you can render them like this:

```<code>render() {
    // don't create the component here with <>, just choose which one to use
    let TheComponent = this.state.width < 600 ? MobileComponent : DesktopComponent;

    return (
        <div>
            <TheComponent prop1=... />
            ...
        </div>
    );
}
</code>```

The advantage is that you don't create DOM nodes which are not needed, so the performance might be better compared to CSS-only solutions. And, it's sometimes much easier to reshuffle things around. The disadvantage is obviously that more code is required.

Body:
For example lets say I want to remove images when display size falls below 600px width. What would be the cleanest, fastest and most maintainable method to do that?

              Kristy

              Joined in 2013

              Kristy is an art director living in New York.

              22 Friends

jQuery method

EDIT: Definitely not using jQuery (it works, but read below):

jQuery Free

jQuery is a DOM manipulation library. It reads from and writes to the
  DOM. React uses a virtual DOM (a JavaScript representation of the real
  DOM). React only writes patch updates to the DOM, but never reads from
  it.

It is not feasible to keep real DOM manipulations in sync with React's
  virtual DOM. Because of this, all jQuery functionality has been
  re-implemented in React.

SemanticUI method (Doc)

  Contents

Using React only?

  render() {
    let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />;
    return(

{content}

        <childComponent myWidth= {this.state.width}></childComponent >
        <childComponent2 myWidth= {this.state.width}></childComponent2 >

  )

Body:
If your GUI changes significantly between the two versions, it may be worth it to maintain two sets of components, where appropriate. Then, you can render them like this:

render() {
    // don't create the component here with <>, just choose which one to use
    let TheComponent = this.state.width < 600 ? MobileComponent : DesktopComponent;

    return (
        <div>
            <TheComponent prop1=... />
            ...
        </div>
    );
}

The advantage is that you don't create DOM nodes which are not needed, so the performance might be better compared to CSS-only solutions. And, it's sometimes much easier to reshuffle things around. The disadvantage is obviously that more code is required.


问:
React styling in Rebass - css prefix?
I played with rebass for few day, and i am thinking use rebass for my future project, but i'm not sure if rebass have some way how to handle css prefix. Is there anybody who worked with Rebass and have some experience with that?

In the documentation I could not find anything about it.

答:
Rebass is built with Styled-Components, and they have it set up so all CSS rules are automatically vendor prefixed.

The official word from the Styled-Components docs:
"The CSS rules are automatically vendor prefixed, so you don't have to think about it."

Title: React styling in Rebass - css prefix?


问:
Postgres - Calculating group percentile for individual object
My app has an assessments table. Each assessment scores people on a variety of levels, and is associated with a group. So something like this:

```<code>id: 'some-assessment',
user_id: 'some-user',
group_id: 'some-group',
overall_score: 98,
speed_score: 99,
vision_score: 97
</code>```

When pulling an assessment from the database, I want to calculate statistics for each score relative to other scores for the same user or group as part of the returned object. As in, I want to return the following:

```<code>id: 'some-assessment',
user_id: 'some-user',
group_id: 'some-group',
overall_score: 98,
overall_score_user_percentile: 75, // ie, this score is in the 75th percentile of this users's other scores
overall_score_group_percentile: 60, // 60th percentile for group
speed_score: 99,
speed_score_user_percentile: 72,
speed_score_group_percentile: 63,
vision_score: 97,
vision_score_user_percentile: 71,
vision_score_group_percentile: 65,
</code>```

I tried to do explore this by generating the following query (based off the use of ntile in an answer to this question:

```<code>SELECT
  asmt.*,
  ntile(100) OVER (ORDER BY overall_score) AS overall_score_group_percentile
FROM
  assessments asmt
WHERE
  asmt.id='some-assessment'
</code>```

Note that this doesn't yet include logic that actually limits the overall_score_group_percentile to other assessments within the group.

Already, I'm running into an issue, which is that it appears that the overall_score_group_percentile calculates the percentile of the current assessment in the current group of assessments -- which is just the current assessment.

In other words, I'm calculating the assessment's percentile within a list of only that one assessment itself. I'm hoping to calculate it within a wider specified list (either of the user's assessments, or the group's).

So I'm always getting 1 as the overall_score_group_percentile.

Any ideas how to calculate the percentile rank of this assessment vs some other set of assessments?

I've tried this as well, in an attempt to widen the comparison group to the full assessments table (before I try to narrow it by group_id):

```<code>SELECT
  asmt.*,
  ntile(100) OVER (SELECT overall_score FROM assessments ORDER BY overall_score) AS overall_score_group_percentile
FROM
  assessments asmt
WHERE
  asmt.id='some-assessment'
</code>```

But no dice. I just get a syntax error.

Thanks! Any help sorting through this would be much appreciated.

答:
I think you just need a partition by:

```<code>SELECT asmt.*,
       ntile(100) OVER (PARTITION BY group_id ORDER BY overall_score) AS overall_score_group_percentile
FROM assessments asmt
WHERE asmt.id = 'some-assessment';
</code>```

Body:
My app has an assessments table. Each assessment scores people on a variety of levels, and is associated with a group. So something like this:

id: 'some-assessment',
user_id: 'some-user',
group_id: 'some-group',
overall_score: 98,
speed_score: 99,
vision_score: 97

When pulling an assessment from the database, I want to calculate statistics for each score relative to other scores for the same user or group as part of the returned object. As in, I want to return the following:

id: 'some-assessment',
user_id: 'some-user',
group_id: 'some-group',
overall_score: 98,
overall_score_user_percentile: 75, // ie, this score is in the 75th percentile of this users's other scores
overall_score_group_percentile: 60, // 60th percentile for group
speed_score: 99,
speed_score_user_percentile: 72,
speed_score_group_percentile: 63,
vision_score: 97,
vision_score_user_percentile: 71,
vision_score_group_percentile: 65,

I tried to do explore this by generating the following query (based off the use of ntile in an answer to this question:

SELECT
  asmt.*,
  ntile(100) OVER (ORDER BY overall_score) AS overall_score_group_percentile
FROM
  assessments asmt
WHERE
  asmt.id='some-assessment'

Note that this doesn't yet include logic that actually limits the overall_score_group_percentile to other assessments within the group.

Already, I'm running into an issue, which is that it appears that the overall_score_group_percentile calculates the percentile of the current assessment in the current group of assessments -- which is just the current assessment.

In other words, I'm calculating the assessment's percentile within a list of only that one assessment itself. I'm hoping to calculate it within a wider specified list (either of the user's assessments, or the group's).

So I'm always getting 1 as the overall_score_group_percentile.

Any ideas how to calculate the percentile rank of this assessment vs some other set of assessments?

I've tried this as well, in an attempt to widen the comparison group to the full assessments table (before I try to narrow it by group_id):

SELECT
  asmt.*,
  ntile(100) OVER (SELECT overall_score FROM assessments ORDER BY overall_score) AS overall_score_group_percentile
FROM
  assessments asmt
WHERE
  asmt.id='some-assessment'

But no dice. I just get a syntax error.

Thanks! Any help sorting through this would be much appreciated.

Body:
I think you just need a partition by:

SELECT asmt.*,
       ntile(100) OVER (PARTITION BY group_id ORDER BY overall_score) AS overall_score_group_percentile
FROM assessments asmt
WHERE asmt.id = 'some-assessment';


问:
Searching for a Key in Multivalue Dictionaries in C#
I want to set up a lookup table like so:

```<code> Key           Value
 -----         ------------------
 Cat           Lion, Tiger, Cheetah
 Fish          Dolphin, Whale
 Dog .         Pitbull, Doberman
</code>```

An input of "Lion" would return the key "Cat"

I have set up 3 possible ways to initialize the data:

A Dictionary:

```<code>var map = new Dictionary<string,string>
{
    ["Dolphin"] = "Fish",
    ["Lion"] = "Cat",
    //....
};
</code>```

A HashSet:

```<code>var data = new Dictionary<string, HashSet<string>>
{
    {"cat", new HashSet<string> {"Lion", "Tiger", "Cheetah"}},
    {"fish", new HashSet<string> {"Dolphin", "Whale"}},
    {"Dog", new HashSet<string> {"Pitbull", "Doberman"}}
};
</code>```

A tuple:

```<code>var data = new List<Tuple<string, List<string>>>
{
    Tuple.Create<string,List<string>> ("Cat", new List<string> { "Cheetah", "Lion" }),
    Tuple.Create<string,List<string>> ("Dog", new List<string> { "Doberman", "Pitbull" }),
    Tuple.Create<string,List<string>> ("Fish", new List<string> { "Dolphin", "Whale" }),

};
</code>```

Given an animal, I want to return its type.
I know for the dictionary I can call the ContainsKey method.

Is there something similar for the other two options?

The data set isn't that big, (~15 keys that have 10 or so values), so I'm also wondering if one option would be better than the other in terms of performance.

答:
I am suggesting a bit different approach.

```<code>public abstract class Animal
{
    public string Type { get; }
    public string Name { get; }

    protected Animal(string type, string name)
    {
        Type = type;
        Name = name;
    }
}

public class Cat : Animal
{
    public Cat(string name) : base("Cat", name)
    {
    }
}

public class Fish : Animal
{
    public Fish(string name) : base("Fish", name)
    {
    }
}

public static class Program
{
    public static void Main(string[] args)
    {
        List<Animal> list = new List<Animal>();
        list.Add(new Cat("Cheetah"));
        list.Add(new Fish("Dolphin"));

        var cheetahType = list.FirstOrDefault(animal => animal.Name == "Cheetah")?.Type;
        var doplhinType = list.FirstOrDefault(animal => animal.Name == "Dolphin")?.Type;
    }
}
</code>```

If you don't actually need that much, you can make Animal nonabstract and define enum instead of string Type and remove derived children.

Body:
I want to set up a lookup table like so:

 Key           Value
 -----         ------------------
 Cat           Lion, Tiger, Cheetah
 Fish          Dolphin, Whale
 Dog .         Pitbull, Doberman

An input of "Lion" would return the key "Cat"

I have set up 3 possible ways to initialize the data:

A Dictionary:

var map = new Dictionary<string,string>
{
    ["Dolphin"] = "Fish",
    ["Lion"] = "Cat",
    //....
};

A HashSet:

var data = new Dictionary<string, HashSet<string>>
{
    {"cat", new HashSet<string> {"Lion", "Tiger", "Cheetah"}},
    {"fish", new HashSet<string> {"Dolphin", "Whale"}},
    {"Dog", new HashSet<string> {"Pitbull", "Doberman"}}
};

A tuple:

var data = new List<Tuple<string, List<string>>>
{
    Tuple.Create<string,List<string>> ("Cat", new List<string> { "Cheetah", "Lion" }),
    Tuple.Create<string,List<string>> ("Dog", new List<string> { "Doberman", "Pitbull" }),
    Tuple.Create<string,List<string>> ("Fish", new List<string> { "Dolphin", "Whale" }),

};

Given an animal, I want to return its type.
I know for the dictionary I can call the ContainsKey method.

Is there something similar for the other two options?

The data set isn't that big, (~15 keys that have 10 or so values), so I'm also wondering if one option would be better than the other in terms of performance.

Body:
I am suggesting a bit different approach.

public abstract class Animal
{
    public string Type { get; }
    public string Name { get; }

    protected Animal(string type, string name)
    {
        Type = type;
        Name = name;
    }
}

public class Cat : Animal
{
    public Cat(string name) : base("Cat", name)
    {
    }
}

public class Fish : Animal
{
    public Fish(string name) : base("Fish", name)
    {
    }
}

public static class Program
{
    public static void Main(string[] args)
    {
        List<Animal> list = new List<Animal>();
        list.Add(new Cat("Cheetah"));
        list.Add(new Fish("Dolphin"));

        var cheetahType = list.FirstOrDefault(animal => animal.Name == "Cheetah")?.Type;
        var doplhinType = list.FirstOrDefault(animal => animal.Name == "Dolphin")?.Type;
    }
}

If you don't actually need that much, you can make Animal nonabstract and define enum instead of string Type and remove derived children.


问:
How to hide SideBar Bootstrap when the screen reaches 660px
I'm trying to hide Bootstrap's SideBar when I zoom in. "@media only screen and (max-width: 660px)" but the result is that it is automatically deployed, I do not want that to happen.

Este es el código de bootstrap:

```<code>@media only screen and (max-width:660px) {
#header {
    height: 160px
}

    #header .brand {
        width: 100%
    }

    #header .user-nav ul {
        padding-left: 0
    }

    #header .toggle-navigation.toggle-left {
        float: left
    }

.sidebar {
    margin-left: -240px
}

.sidebar-toggle {
    margin-left: 0;
    width: 100%
}

.main-content-wrapper {
    margin-left: 0
}

.main-content-toggle-left {
    margin-left: 0px;
}

.sidebarRight {
    top: 160px;
    width: 100%
}

.user-nav ul li {
    font-size: 12px
}

}
</code>```

this is my html code

答:
Use a new Class and insert
    visibility: hidden;</p>

```<code>@media(max-width: 660px){
  .hide{
    visibility: hidden;
  }
}

<nav class="sidebar sidebar sidebar-toggle hide">
</code>```

Body:
I'm trying to hide Bootstrap's SideBar when I zoom in. "@media only screen and (max-width: 660px)" but the result is that it is automatically deployed, I do not want that to happen.

Este es el código de bootstrap:

@media only screen and (max-width:660px) {
#header {
    height: 160px
}

    #header .brand {
        width: 100%
    }

    #header .user-nav ul {
        padding-left: 0
    }

    #header .toggle-navigation.toggle-left {
        float: left
    }

.sidebar {
    margin-left: -240px
}

.sidebar-toggle {
    margin-left: 0;
    width: 100%
}

.main-content-wrapper {
    margin-left: 0
}

.main-content-toggle-left {
    margin-left: 0px;
}

.sidebarRight {
    top: 160px;
    width: 100%
}

.user-nav ul li {
    font-size: 12px
}

}

this is my html code

Body:
Use a new Class and insert
    visibility: hidden;

@media(max-width: 660px){
  .hide{
    visibility: hidden;
  }
}

<nav class="sidebar sidebar sidebar-toggle hide">


问:
Specify path to files
First of all, I'm totally new to PHP, so I'll need a bit more explanation. I'm trying to make a Multi-language site using PHP, the problem is; when I create a new folder like: domain.tld/test/location (location is new in this case), the language files which are located at domain.tld/test, are of course not imported. How can you clarify where these files NEED to be coming from?

Script

```<code><?php
// include language configuration file based on selected language
echo realpath(dirname(__FILE__));
$lang = "en";
if(isset($_GET['lang'])){
    $lang = $_GET['lang'];
}
require_once("lang.".$lang.".php");
?>
</code>```

答:
Try:

```<code>require_once __DIR__ . '/../lang.' . $lang . '.php';
</code>```

Alternatively you could load upfront for all your Php files see:

```<code>auto_prepend_file
</code>```

Title: Specify path to files

Body:
First of all, I'm totally new to PHP, so I'll need a bit more explanation. I'm trying to make a Multi-language site using PHP, the problem is; when I create a new folder like: domain.tld/test/location (location is new in this case), the language files which are located at domain.tld/test, are of course not imported. How can you clarify where these files NEED to be coming from?

Script

<?php
// include language configuration file based on selected language
echo realpath(dirname(__FILE__));
$lang = "en";
if(isset($_GET['lang'])){
    $lang = $_GET['lang'];
}
require_once("lang.".$lang.".php");
?>

Body:
Try:

require_once __DIR__ . '/../lang.' . $lang . '.php';

Alternatively you could load upfront for all your Php files see:

auto_prepend_file


问:
R - Compare 2 matrices to find rows which rows aren't in both
I have two large matrices in R of differing sizes, 371 x 1502 (A) and 371 x 1207 (B).

All of matrix B is included in A. A also contains many other rows mixed in. I am looking for a way to create a new matrix, C, which contains all the rows in A not found in B.

I am sure there is a way to do this using data.tables and keys but I can't for the life of me figure it out.

example data:

```<code>a = t(matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3))
b = t(matrix(c(1,2,3,7,8,9), nrow = 3))
</code>```

Any help is appreciated,

Thanks.

答:
I would do it in base R:

```<code>a[!duplicated(rbind(b,a))[(nrow(b)+1):(nrow(a)+nrow(b))], ]
</code>```

... But a data.table solution might be more elegant and/or quicker.

Thanks to @thelatemail, here is the data.table version:

```<code>a[!b, on=names(a)]
</code>```

And here is a benchmark of all solutions proposed so far, here and by  Maurits Evers:

```<code>require('data.table')
require('plyr')
require('microbenchmark')

n = 371
n1 = 1502
n2 = 1207

b = matrix(0 + sample.int(n * n2), ncol = n)
a = rbind(matrix(n*n2+1 + sample.int(n * (n1 - n2)), ncol = n), b)
b = b[sample.int(nrow(b)), ]

# preparing the data.table and data.frame versions of the data:
a.dt = data.table(a)
b.dt = data.table(b)
a.df = as.data.frame(a)
b.df = as.data.frame(b)

microbenchmark(
  BASE_R = a[!duplicated(rbind(b,a))[(nrow(b)+1):(nrow(a)+nrow(b))], ],
  DATA.TABLE = a.dt[!b.dt, on=names(a.dt)],
  DATA.TABLE2 = fsetdiff(a.dt, b.dt),
  PLYR = anti_join(a.df, b.df),
  times = 100
)
</code>```

For this problem, the plyr solution proposed in the other answer is the fastest. The two data.table solutions are trailing it closely, and the base R version is much slower.

```<code>    Unit: milliseconds
        expr        min         lq       mean     median        uq       max neval cld
      BASE_R 1125.05968 1412.13170 1555.82674 1577.81665 1703.3674 1927.1632   100   c
  DATA.TABLE   54.68581   83.99182  117.90571   91.86808  123.8300  318.3788   100  b
 DATA.TABLE2   58.44053   86.90981  127.11152   97.39086  138.8306  328.1396   100  b
        PLYR   30.87235   49.32260   61.02968   53.66639   59.6925  278.6965   100 a
</code>```

Body:
I have two large matrices in R of differing sizes, 371 x 1502 (A) and 371 x 1207 (B).

All of matrix B is included in A. A also contains many other rows mixed in. I am looking for a way to create a new matrix, C, which contains all the rows in A not found in B.

I am sure there is a way to do this using data.tables and keys but I can't for the life of me figure it out.

example data:

a = t(matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3))
b = t(matrix(c(1,2,3,7,8,9), nrow = 3))

Any help is appreciated,

Thanks.

Body:
I would do it in base R:

a[!duplicated(rbind(b,a))[(nrow(b)+1):(nrow(a)+nrow(b))], ]

... But a data.table solution might be more elegant and/or quicker.

Thanks to @thelatemail, here is the data.table version:

a[!b, on=names(a)]

And here is a benchmark of all solutions proposed so far, here and by  Maurits Evers:

require('data.table')
require('plyr')
require('microbenchmark')

n = 371
n1 = 1502
n2 = 1207

b = matrix(0 + sample.int(n * n2), ncol = n)
a = rbind(matrix(n*n2+1 + sample.int(n * (n1 - n2)), ncol = n), b)
b = b[sample.int(nrow(b)), ]

# preparing the data.table and data.frame versions of the data:
a.dt = data.table(a)
b.dt = data.table(b)
a.df = as.data.frame(a)
b.df = as.data.frame(b)

microbenchmark(
  BASE_R = a[!duplicated(rbind(b,a))[(nrow(b)+1):(nrow(a)+nrow(b))], ],
  DATA.TABLE = a.dt[!b.dt, on=names(a.dt)],
  DATA.TABLE2 = fsetdiff(a.dt, b.dt),
  PLYR = anti_join(a.df, b.df),
  times = 100
)

For this problem, the plyr solution proposed in the other answer is the fastest. The two data.table solutions are trailing it closely, and the base R version is much slower.

    Unit: milliseconds
        expr        min         lq       mean     median        uq       max neval cld
      BASE_R 1125.05968 1412.13170 1555.82674 1577.81665 1703.3674 1927.1632   100   c
  DATA.TABLE   54.68581   83.99182  117.90571   91.86808  123.8300  318.3788   100  b
 DATA.TABLE2   58.44053   86.90981  127.11152   97.39086  138.8306  328.1396   100  b
        PLYR   30.87235   49.32260   61.02968   53.66639   59.6925  278.6965   100 a


问:
Observing changes in visibleCells array of UICollectionView
I would like to know when the count of visibleCells property of UICollectionView changes.
I know that I can observe objects that inherit from NSObject as long as the property I want to observe is dynamic. For example:

```<code>let view = UIView()
view.observe(\.isHidden, options: .new) { view, change in
  print(change.newValue)
}
</code>```

How can I observe visibleCells of UICollectionView in a similar manner?

答:
You can see the visible cell rendering in willDisplay by
For cell in collectionview.visiblecells {
}</p>

Body:
I would like to know when the count of visibleCells property of UICollectionView changes.
I know that I can observe objects that inherit from NSObject as long as the property I want to observe is dynamic. For example:

let view = UIView()
view.observe(\.isHidden, options: .new) { view, change in
  print(change.newValue)
}

How can I observe visibleCells of UICollectionView in a similar manner?


问:
Linker Errors LNK2019 and LNK1120 in single file code
C++ code of my compiler
There is only one .cpp file in my Win32 console project. I am facing these LNK compile-time errors in my code. I am working on Visual Studio 12. I have tried a lot of things but nothing seems to have solved my issue.

I am writing code for a compiler that was originally built in Java and now the task at hand is to convert it in C++. I am looking forward to some useful solutions.
Can anyone help me with this task?

答:
From the documentation:

unresolved external symbol 'symbol' referenced in function 'function'

The compiled code for function makes a reference or call to symbol,
but that symbol isn't defined in any of the libraries or object files
specified to the linker.

This error message is followed by fatal error
LNK1120. You must fix all LNK2001 and LNK2019 errors to fix error
LNK1120.

You are referencing something not in the file that you are not linking to.


问:
nginx docker container: 502 bad gateway response
I've a service listening to 8080 port. This one is not a container.

Then, I've created a nginx container using official image:

```<code>docker run --name nginx -d -v /root/nginx/conf:/etc/nginx/conf.d -p 443:443 -p 80:80 nginx
</code>```

After all:

```<code># netstat -tupln | grep 443
tcp6       0      0 :::443                  :::*                    LISTEN      3482/docker-proxy
# netstat -tupln | grep 80
tcp6       0      0 :::80                   :::*                    LISTEN      3489/docker-proxy
tcp6       0      0 :::8080                 :::*                    LISTEN      1009/java
</code>```

Nginx configuration is:

```<code>upstream eighty {
    server 127.0.0.1:8080;
}

server {
    listen 80;
    server_name eighty.domain.com;

    location / {
      proxy_pass                        http://eighty;
    }
}
</code>```

I've checked I'm able to connect with with this server with # curl http://127.0.0.1:8080

```<code> <html><head><meta http-equiv='refresh'
 content='1;url=/login?from=%2F'/><script>window.location.replace('/login?from=%2F');</script></head><body
 style='background-color:white; color:white;'>
 ...
</code>```

It seems running well, however, when I'm trying to access using my browser, nginx tells bt a 502 bad gateway response.

I'm figuring out it can be a problem related with the visibility between a open by a non-containerized process and a container. Can I container stablish connection to a port open by other non-container process?

EDIT

Logs where upstream { server 127.0.0.1:8080; }:

```<code>2016/07/13 09:06:53 [error] 5#5: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 62.57.217.25, server: eighty.domain.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8080/", host: "eighty.domain.com"
62.57.217.25 - - [13/Jul/2016:09:06:53 +0000] "GET / HTTP/1.1" 502 173 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0" "-"
</code>```

Logs where upstream { server 0.0.0.0:8080; }:

```<code>62.57.217.25 - - [13/Jul/2016:09:00:30 +0000] "GET / HTTP/1.1" 502 173 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0" "-" 2016/07/13 09:00:30 [error] 5#5: *1 connect() failed (111: Connection refused) while connecting to upstream, client:
62.57.217.25, server: eighty.domain.com, request: "GET / HTTP/1.1", upstream: "http://0.0.0.0:8080/", host: "eighty.domain.com" 2016/07/13 09:00:32 [error] 5#5: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 62.57.217.25, server: eighty.domain.com, request: "GET / HTTP/1.1", upstream: "http://0.0.0.0:8080/", host: "eighty.domain.com"
62.57.217.25 - - [13/Jul/2016:09:00:32 +0000] "GET / HTTP/1.1" 502 173 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0" "-"
</code>```

Any ideas?

答:
The Problem

Localhost is a bit tricky when it comes to containers. Within a docker container, localhost points to the container itself.
This means, with an upstream like this:

```<code>upstream foo{
  server 127.0.0.1:8080;
}
</code>```

or

```<code>upstream foo{
  server 0.0.0.0:8080;
}
</code>```

you are telling nginx to pass your request to the local host.
But in the context of a docker-container, localhost (and the corresponding ip addresses) are pointing to the container itself:

by addressing 127.0.0.1 you will never reach your host machine, if your container is not on the host network.

Solutions

Host Networking

You can choose to run nginx on the same network as your host:

```<code>docker run --name nginx -d -v /root/nginx/conf:/etc/nginx/conf.d --net=host nginx
</code>```

Note that you do not need to expose any ports in this case.

This works though you lose the benefit of docker networking. If you have multiple containers that should communicate through the docker network, this approach can be a problem. If you just want to deploy nginx with docker and do not want to use any advanced docker network features, this approach is fine.

Access the hosts remote IP Address

Another approach is to reconfigure your nginx upstream directive to directly connect to your host machine by adding its remote IP address:

```<code>upstream foo{
  //insert your hosts ip here
  server 192.168.99.100:8080;
}
</code>```

The container will now go through the network stack and resolve your host correctly:

You can also use your DNS name if you have one. Make sure docker knows about your DNS server.

ContentLicense: CC BY-SA 4.0

Body:
I've a service listening to 8080 port. This one is not a container.

Then, I've created a nginx container using official image:

docker run --name nginx -d -v /root/nginx/conf:/etc/nginx/conf.d -p 443:443 -p 80:80 nginx

After all:

# netstat -tupln | grep 443
tcp6       0      0 :::443                  :::*                    LISTEN      3482/docker-proxy
# netstat -tupln | grep 80
tcp6       0      0 :::80                   :::*                    LISTEN      3489/docker-proxy
tcp6       0      0 :::8080                 :::*                    LISTEN      1009/java

Nginx configuration is:

upstream eighty {
    server 127.0.0.1:8080;
}

server {
    listen 80;
    server_name eighty.domain.com;

    location / {
      proxy_pass                        http://eighty;
    }
}

I've checked I'm able to connect with with this server with # curl http://127.0.0.1:8080

 <meta http-equiv='refresh'
 content='1;url=/login?from=%2F'/>
 ...

It seems running well, however, when I'm trying to access using my browser, nginx tells bt a 502 bad gateway response.

I'm figuring out it can be a problem related with the visibility between a open by a non-containerized process and a container. Can I container stablish connection to a port open by other non-container process?

EDIT

Logs where upstream { server 127.0.0.1:8080; }:

2016/07/13 09:06:53 [error] 5#5: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 62.57.217.25, server: eighty.domain.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8080/", host: "eighty.domain.com"
62.57.217.25 - - [13/Jul/2016:09:06:53 +0000] "GET / HTTP/1.1" 502 173 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0" "-"

Logs where upstream { server 0.0.0.0:8080; }:

62.57.217.25 - - [13/Jul/2016:09:00:30 +0000] "GET / HTTP/1.1" 502 173 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0" "-" 2016/07/13 09:00:30 [error] 5#5: *1 connect() failed (111: Connection refused) while connecting to upstream, client:
62.57.217.25, server: eighty.domain.com, request: "GET / HTTP/1.1", upstream: "http://0.0.0.0:8080/", host: "eighty.domain.com" 2016/07/13 09:00:32 [error] 5#5: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 62.57.217.25, server: eighty.domain.com, request: "GET / HTTP/1.1", upstream: "http://0.0.0.0:8080/", host: "eighty.domain.com"
62.57.217.25 - - [13/Jul/2016:09:00:32 +0000] "GET / HTTP/1.1" 502 173 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0" "-"

Any ideas?

Body:
The Problem

Localhost is a bit tricky when it comes to containers. Within a docker container, localhost points to the container itself.
This means, with an upstream like this:

upstream foo{
  server 127.0.0.1:8080;
}

or

upstream foo{
  server 0.0.0.0:8080;
}

you are telling nginx to pass your request to the local host.
But in the context of a docker-container, localhost (and the corresponding ip addresses) are pointing to the container itself:

by addressing 127.0.0.1 you will never reach your host machine, if your container is not on the host network.

Solutions

Host Networking

You can choose to run nginx on the same network as your host:

docker run --name nginx -d -v /root/nginx/conf:/etc/nginx/conf.d --net=host nginx

Note that you do not need to expose any ports in this case.

This works though you lose the benefit of docker networking. If you have multiple containers that should communicate through the docker network, this approach can be a problem. If you just want to deploy nginx with docker and do not want to use any advanced docker network features, this approach is fine.

Access the hosts remote IP Address

Another approach is to reconfigure your nginx upstream directive to directly connect to your host machine by adding its remote IP address:

upstream foo{
  //insert your hosts ip here
  server 192.168.99.100:8080;
}

The container will now go through the network stack and resolve your host correctly:

You can also use your DNS name if you have one. Make sure docker knows about your DNS server.


问:
How can I center a multiple line text on an image in this case?
I have an image that takes up the whole screen. Now I want to have centered text over it. The method that I'm using works great for single line text but when I have two lines, it centers the longest line and aligns all other lines to the left of the longest one. How can I make all of them centered?

Here's the class that I'm using to center my text over the image:

```<code>.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</code>```

答:
Add text-align:center;

```<code>.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align:center;
}
</code>```

Updated demo at https://codepen.io/gpetrioli/pen/eeoKyo

Body:
I have an image that takes up the whole screen. Now I want to have centered text over it. The method that I'm using works great for single line text but when I have two lines, it centers the longest line and aligns all other lines to the left of the longest one. How can I make all of them centered?

Here's the class that I'm using to center my text over the image:

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Body:
Add text-align:center;

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align:center;
}

Updated demo at https://codepen.io/gpetrioli/pen/eeoKyo


问:
Javascript regex - getting function name from string
I am trying to get a function name from a string in javascript.

Let's say I have this string:

```<code>function multiply($number) {
    return ($number * 2);
}
</code>```

I am using the following regex in javascript:

```<code>/([a-zA-Z_{1}][a-zA-Z0-9_]+)\(/g
</code>```

However, what is selected is multiply(. This is wrong. What I want is the word multiply without the the (, though the regex should keep in mind that the function name must be attached an (.

I can't get this done. How can I make the proper regex for this? I know that this is not something I really should do and that it is quite error sensitive, but I still wanna try to make this work.

答:
You can use:

```<code>var name = functionString.match(/function(.*?)\(/)[1].trim();
</code>```

Get anything between function and the first ( (using a non-gredy quantifier *?), then get the value of the group [1]. And finally, trim to remove surrounding spaces.

Example:

var functionString = "function dollar$$$AreAllowedToo () {  }";

var name = functionString.match(/function(.*?)\(/)[1].trim();

console.log(name);```
</div>
</div>
</p>

<p><strong>Notes:</strong></p>

<ol>
<li>The characters allowed in javascript for variable names are way too much to express in a set. My answer takes care of that. <strong>More about this here</strong></li>
<li>You may want to consider the posibility of a comment between <code>function</code> and <code>(</code>, or a new line too. But this really depends on how you intend to use this regex.</li>
</ol>

<p>take for examlpe:</p>

```function /*this is a tricky comment*/ functionName // another one
   (param1, param2) {

}
```

Body:
I am trying to get a function name from a string in javascript.

Let's say I have this string:

function multiply($number) {
    return ($number * 2);
}

I am using the following regex in javascript:

/([a-zA-Z_{1}][a-zA-Z0-9_]+)\(/g

However, what is selected is multiply(. This is wrong. What I want is the word multiply without the the (, though the regex should keep in mind that the function name must be attached an (.

I can't get this done. How can I make the proper regex for this? I know that this is not something I really should do and that it is quite error sensitive, but I still wanna try to make this work.

Body:
You can use:

var name = functionString.match(/function(.*?)\(/)[1].trim();

Get anything between function and the first ( (using a non-gredy quantifier *?), then get the value of the group [1]. And finally, trim to remove surrounding spaces.

Example:

var functionString = "function dollar$$$AreAllowedToo () {  }";

var name = functionString.match(/function(.*?)\(/)[1].trim();

console.log(name);

Notes:

The characters allowed in javascript for variable names are way too much to express in a set. My answer takes care of that. More about this here

You may want to consider the posibility of a comment between function and (, or a new line too. But this really depends on how you intend to use this regex.

take for examlpe:

function /*this is a tricky comment*/ functionName // another one
   (param1, param2) {

}


问:
Message key as Long in Kafka Streams
I am trying to use Long as type of the message key, but I get

```<code>Exception in thread "kafka_stream_app-f236aaca-3f90-469d-9d32-20ff694806ff-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Failed to deserialize key for record. topic=test, partition=0, offset=0
    at org.apache.kafka.streams.processor.internals.SourceNodeRecordDeserializer.deserialize(SourceNodeRecordDeserializer.java:38)
    at org.apache.kafka.streams.processor.internals.RecordQueue.addRawRecords(RecordQueue.java:84)
    at org.apache.kafka.streams.processor.internals.PartitionGroup.addRawRecords(PartitionGroup.java:117)
    at org.apache.kafka.streams.processor.internals.StreamTask.addRecords(StreamTask.java:474)
    at org.apache.kafka.streams.processor.internals.StreamThread.addRecordsToTasks(StreamThread.java:642)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:548)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:519)
Caused by: org.apache.kafka.common.errors.SerializationException: Size of data received by LongDeserializer is not 8
</code>```

I checked and the data.length is 7.

In streamsConfiguration I've set

```<code>streamsConfiguration.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.Long().getClass().getName());
</code>```

and I use

```<code>KStream<Long, GenericRecord> stream = builder.stream(topic);
</code>```

I've tried sending the message via a simple app and also with kafka-avro-console-producer:

```<code>/opt/confluent-3.3.0/bin/kafka-avro-console-producer \
--broker-list localhost:9092 \
--topic test \
--property key.separator=, \
--property parse.key=true \
--property key.schema='{"type":"long"}' \
--property value.schema='{"type":"string"}' \
--property schema.registry.url=http://localhost:8081
</code>```

with message

```<code>123,"293"
</code>```

Using the kafka-avro-console-consumer I can consume the message and see (with --property print.key=true that the key sent is correctly 123)

Any idea what could be wrong when decoding the message?

答:
Because you are using kafka-avro-console-producer the key is not serialized as plain Long but as an Avro type. Thus, you need to use a corresponding Avro Serde with the same schema you used on the write path (ie, '{"type":"long"}").

Also, your return type will not be Long but an Avro type.

Title: Message key as Long in Kafka Streams

Body:
I am trying to use Long as type of the message key, but I get

Exception in thread "kafka_stream_app-f236aaca-3f90-469d-9d32-20ff694806ff-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Failed to deserialize key for record. topic=test, partition=0, offset=0
    at org.apache.kafka.streams.processor.internals.SourceNodeRecordDeserializer.deserialize(SourceNodeRecordDeserializer.java:38)
    at org.apache.kafka.streams.processor.internals.RecordQueue.addRawRecords(RecordQueue.java:84)
    at org.apache.kafka.streams.processor.internals.PartitionGroup.addRawRecords(PartitionGroup.java:117)
    at org.apache.kafka.streams.processor.internals.StreamTask.addRecords(StreamTask.java:474)
    at org.apache.kafka.streams.processor.internals.StreamThread.addRecordsToTasks(StreamThread.java:642)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:548)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:519)
Caused by: org.apache.kafka.common.errors.SerializationException: Size of data received by LongDeserializer is not 8

I checked and the data.length is 7.

In streamsConfiguration I've set

streamsConfiguration.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.Long().getClass().getName());

and I use

KStream<Long, GenericRecord> stream = builder.stream(topic);

I've tried sending the message via a simple app and also with kafka-avro-console-producer:

/opt/confluent-3.3.0/bin/kafka-avro-console-producer \
--broker-list localhost:9092 \
--topic test \
--property key.separator=, \
--property parse.key=true \
--property key.schema='{"type":"long"}' \
--property value.schema='{"type":"string"}' \
--property schema.registry.url=http://localhost:8081

with message

123,"293"

Using the kafka-avro-console-consumer I can consume the message and see (with --property print.key=true that the key sent is correctly 123)

Any idea what could be wrong when decoding the message?


问:
Numbering child elements in ReactJS
I'm new to React, and I'm confused about how it's supposed to work.

I want to make a little assessment app with questions, sections, and a totals section.

I marked up what I want inside of a home page component like this:

```<code>export default class Home extends React.Component {
    public render() {
        return <SurvivalTest>
            <Section title="Requirements">
                <Question>
                    Does the project have a clear, unambiguous vision statement
                    or mission statement?
                </Question>
                <Question>
                    Do all team members believe the vision is realistic?
                </Question>
                <Question>
                    Does the project have a business case that details the
                    business benefit and how the benefit will be measured?
                </Question>
            </Section>
            <Section title="Planning">
                <Question>
                    Does the project have a detailed, written Software
                    Development Plan?
                </Question>
                <Question>
                    Were the schedule and budget estimates officially updated
                    at the end of the most recently completed phase?
                </Question>
                <Question>
                    Does the project have detailed, written architecture and
                    design documents?
                </Question>
            </Section>
            <TotalsSection />
        </SurvivalTest>;
    }
}
</code>```

The questions each have 4 possible answers, scored 0-3.  The answers are the same for all questions and they are: "No", "Not really", "Probably", and "Yes".  The Section component the table element and labels for the answers are in the table headers.

```<code>export class Question extends React.Component {
    constructor() {
        super();
        this.state = { score: 0 };
    }

    public render() {
        return <tr>
            <td>
                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 0 })} checked={this.state.score === 0} />
            </td>
            <td>
                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 1 })} checked={this.state.score === 1} />
            </td>
            <td>
                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 2 })} checked={this.state.score === 2} />
            </td>
            <td>
                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 3 })} checked={this.state.score === 3} />
            </td>
            <td>
                {??? + '. ' + this.props.children}
            </td>
        </tr>;
    }
}
</code>```

How do I number the questions automatically?  I want to display a question number before the question text, and I also want to name the input fields based on the question number (e.g. q1, q2, etc.)

Can each Question component ask its parent (Section) component for its question number?

答:
good choice to use react.js ;-)

You have encountered a first huge problem with react.js standalone: You need to bubble a lot of information between your component layers up and down. After time it becomes so complex that you'll reach a point you just want to f*** that s*** off.

So let's first talk about how to separate the business logic from the view components so that you then can then handle state changes.

I will use React Baobab to handle the application state.

```<code>// state.js
import Baobab from "baobab";

const state = new Baobab({
    name:      "MySurvivalTest",
    structure: {
        sections: [{
            id:        0
            title:     "MyFirstSection",
            questions: [{
                id:    0,
                items: [{
                    id:    0,
                    name:  "q1",
                    value: 0
                }]
            }]
        }]
    },
    answers: []
});

export default state;
</code>```

This is the place where all your application data is stored. In my example your test contains one section with one question that has one item and no question is answered yet (answers is empty).

Before we build the components let's build the application logic.

```<code>// actions/Question.js
export const answer = (state, questionId, value) => {
    state.select("answers").set(
        state.get("answers")
            .filter(x => x.questionId !== questionId)
            .concat([{ questionId, value }])
    );
};
</code>```

The Question.answer function adds answers to the state mentioned before.

So now it's time to build the components very quickly and consistent.

```<code>import React, { Component } from "react";
import { branch as BaobabBranch } from "baobab-react/higher-order";
import PropTypes from "prop-types";

@BaobabBranch({
    structure: ["structure"]
})
export default class Home extends Component {
    static propTypes = {
        structure: PropTypes.object.isRequired,
        answers:   PropTypes.array.isRequired
    };

    public render() {
        return (<SurvivalTest>
            { this.props.structure.sections.map(section =>
                <Section
                    title={section.title}
                >
                { section.questions.map(question =>
                    <Question structure={question} />
                )}
                </Section>
            )}
        </SurvivalTest>);
    }
}

import React, { Component } from "react";
import { branch as BaobabBranch } from "baobab-react/higher-order";
import PropTypes from "prop-types";
import { answer } from "../actions/Question";

@BaobabBranch({
    answers: ["answers"]
})
export default class Question extends Component {
    static propTypes = {
        question: PropTypes.object.isRequired,
        dispatch: PropTypes.func.isRequired,
        answers:  PropTypes.array.isRequired
    };

    onClick(id, event) {
        this.props.dispatch(answer, id, value);
    }

    public render() {
        return this.props.question.items.map(item =>
            <tr>
                <td>
                    <input
                        name={item.name}
                        checked={this.props.answers.find(x => x.questionId === this.props.question.id).value === item.value}
                        onClick={this.onClick.bind(this, this.props.question.id, item.value)}
                    />
                </td>
            </tr>
        );
    }
}
</code>```

Ok this is much input. So what's the Baobab annotation? The Baobab annotation can be seen as a listener. So Home listens on structure while Question listens on answers. Each time a listened attribute is changed by an action (we just have 1 action - the answer action) all listening components trigger a rerender with the new data.

So if you now trigger a click action on the input field the answer action is triggered (The dispatch function is automatically added to your component if you use the Baobab annotation. It binds the state to the action (first argument) and adds all other arguments behind.). The answer action causes a state change on answers which then forces a rerender of Questions.

Disclaimer: I have not tested the code so maybe some parts are missing or wrong. But I hope you get a deeper understanding of how to build an application with React.js (and Baobab).

Title: Numbering child elements in ReactJS

Body:
I'm new to React, and I'm confused about how it's supposed to work.

I want to make a little assessment app with questions, sections, and a totals section.

I marked up what I want inside of a home page component like this:

export default class Home extends React.Component {
    public render() {
        return <SurvivalTest>

                <Question>
                    Does the project have a clear, unambiguous vision statement
                    or mission statement?
                </Question>
                <Question>
                    Do all team members believe the vision is realistic?
                </Question>
                <Question>
                    Does the project have a business case that details the
                    business benefit and how the benefit will be measured?
                </Question>

                <Question>
                    Does the project have a detailed, written Software
                    Development Plan?
                </Question>
                <Question>
                    Were the schedule and budget estimates officially updated
                    at the end of the most recently completed phase?
                </Question>
                <Question>
                    Does the project have detailed, written architecture and
                    design documents?
                </Question>

            <TotalsSection />
        </SurvivalTest>;
    }
}

The questions each have 4 possible answers, scored 0-3.  The answers are the same for all questions and they are: "No", "Not really", "Probably", and "Yes".  The Section component the table element and labels for the answers are in the table headers.

export class Question extends React.Component {
    constructor() {
        super();
        this.state = { score: 0 };
    }

    public render() {
        return

                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 0 })} checked={this.state.score === 0} />

                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 1 })} checked={this.state.score === 1} />

                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 2 })} checked={this.state.score === 2} />

                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 3 })} checked={this.state.score === 3} />

                {??? + '. ' + this.props.children}

;
    }
}

How do I number the questions automatically?  I want to display a question number before the question text, and I also want to name the input fields based on the question number (e.g. q1, q2, etc.)

Can each Question component ask its parent (Section) component for its question number?

Body:
good choice to use react.js ;-)

You have encountered a first huge problem with react.js standalone: You need to bubble a lot of information between your component layers up and down. After time it becomes so complex that you'll reach a point you just want to f*** that s*** off.

So let's first talk about how to separate the business logic from the view components so that you then can then handle state changes.

I will use React Baobab to handle the application state.

// state.js
import Baobab from "baobab";

const state = new Baobab({
    name:      "MySurvivalTest",
    structure: {
        sections: [{
            id:        0
            title:     "MyFirstSection",
            questions: [{
                id:    0,
                items: [{
                    id:    0,
                    name:  "q1",
                    value: 0
                }]
            }]
        }]
    },
    answers: []
});

export default state;

This is the place where all your application data is stored. In my example your test contains one section with one question that has one item and no question is answered yet (answers is empty).

Before we build the components let's build the application logic.

// actions/Question.js
export const answer = (state, questionId, value) => {
    state.select("answers").set(
        state.get("answers")
            .filter(x => x.questionId !== questionId)
            .concat([{ questionId, value }])
    );
};

The Question.answer function adds answers to the state mentioned before.

So now it's time to build the components very quickly and consistent.

import React, { Component } from "react";
import { branch as BaobabBranch } from "baobab-react/higher-order";
import PropTypes from "prop-types";

@BaobabBranch({
    structure: ["structure"]
})
export default class Home extends Component {
    static propTypes = {
        structure: PropTypes.object.isRequired,
        answers:   PropTypes.array.isRequired
    };

    public render() {
        return (<SurvivalTest>
            { this.props.structure.sections.map(section =>
                <Section
                    title={section.title}
                >
                { section.questions.map(question =>
                    <Question structure={question} />
                )}
                </Section>
            )}
        </SurvivalTest>);
    }
}

import React, { Component } from "react";
import { branch as BaobabBranch } from "baobab-react/higher-order";
import PropTypes from "prop-types";
import { answer } from "../actions/Question";

@BaobabBranch({
    answers: ["answers"]
})
export default class Question extends Component {
    static propTypes = {
        question: PropTypes.object.isRequired,
        dispatch: PropTypes.func.isRequired,
        answers:  PropTypes.array.isRequired
    };

    onClick(id, event) {
        this.props.dispatch(answer, id, value);
    }

    public render() {
        return this.props.question.items.map(item =>
            <tr>
                <td>
                    <input
                        name={item.name}
                        checked={this.props.answers.find(x => x.questionId === this.props.question.id).value === item.value}
                        onClick={this.onClick.bind(this, this.props.question.id, item.value)}
                    />
                </td>
            </tr>
        );
    }
}

Ok this is much input. So what's the Baobab annotation? The Baobab annotation can be seen as a listener. So Home listens on structure while Question listens on answers. Each time a listened attribute is changed by an action (we just have 1 action - the answer action) all listening components trigger a rerender with the new data.

So if you now trigger a click action on the input field the answer action is triggered (The dispatch function is automatically added to your component if you use the Baobab annotation. It binds the state to the action (first argument) and adds all other arguments behind.). The answer action causes a state change on answers which then forces a rerender of Questions.

Disclaimer: I have not tested the code so maybe some parts are missing or wrong. But I hope you get a deeper understanding of how to build an application with React.js (and Baobab).


问:
Copy files from android/data directory to internal storage
I have 2 files which are located deep in the android/data system, example of such a file below.

```<code>/storage/emulated/0/Android/data/mytest.com.test/files/Documents/Test/Bin/data.dat
</code>```

I want to copy both of them to a location on the internal storage.
Now stackoverflow is a nice community which has a lot of examples and I therefore searched already for some examples how it is done but unfortunatly it is not working.

Logcat:

```<code>V/debug: Copy file failed. Source file missing.
</code>```

I verified this but the files are definitely there, the destination directory is created but is empty.
Could anybody please assist me?

Main backup method:

```<code>public void backupFavorites() {

        String folder1, folder2, folder3, folder4;

        //Set target directory
        String path = Utils.getDownloadDestination(this) + "/FavoritesBackup/Bin/";
        File rootPath = new File(path);

        if (!rootPath.exists())
            rootPath.mkdirs();

        //Prepare Sourcefile 1
        folder1 = (rootPath + "/" + "data.dat");
        File sdcardData = new File (this.getExternalFilesDir
                ("Documents"), "MyTestApp");
        String pathdata = sdcardData.getPath() + "/Bin/data.dat";
        File data = new File(pathdata);

        //Prepare Sourcefile 2
        folder2 = (rootPath + "/" + "trackerdata.dat");
        File sdcardTracker = new File(this.getExternalFilesDir
                ("Documents"), "MyTestApp");
        String pathtracker = sdcardTracker.getPath() + "/Bin/trackerdata.dat";
        File tracker = new File(pathtracker);

        if (trackerDataExists(this)) {

            ArrayList<File> sourceFiles = new ArrayList<>();
            sourceFiles.add(data);
            sourceFiles.add(tracker);

            ArrayList<String> destFiles = new ArrayList<>();
            destFiles.add(folder1);
            destFiles.add(folder2);

            for (int i = 0; i < sourceFiles.size(); i++) {
                for (int p = 0; p < destFiles.size(); p++) {
                    try {
                        copyFiles(sourceFiles.get(i), destFiles.get(p));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            Toast.makeText(this, "Backup created", Toast.LENGTH_SHORT).show();
        }
    }
</code>```

Code which copies the files:

```<code>void copyFiles(File sourceLocation, String targtLocation) throws IOException {

        if (sourceLocation.exists()) {
            FileInputStream fin = null;
            FileOutputStream fout = null;
            Log.i("debug", "source " + sourceLocation);
            Log.i("debug", "des " + targtLocation);
            try {
                fin = new FileInputStream(sourceLocation);
                new File(String.valueOf(targtLocation)).delete();
                fout = new FileOutputStream(targtLocation, false);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // Copy the bits from instream to outstream
            byte[] buf = new byte[2048];
            int len;
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fout);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fin);
            while ((len = bufferedInputStream.read(buf)) > 0) {
                bufferedOutputStream.write(buf, 0, len);
            }
            fin.close();
            bufferedOutputStream.close();
            fout.close();

            Log.e("debug", "Copy file successful.");

        } else {
            Log.v("debug", "Copy file failed. Source file missing.");
        }
    }
</code>```

Code to get the download destination:

```<code>public static String getDownloadDestination(Context mCon) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mCon);
        return pref.getString("downloadFolder", MYDESTINATION.getAbsolutePath());
    }

public static final File MYDESTINATION = new File(Environment.getExternalStorageDirectory(),
            "Test");
</code>```

答:
I solved it myself. If anyone encounters the same issue, below is the working code.</p>

```<code>public void backupFiles() {

        if (DataExists(this)) {

            ArrayList<String> sourceFiles = new ArrayList<>();
            sourceFiles.add("codex.dat");
            sourceFiles.add("ids.dat");
            sourceFiles.add("data.dat");

            for (int i = 0; i < sourceFiles.size(); i++) {
                try {
                    copyFiles(sourceFiles.get(i));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            Toast.makeText(this, "Backup of FAVORITES created", Toast.LENGTH_SHORT).show();
        }
    }

public void copyFiles(String sourceLocation) throws IOException {

        if (!sourceLocation.isEmpty()) {
            FileInputStream fin = null;
            FileOutputStream fout = null;

            String path = Environment.getExternalStorageDirectory() + Utils.getDownloadDestination
                    (this) + "/TestBackup/Bin/";
            File rootPath = new File(path);

            if (!rootPath.exists())
                rootPath.mkdirs();

            File sdcardData = new File(this.getExternalFilesDir
                    ("Documents"), "MyTest");
            String pathdata = sdcardData.getPath() + "/Bin/" + sourceLocation;
            File data = new File(pathdata);

            Log.i("debug", "source " + pathData);
            Log.i("debug", "des " + path + sourceLocation);

            try {
                fin = new FileInputStream(data);
                File outFile = new File(path, sourceLocation);
                fout = new FileOutputStream(outFile, true);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fout);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fin);
            while ((len = bufferedInputStream.read(buf)) > 0) {
                bufferedOutputStream.write(buf, 0, len);
            }
            fin.close();
            bufferedOutputStream.close();
            fout.close();

            //Comment out to delete originals!
            //data.delete();
            Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            scanIntent.setData(Uri.parse(sourceLocation));
            sendBroadcast(scanIntent);
            Log.e("debug", "Copy file successful.");

        } else {
            Log.v("debug", "Copy file failed. Source file missing." + sourceLocation);
        }
    }
</code>```

Body:
I have 2 files which are located deep in the android/data system, example of such a file below.

/storage/emulated/0/Android/data/mytest.com.test/files/Documents/Test/Bin/data.dat

I want to copy both of them to a location on the internal storage.
Now stackoverflow is a nice community which has a lot of examples and I therefore searched already for some examples how it is done but unfortunatly it is not working.

Logcat:

V/debug: Copy file failed. Source file missing.

I verified this but the files are definitely there, the destination directory is created but is empty.
Could anybody please assist me?

Main backup method:

public void backupFavorites() {

        String folder1, folder2, folder3, folder4;

        //Set target directory
        String path = Utils.getDownloadDestination(this) + "/FavoritesBackup/Bin/";
        File rootPath = new File(path);

        if (!rootPath.exists())
            rootPath.mkdirs();

        //Prepare Sourcefile 1
        folder1 = (rootPath + "/" + "data.dat");
        File sdcardData = new File (this.getExternalFilesDir
                ("Documents"), "MyTestApp");
        String pathdata = sdcardData.getPath() + "/Bin/data.dat";
        File data = new File(pathdata);

        //Prepare Sourcefile 2
        folder2 = (rootPath + "/" + "trackerdata.dat");
        File sdcardTracker = new File(this.getExternalFilesDir
                ("Documents"), "MyTestApp");
        String pathtracker = sdcardTracker.getPath() + "/Bin/trackerdata.dat";
        File tracker = new File(pathtracker);

        if (trackerDataExists(this)) {

            ArrayList<File> sourceFiles = new ArrayList<>();
            sourceFiles.add(data);
            sourceFiles.add(tracker);

            ArrayList<String> destFiles = new ArrayList<>();
            destFiles.add(folder1);
            destFiles.add(folder2);

            for (int i = 0; i < sourceFiles.size(); i++) {
                for (int p = 0; p < destFiles.size(); p++) {
                    try {
                        copyFiles(sourceFiles.get(i), destFiles.get(p));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            Toast.makeText(this, "Backup created", Toast.LENGTH_SHORT).show();
        }
    }

Code which copies the files:

void copyFiles(File sourceLocation, String targtLocation) throws IOException {

        if (sourceLocation.exists()) {
            FileInputStream fin = null;
            FileOutputStream fout = null;
            Log.i("debug", "source " + sourceLocation);
            Log.i("debug", "des " + targtLocation);
            try {
                fin = new FileInputStream(sourceLocation);
                new File(String.valueOf(targtLocation)).delete();
                fout = new FileOutputStream(targtLocation, false);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // Copy the bits from instream to outstream
            byte[] buf = new byte[2048];
            int len;
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fout);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fin);
            while ((len = bufferedInputStream.read(buf)) > 0) {
                bufferedOutputStream.write(buf, 0, len);
            }
            fin.close();
            bufferedOutputStream.close();
            fout.close();

            Log.e("debug", "Copy file successful.");

        } else {
            Log.v("debug", "Copy file failed. Source file missing.");
        }
    }

Code to get the download destination:

public static String getDownloadDestination(Context mCon) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mCon);
        return pref.getString("downloadFolder", MYDESTINATION.getAbsolutePath());
    }

public static final File MYDESTINATION = new File(Environment.getExternalStorageDirectory(),
            "Test");

Body:
I solved it myself. If anyone encounters the same issue, below is the working code.

public void backupFiles() {

        if (DataExists(this)) {

            ArrayList<String> sourceFiles = new ArrayList<>();
            sourceFiles.add("codex.dat");
            sourceFiles.add("ids.dat");
            sourceFiles.add("data.dat");

            for (int i = 0; i < sourceFiles.size(); i++) {
                try {
                    copyFiles(sourceFiles.get(i));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            Toast.makeText(this, "Backup of FAVORITES created", Toast.LENGTH_SHORT).show();
        }
    }

public void copyFiles(String sourceLocation) throws IOException {

        if (!sourceLocation.isEmpty()) {
            FileInputStream fin = null;
            FileOutputStream fout = null;

            String path = Environment.getExternalStorageDirectory() + Utils.getDownloadDestination
                    (this) + "/TestBackup/Bin/";
            File rootPath = new File(path);

            if (!rootPath.exists())
                rootPath.mkdirs();

            File sdcardData = new File(this.getExternalFilesDir
                    ("Documents"), "MyTest");
            String pathdata = sdcardData.getPath() + "/Bin/" + sourceLocation;
            File data = new File(pathdata);

            Log.i("debug", "source " + pathData);
            Log.i("debug", "des " + path + sourceLocation);

            try {
                fin = new FileInputStream(data);
                File outFile = new File(path, sourceLocation);
                fout = new FileOutputStream(outFile, true);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fout);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fin);
            while ((len = bufferedInputStream.read(buf)) > 0) {
                bufferedOutputStream.write(buf, 0, len);
            }
            fin.close();
            bufferedOutputStream.close();
            fout.close();

            //Comment out to delete originals!
            //data.delete();
            Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            scanIntent.setData(Uri.parse(sourceLocation));
            sendBroadcast(scanIntent);
            Log.e("debug", "Copy file successful.");

        } else {
            Log.v("debug", "Copy file failed. Source file missing." + sourceLocation);
        }
    }


问:
neo4j cypher How to find existence count of a specific node in relations?
In my application, i will try to calculate betweenness centrality of nodes. Here is the
Betweenness Centrality Calculation Formula. Deminator is just count of relationship between two nodes. But numerator is the existence count of a specific node between this relation. So how can i find the existence count of a node in the relation?

For example as a result of this cypher:MATCH p=allShortestPaths( (u1{name:1174}) - [*..20] - (u2{name:1179}) ) return  p

A graph between 2 specific nodes. how can i find the transition count of node:1204 on the relationships between nodes:1174-1179

Shortly, there are shortest paths between node A to node B. How many of them includes node node C ?

答:
You can use the nodes() function on the path variable to get a collection of nodes for the given path. From there you can check if a specific previously matched node is present. Here's one way to do it:

```<code>MATCH (n{name:1204})
MATCH p=allShortestPaths( (u1{name:1174}) - [*..20] - (u2{name:1179}) )
WITH p, case when n in nodes(p) then 1 else 0 end as occurrences
RETURN count(p) as shortestPathCount, sum(occurrences) as occurrencesCount
</code>```

Also, it's recommended you use labels in your graph and in your queries. Currently this is performing an all nodes scan to find any node with the given name, and that gets less and less efficient as the number of nodes grows. If you add a label on your nodes and use them in your match, then you'll at least be performing a label scan instead. If you create an index on the label/property then you'll be doing index lookups for starting nodes in your query.

Body:
You can use the nodes() function on the path variable to get a collection of nodes for the given path. From there you can check if a specific previously matched node is present. Here's one way to do it:

MATCH (n{name:1204})
MATCH p=allShortestPaths( (u1{name:1174}) - [*..20] - (u2{name:1179}) )
WITH p, case when n in nodes(p) then 1 else 0 end as occurrences
RETURN count(p) as shortestPathCount, sum(occurrences) as occurrencesCount

Also, it's recommended you use labels in your graph and in your queries. Currently this is performing an all nodes scan to find any node with the given name, and that gets less and less efficient as the number of nodes grows. If you add a label on your nodes and use them in your match, then you'll at least be performing a label scan instead. If you create an index on the label/property then you'll be doing index lookups for starting nodes in your query.


问:
What is the purpose of nesting dispatch_async(dispatch_get_main_queue()^{}) ?
I've inherited some code that has this rather unusual nested sequence. The usual paradigm would have a single dispatch to the main queue to update the UI. The code, shown below, nests a dispatch to the main queue within another dispatch to the main queue.

```<code>- (void)viewDidLoad
{
// Setup some data
// Adjust UI

 dispatch_async(myBackgroundQueue, ^{
   while(Do_some_time_consuming_work) {

     // Time consuming work goes here

     if (things_are_going_slowly) {

        dispatch_async(dispatch_get_main_queue(), ^{    // <- one of these two seems redundant
          dispatch_async(dispatch_get_main_queue(), ^{  // <- one of these two seems redundant

            stillWorkingLabel.hidden = NO; //Let user know the work is still ongoing
          });
        });
     )

   // Finish time-consuming work
   }

  });

}
</code>```

What is the purpose, if any, of nesting dispatch_async(dispatch_get_main_queue()? This nested sequence shows up in several places in the app. It seems to me that only one dispatch to the main queue is needed.

I think I've read all of the relevant questions on related topics here and via Google search, but I haven't found anyone suggesting nesting two identical dispatches.

The app works well, with the UI updating as expected in the above example and in other places in the code.

Most of the app's code uses the usual non-nested version of the above scheme, and of course it also works just fine.

I'm inclined to just replace these nested calls with a single dispatch, but maybe I'm missing something here. Any advice would be appreciated.

答:
I can't think of a single advantage to doing this, and can think of reasons not to. It will delay the execution of the inner closure, as well as taking a small amount of additional resources. (It's going to force the app to go through at least 2 passes through the event loop before the work item gets executed.)

I think removing the nested calls is the right thing to do.

Body:
I've inherited some code that has this rather unusual nested sequence. The usual paradigm would have a single dispatch to the main queue to update the UI. The code, shown below, nests a dispatch to the main queue within another dispatch to the main queue.

- (void)viewDidLoad
{
// Setup some data
// Adjust UI

 dispatch_async(myBackgroundQueue, ^{
   while(Do_some_time_consuming_work) {

     // Time consuming work goes here

     if (things_are_going_slowly) {

        dispatch_async(dispatch_get_main_queue(), ^{    // <- one of these two seems redundant
          dispatch_async(dispatch_get_main_queue(), ^{  // <- one of these two seems redundant

            stillWorkingLabel.hidden = NO; //Let user know the work is still ongoing
          });
        });
     )

   // Finish time-consuming work
   }

  });

}

What is the purpose, if any, of nesting dispatch_async(dispatch_get_main_queue()? This nested sequence shows up in several places in the app. It seems to me that only one dispatch to the main queue is needed.

I think I've read all of the relevant questions on related topics here and via Google search, but I haven't found anyone suggesting nesting two identical dispatches.

The app works well, with the UI updating as expected in the above example and in other places in the code.

Most of the app's code uses the usual non-nested version of the above scheme, and of course it also works just fine.

I'm inclined to just replace these nested calls with a single dispatch, but maybe I'm missing something here. Any advice would be appreciated.


问:
iFrame Redirect Issue - Not Changing the page
```<code><iframe src="http://runebet.com/" width="80%" height="65%"     name="runeBetAPI"></iframe>

<script src="http://code.jquery.com/jquery-latest.min.js"
    type="text/javascript"></script>
<script>
function RegisterPage() {
window.frames["runeBetAPI"].location = "http://runebet.com/register/";
}
RegisterPage();
</script>
</code>```

This doesn't seem to work/change the content..

答: The URL should start with http://www. to avoid a server redirection</p>