问:
Determining programmatically what modules are loaded in another process? (OS X)
What I'm trying to do I feel is pretty straightforward, I'm just not sure exactly how to do it.

Specifically I just want to get a list of modules (shared/dynamic libraries) that are loaded in another process.  As well as get the starting address of where that module is in the given process.

It's very straightforward to get this information with GDB.  You simple connect to the process, and type "info shared."  That is the exact type of information I would like to get to.  Such as:

Num Basename

  Type Address         Reason | | Source
  | |

  | |                    | | | |

  1 Adium

  - 0x1000            exec Y Y /Applications/Adium.app/Contents/MacOS/Adium
  (offset 0x0)   2 dyld

  - 0x8fe00000        dyld Y Y /usr/lib/dyld at 0x8fe00000 (offset
  0x0) with prefix "__dyld_"   3 WebCore
  F 0x95b6a000        dyld Y Y
  /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/WebCore
  at 0x95b6a000 (offset 0x95b6a000)

Does anyone know how to do this programmatically? Obviously where modules load is dynamic so I need to determine where it's located.

答:
I would suggest that you could go download the source for gdb as used by the Development Tools.

But, well, I've read that source and I'm not sure that telling anyone to go read it is a productive suggestion.

In any case, you will want to use the various mach APIs to do this.   In particular, the APIs are found in /usr/include/mach/*.h.   Specifically, you'll want to start with task_for_pid() and work your way down to the info you need.

Note that task_for_pid() (and any other mechanism used to grub through another tasks innards) requires either admin access or membership in the development group on the machine.


来源: stackexchange

问:
Is there a keyboard shortkey to browse the history in a Jupyter notebook
Is there an easy way to browse through command history and reuse old commands in a Jupyter notebook? Some equivalent to either the arrow up/down use in the iPython console or to the % sign use in Mathematica.
(Although the answer might seem trivial to an expert, it is really hard to find for a newbie)</p>

答: I was looking for the same. But a year later, and after about 10 min of scouring the best I found (link) is this magic command: %recall last or %recall <integer>, which after execution copies a command from history into a new cell. Probably not quite what you had been looking - a tad too kludgy compared to arrow up/down. But a good option for cells with lots of text.

ContentLicense: CC BY-SA 3.0


问:
Flask set_response for domain (not just subdomain)
So when users of my site visit a.mysite.com, my flask server is setting the browser in their cookie via:

```<code>@app.route('/safe')
def tag_browser():
  response = redirect('/')
  response.set_cookie('hello', 'world')
  return response
</code>```

This sets the cookie for a.mysite.com. However, I am interested to set the cookie for mysite.com

There is this thread: Share cookie between subdomain and domain which talks about how I can achieve the same effect wth

```<code>Set-Cookie: name=value; domain=mydomain.com
</code>```

My problem is, how can I do so inside flask?

答:
Looks like the set_cookie function can get domain as param. From the documentation:

```<code>set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)
</code>```

domain – if you want to set a cross-domain cookie. For example,
  domain=".example.com" will set a cookie that is readable by the domain
  www.example.com, foo.example.com etc. Otherwise, a cookie will only be
  readable by the domain that set it.

Body:
So when users of my site visit a.mysite.com, my flask server is setting the browser in their cookie via:

@app.route('/safe')
def tag_browser():
  response = redirect('/')
  response.set_cookie('hello', 'world')
  return response

This sets the cookie for a.mysite.com. However, I am interested to set the cookie for mysite.com

There is this thread: Share cookie between subdomain and domain which talks about how I can achieve the same effect wth

Set-Cookie: name=value; domain=mydomain.com

My problem is, how can I do so inside flask?

Body:
Looks like the set_cookie function can get domain as param. From the documentation:

set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)

domain – if you want to set a cross-domain cookie. For example,
  domain=".example.com" will set a cookie that is readable by the domain
  www.example.com, foo.example.com etc. Otherwise, a cookie will only be
  readable by the domain that set it.


问:
SQL Query for Repeated category(count items in each category) and has to contain atleast one specific type

SQL Query to perform repeated item_id against each category_id. For this the query would be

```<code>Select item_id, category_id, COUNT(*)
from table
group by category_id, item_id
having count(*)>1
</code>```

but how can I change the code to filter only ones which have atleast one type A in their repeated counts.

答:
You can count the "A"s in the HAVING clause as well:

```<code>Select item_id, category_id, COUNT(*)
from table
group by category_id, item_id
having count(*) > 1 and sum(case when type = 'A' then 1 else 0 end) > 0;
</code>```

Given your sample data, you can shorten this to:

```<code>Select item_id, category_id, COUNT(*)
from table
group by category_id, item_id
having count(*) > 1 and min(type)= 'A' ;
</code>```

But this depends on the actual names you are using.

Body:
SQL Query to perform repeated item_id against each category_id. For this the query would be

Select item_id, category_id, COUNT(*)
from table
group by category_id, item_id
having count(*)>1

but how can I change the code to filter only ones which have atleast one type A in their repeated counts.

Body:
You can count the "A"s in the HAVING clause as well:

Select item_id, category_id, COUNT(*)
from table
group by category_id, item_id
having count(*) > 1 and sum(case when type = 'A' then 1 else 0 end) > 0;

Given your sample data, you can shorten this to:

Select item_id, category_id, COUNT(*)
from table
group by category_id, item_id
having count(*) > 1 and min(type)= 'A' ;

But this depends on the actual names you are using.


问:
Java - is there a way to open a text file if it does not exist already, and append to it if it does exist?
I am pretty new to Java and I came across this problem. I want the java code to make a txt file if it does not exist already, but if it does, I want PrintWriter to append to it using FileWriter. Here is my code:

Edit: I attempted to fix my code but now I am getting the IOException error. What am I doing wrong here?
Edit 2: I think my code is unique since I am trying to make it create a new file if the file does not exist, and make it append to the existing file if it already exists.

```<code>import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

/**
 * Created by FakeOwl96 on 3/28/2017.
 */
public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.nextLine();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}
</code>```

答:
This is another example of file append line and create new file if file is not exists.</p>

```<code>import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AppendFileDemo2 {

    public static void main(String[] args) {
        try {
            File file = new File("myfile2.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            //This will add a new line to the file content
            pw.println("");
            /* Below three statements would add three
           * mentioned Strings to the file in new lines.
             */
            pw.println("This is first line");
            pw.println("This is the second line");
            pw.println("This is third line");
            pw.close();

            System.out.println("Data successfully appended at the end of file");

        } catch (IOException ioe) {
            System.out.println("Exception occurred:");
            ioe.printStackTrace();
        }
    }
}
</code>```

Body:
I am pretty new to Java and I came across this problem. I want the java code to make a txt file if it does not exist already, but if it does, I want PrintWriter to append to it using FileWriter. Here is my code:

Edit: I attempted to fix my code but now I am getting the IOException error. What am I doing wrong here?
Edit 2: I think my code is unique since I am trying to make it create a new file if the file does not exist, and make it append to the existing file if it already exists.

import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

/**
 * Created by FakeOwl96 on 3/28/2017.
 */
public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.nextLine();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}

Body:
This is another example of file append line and create new file if file is not exists.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AppendFileDemo2 {

    public static void main(String[] args) {
        try {
            File file = new File("myfile2.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            //This will add a new line to the file content
            pw.println("");
            /* Below three statements would add three
           * mentioned Strings to the file in new lines.
             */
            pw.println("This is first line");
            pw.println("This is the second line");
            pw.println("This is third line");
            pw.close();

            System.out.println("Data successfully appended at the end of file");

        } catch (IOException ioe) {
            System.out.println("Exception occurred:");
            ioe.printStackTrace();
        }
    }
}


问:
CSS: How to account for the lost space when converting item from static to fixed/absolute
Here's my jsfiddle: https://jsfiddle.net/vd2vstoy/1/

HTML:

```<code><div class="content">
    <div class="top-banner">
        <h1>
            Some<body> Once Told Me
        </h1>
    </div>
    <div class="fixedElement">
        the <i>HelloWorld</i> is gonna roll me
    </div>
    <h1>
        I ain't the C-sharp-est tool<br>
        In the shed.
    </h1>
</div>
</code>```

CSS:

```<code>.content {
    height:1000px;
}
.top-banner  {
    background-color:yellow;
    height:200px;
}
.fixedElement {
    background-color: #c0c0c0;
    padding:15px;
    position:static;
    top:0;
    width:100%;
    z-index:100;
}
</code>```

Javascript:

```<code>$(window).scroll(function(e){
    var $el = $('.fixedElement');
    var isPositionFixed = ($el.css('position') == 'fixed');

    if ($(this).scrollTop() > 220 && !isPositionFixed) {
        $('.fixedElement').css({'position': 'fixed', 'top': '0px'});
    }
    if ($(this).scrollTop() < 220 && isPositionFixed) {
        $('.fixedElement').css({'position': 'static', 'top': '0px'});
    }
});
</code>```

The point of this is so that the fixedElement sticks to the top when it reached that 200 pixel mark. Unfortunately, the space that the fixedElement was taking up goes away when it turns fixed position.

Is there anyway that I can preserve the space that was there so that as soon as the element becomes fixed, the rest of the content doesn't shift up and become unseen?

To see what's happening, just scroll down in the example jsfiddle and see what happens when the fixedElement div reaches the top of the screen.

答:
What I normally do is wrap the item that is going to be fixed to the top in a div that has a fixed height and remains relative. That way, when the fixed element is moved out of the regular flow by setting its position: absolute (in the scroll event), the space will be retained by the containing div, and no page-jumping occurs.

So you wrap the .fixed-element in a div of a matching height, but do not make that one change to a position: absolute

Here's a working snippet:

$(window).scroll(function(e) {
  var $el = $('.fixedElement');
  var isPositionFixed = ($el.css('position') == 'fixed');
  if ($(this).scrollTop() > 220 && !isPositionFixed) {
    $('.fixedElement').css({
      'position': 'fixed',
      'top': '0px'
    });
  }
  if ($(this).scrollTop() < 220 && isPositionFixed) {
    $('.fixedElement').css({
      'position': 'static',
      'top': '0px'
    });
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content {
  height: 1000px;
}

.top-banner {
  background-color: yellow;
  height: 200px;
}

.fixedElement {
  background-color: #c0c0c0;
  padding: 15px;
  position: static;
  top: 0;
  width: 100%;
  z-index: 100;
  height: 25px;
}

.fixedElementWrapper {
  /* Match the height of the elements to prevent shifting */
  height: 25px;
}

h1 {
  /* Adding some space to make the effect more visible */
  margin-top: 40px;
}</code>```

      Some Once Told Me

      The HelloWorld is gonna roll me

    I ain't the C-sharp-est tool
 In the shed.

```

Hope it helps!

Body:
Here's my jsfiddle: https://jsfiddle.net/vd2vstoy/1/

HTML:

            Some Once Told Me

        the HelloWorld is gonna roll me

        I ain't the C-sharp-est tool

        In the shed.

CSS:

.content {
    height:1000px;
}
.top-banner  {
    background-color:yellow;
    height:200px;
}
.fixedElement {
    background-color: #c0c0c0;
    padding:15px;
    position:static;
    top:0;
    width:100%;
    z-index:100;
}

Javascript:

$(window).scroll(function(e){
    var $el = $('.fixedElement');
    var isPositionFixed = ($el.css('position') == 'fixed');

    if ($(this).scrollTop() > 220 && !isPositionFixed) {
        $('.fixedElement').css({'position': 'fixed', 'top': '0px'});
    }
    if ($(this).scrollTop() < 220 && isPositionFixed) {
        $('.fixedElement').css({'position': 'static', 'top': '0px'});
    }
});

The point of this is so that the fixedElement sticks to the top when it reached that 200 pixel mark. Unfortunately, the space that the fixedElement was taking up goes away when it turns fixed position.

Is there anyway that I can preserve the space that was there so that as soon as the element becomes fixed, the rest of the content doesn't shift up and become unseen?

To see what's happening, just scroll down in the example jsfiddle and see what happens when the fixedElement div reaches the top of the screen.

Body:
What I normally do is wrap the item that is going to be fixed to the top in a div that has a fixed height and remains relative. That way, when the fixed element is moved out of the regular flow by setting its position: absolute (in the scroll event), the space will be retained by the containing div, and no page-jumping occurs.

So you wrap the .fixed-element in a div of a matching height, but do not make that one change to a position: absolute

Here's a working snippet:

$(window).scroll(function(e) {
  var $el = $('.fixedElement');
  var isPositionFixed = ($el.css('position') == 'fixed');
  if ($(this).scrollTop() > 220 && !isPositionFixed) {
    $('.fixedElement').css({
      'position': 'fixed',
      'top': '0px'
    });
  }
  if ($(this).scrollTop() < 220 && isPositionFixed) {
    $('.fixedElement').css({
      'position': 'static',
      'top': '0px'
    });
  }
});

.content {
  height: 1000px;
}

.top-banner {
  background-color: yellow;
  height: 200px;
}

.fixedElement {
  background-color: #c0c0c0;
  padding: 15px;
  position: static;
  top: 0;
  width: 100%;
  z-index: 100;
  height: 25px;
}

.fixedElementWrapper {
  /* Match the height of the elements to prevent shifting */
  height: 25px;
}

h1 {
  /* Adding some space to make the effect more visible */
  margin-top: 40px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <div class="top-banner">
    <h1>
      Some&lt;body&gt; Once Told Me
    </h1>
  </div>
  <div class="fixedElementWrapper">
    <!-- we add this because this is gonna preserve our space -->
    <div class="fixedElement">
      The <i>HelloWorld</i> is gonna roll me

    </div>
  </div>
  <h1>
    I ain't the C-sharp-est tool<br> In the shed.
  </h1>
</div>

Hope it helps!


问:
Printing the second half of a linked list in reverse order
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example:

If the elements are: 1 2 3 4 5 6

It should print: 1 2 3 6 5 4

But it's printing: 1 2 3 5 4

Why isn't it printing the last element? How can this be solved?

```<code>void reverse()
{
    int c=1;
    node *current,*prev,*temp;
    current=head;
    prev=NULL;
    std::stack<int>s;
    while(current->next!=NULL)
    {
        c++;
        s.push(current->data);
        current=current->next;
    }

    int mid=0;
    if((c%2)==0)
    {
        mid=c/2;
    }
    else
    {
        mid=(c+1)/2;
    }
    current=head;
    for(int i=0;i<mid;i++)
    {
        cout<<current->data<<"\t";
        current=current->next;
    }

    for(int i=mid;i>1;i--)
    {
       std::cout<<s.top()<<"\t";
       s.pop();
    }
    std::cout << '\n';
}
</code>```

答:
It's not quite going to compile, but this is somewhat fewer lines:</p>

```<code>// assert myList is sorted before called
// if it's not, add
// std::sort(myList.begin(), myList.end());
// as the first line of the function
void reverseLatterHalf(std::vector& myList)  {
  auto it = myList.begin() + myList.size() / 2;
  std::reverse(it, myList.end());
}
</code>```

Body:
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example:

If the elements are: 1 2 3 4 5 6

It should print: 1 2 3 6 5 4

But it's printing: 1 2 3 5 4

Why isn't it printing the last element? How can this be solved?

void reverse()
{
    int c=1;
    node *current,*prev,*temp;
    current=head;
    prev=NULL;
    std::stack<int>s;
    while(current->next!=NULL)
    {
        c++;
        s.push(current->data);
        current=current->next;
    }

    int mid=0;
    if((c%2)==0)
    {
        mid=c/2;
    }
    else
    {
        mid=(c+1)/2;
    }
    current=head;
    for(int i=0;i<mid;i++)
    {
        cout<<current->data<<"\t";
        current=current->next;
    }

    for(int i=mid;i>1;i--)
    {
       std::cout<<s.top()<<"\t";
       s.pop();
    }
    std::cout << '\n';
}

Body:
It's not quite going to compile, but this is somewhat fewer lines:

// assert myList is sorted before called
// if it's not, add
// std::sort(myList.begin(), myList.end());
// as the first line of the function
void reverseLatterHalf(std::vector& myList)  {
  auto it = myList.begin() + myList.size() / 2;
  std::reverse(it, myList.end());
}


问:
output matcher expected block but was not a block
here is a snippet from my spec:

context "Given array [1,2,3] and block {|e| puts e if e == 1}" do

```<code>subject { Array.new([1,2,3]) }

it "prints out 1 and returns [1,2,3]" do
  expect(subject.my_each { |e| puts e if e == 1 }).to output("1\n").to_stdout
  expect(subject.my_each { |e| puts e if e == 1 }).to eql([1,2,3])
end
</code>```

end

here is the Rspec output:

1) .my_each Given array [1,2,3] and block {|e| puts e if e == 1} prints out 1 and returns [1,2,3]
     Failure/Error: expect(subject.my_each { |e| puts e if e == 1 }).to output("1\n").to_stdout

```<code>   expected block to output "1\n" to stdout, but was not a block
   Diff:
   @@ -1,2 +1 @@
   -1

 # ./spec/enumerable_spec.rb:30:in `block (3 levels) in <top (required)>'
</code>```

答:
Based on this, I changed my expect to this:
expect { subject.my_each { |e| puts e if e == 1 } }.to output("1\n").to_stdout</p>

Body:
here is a snippet from my spec:

context "Given array [1,2,3] and block {|e| puts e if e == 1}" do

subject { Array.new([1,2,3]) }

it "prints out 1 and returns [1,2,3]" do
  expect(subject.my_each { |e| puts e if e == 1 }).to output("1\n").to_stdout
  expect(subject.my_each { |e| puts e if e == 1 }).to eql([1,2,3])
end

end

here is the Rspec output:

1) .my_each Given array [1,2,3] and block {|e| puts e if e == 1} prints out 1 and returns [1,2,3]
     Failure/Error: expect(subject.my_each { |e| puts e if e == 1 }).to output("1\n").to_stdout

   expected block to output "1\n" to stdout, but was not a block
   Diff:
   @@ -1,2 +1 @@
   -1

 # ./spec/enumerable_spec.rb:30:in `block (3 levels) in <top (required)>'


问:
Deploying a JHipster Application to Heroku
Has anyone had luck deploying a JHipster application to Heroku? I think a custom buildpack is required, but I'm not 100% sure, as I'm new to Heroku.</p>

答:
I have deployed an app to Heroku sucessfully (https://smallgis.herokuapp.com/#/login), you should create an app in Heroku and install the mlab add on (mongodb in my case), you should always mantain the slug size less of 300 MB. Link your project to the heroku app that you had created.

heroku login

Create a new Git repository

Initialize a git repository in a new or existing directory

cd my-project/

git init

heroku git:remote -a appname

Deploy your app

git add .

git commit -m "changes...."

git push heroku master (It builds and compresses all the app and you
could visualize in the default heroku application url)


问:
How do I control which channel sound is played through using MATLAB?
I'm a novice MATLAB user, so apologies if the question is very basic. I need a .wav sound file to be played in a single, specific channel -- let's say the left channel. As it is, my code reads in the sound file, and I add in a column of zeros to nullify the channel I don't want, like so:

```<code>currentDir = pwd;
soundFile = [currentDir '\sound1.wav']; % load the file

[y, Fs] = audioread(soundFile); % read the file in

soundData(:,1) = y(:,1); % keeps sound for the left channel
soundData(:,2) = 0; % nullifies the right channel

sound = audioplayer(soundData,Fs);
play(sound);
</code>```

As it stands, the code currently produces a sound that is full volume in the left speaker, and half volume (but still very much audible) in the right speaker. I have tried this with at least 20 .wav files, with the same result.

In case it's relevant, this happens even when I write in code that explicitly matches the length of the sound variable in 0s, like so:

```<code>[y, Fs] = audioread(soundFile);
silentChannel = zeros(size(y));

soundData(:,1) = y(:,1); % keeps sound for the left channel
soundData(:,2) = silentChannel(:,2); % nullifies the right channel
</code>```

Does anybody know what I'm doing wrong, or have any thoughts?

答:
Your code is definitely correct and it should only play audio in the left channel. I suspect that the problem is caused by a sound-card/driver issues. Allow me suggest the following troubleshooting steps:

Save your output as a wav file using audiowrite('output.wav', soundData, Fs). Play this using a different audio player, such as Audacity. If you still hear output in both channels, it must be a sound-card/driver issue.

Assuming that you are using a Windows PC (going by the syntax in your file path), make sure all sound enhancements are disabled. How to do this depends on the PC. If there is a third-party app controlling the playback settings, you'd have to use that. Otherwise find the settings shown in the picture below in the Control Panel.

Body:
I'm a novice MATLAB user, so apologies if the question is very basic. I need a .wav sound file to be played in a single, specific channel -- let's say the left channel. As it is, my code reads in the sound file, and I add in a column of zeros to nullify the channel I don't want, like so:

currentDir = pwd;
soundFile = [currentDir '\sound1.wav']; % load the file

[y, Fs] = audioread(soundFile); % read the file in

soundData(:,1) = y(:,1); % keeps sound for the left channel
soundData(:,2) = 0; % nullifies the right channel

sound = audioplayer(soundData,Fs);
play(sound);

As it stands, the code currently produces a sound that is full volume in the left speaker, and half volume (but still very much audible) in the right speaker. I have tried this with at least 20 .wav files, with the same result.

In case it's relevant, this happens even when I write in code that explicitly matches the length of the sound variable in 0s, like so:

[y, Fs] = audioread(soundFile);
silentChannel = zeros(size(y));

soundData(:,1) = y(:,1); % keeps sound for the left channel
soundData(:,2) = silentChannel(:,2); % nullifies the right channel

Does anybody know what I'm doing wrong, or have any thoughts?


问:
On click get input value using jQuery
I have the following:

```<code>$('.checkbox').click(function () {
      console.log(this);
      $.ajax({
        type:'POST',
        url: '/loadProducts',
        data: {},
        success: function(response) {
               console.log(response);
               $('.js-products').html(response);
        }});
    return false;
});
</code>```

Now where I do the console.log(this), it returns:

```<code><div class="ui checkbox checked">
    <input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
    <label>Women</label>
</div>
</code>```

How do I get the input name (gender)? And whether the checkbox is checked out or not?

答:
You can use the method find of jQuery to get the input object, then to check if the gender woman is checked you can use prop method of jQuery as well.

$('.checkbox').click(function () {
  // to get the input
  var $input = $(this).find('input');
  // to check if the checkbox is checked or not
  console.info($input.prop('checked'));

            $.ajax({
                type:'POST',
                url: '/loadProducts',
                data: {},
                success: function(response) {
                    console.log(response);
                    $('.js-products').html(response);
                }});
    return false;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui checkbox checked">
        <input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
        <label>Women</label>
 </div></code>```

Title: On click get input value using jQuery

Body:
I have the following:

$('.checkbox').click(function () {
      console.log(this);
      $.ajax({
        type:'POST',
        url: '/loadProducts',
        data: {},
        success: function(response) {
               console.log(response);
               $('.js-products').html(response);
        }});
    return false;
});

Now where I do the console.log(this), it returns:

    <input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
    Women

How do I get the input name (gender)? And whether the checkbox is checked out or not?

Body:
You can use the method find of jQuery to get the input object, then to check if the gender woman is checked you can use prop method of jQuery as well.

$('.checkbox').click(function () {
  // to get the input
  var $input = $(this).find('input');
  // to check if the checkbox is checked or not
  console.info($input.prop('checked'));

            $.ajax({
                type:'POST',
                url: '/loadProducts',
                data: {},
                success: function(response) {
                    console.log(response);
                    $('.js-products').html(response);
                }});
    return false;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui checkbox checked">
        <input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
        <label>Women</label>
 </div>


问:
Installing Phalcon 1.3.4 incubator
I am trying to install the incubator of Phalcon 1.3.4 as per the documentation at https://github.com/phalcon/incubator

```<code>{
"require": {
    "phalcon/incubator": "v1.2.5"
}
</code>```

in the composer.json.
I have phalcon 1.3.4 installed already. But when I try to update the composer, I get the following error:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
    - Installation request for phalcon/incubator v1.2.5 -> satisfiable by phalcon/incubator[v1.2.5].
    - phalcon/incubator v1.2.5 requires ext-phalcon 1.2.5 -> the requested PHP extension phalcon has the wrong version (1.3.4) installed.

How can this be installed for 1.3.4 version?

答:
You can place the specified version in place of the one you are using.
Or you can put a * to use the newer version.

Then just run the 'composer install'

Title: Installing Phalcon 1.3.4 incubator

Body:
I am trying to install the incubator of Phalcon 1.3.4 as per the documentation at https://github.com/phalcon/incubator

{
"require": {
    "phalcon/incubator": "v1.2.5"
}

in the composer.json.
I have phalcon 1.3.4 installed already. But when I try to update the composer, I get the following error:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
    - Installation request for phalcon/incubator v1.2.5 -> satisfiable by phalcon/incubator[v1.2.5].
    - phalcon/incubator v1.2.5 requires ext-phalcon 1.2.5 -> the requested PHP extension phalcon has the wrong version (1.3.4) installed.

How can this be installed for 1.3.4 version?


问:
How to use react-burger-menu with react router?
I'm trying to follow this guide (https://github.com/negomi/react-burger-menu) to implement react-burger-menu with react-router

Specifically this part https://github.com/negomi/react-burger-menu/wiki/FAQ#why-doesnt-the-link-component-from-react-router-work.

The issue I'm having is that the menu button seems to be placed on the left of the menu and the menu does not seem to hide. Here's a screenshot of what that looks like.

My code looks like this:

app.js

```<code>// This component handles the App template used on every page.
import React, {PropTypes} from 'react';
import SideBar from './common/Header';

class App extends React.Component {
    render() {
        return (
            <div className="container-fluid">
                        <SideBar />
                        {this.props.children}
            </div>
        );
    }
}

App.propTypes = {
    children: PropTypes.object.isRequired
};

export default App;
</code>```

header.js

```<code>import React, {PropTypes} from 'react';
import { Link, IndexLink } from 'react-router';
import {slide as Menu} from 'react-burger-menu';
import Radium from 'radium';

let RadiumLink = Radium(Link);
let RadiumIndexLink = Radium(IndexLink);

const SideBar = () => {
    return (

    <Menu className="bm-menu">
        <RadiumIndexLink className="bm-item-list" to="/" activeClassName="active">Home</RadiumIndexLink>
        <RadiumLink className="bm-item-list" to="/courses" activeClassName="active">Courses</RadiumLink>
        <RadiumLink className="bm-item-list" to="/about" activeClassName="active">About</RadiumLink>
    </Menu>

    );
};

export default SideBar;
</code>```

style.css

```<code>#app {
    font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
    color: #4d4d4d;
    min-width: 550px;
    max-width: 850px;
    margin: 0 auto;
}

a.active {
    color: orange;
}

nav {
    padding-top: 20px;
    padding-bottom: 20px;
}

/* Position and sizing of burger button */
.bm-burger-button {
  position: fixed;
  width: 36px;
  height: 30px;
  left: 36px;
  top: 36px;
}

/* Color/shape of burger icon bars */
.bm-burger-bars {
  background: #373a47;
}

/* Position and sizing of clickable cross button */
.bm-cross-button {
  height: 24px;
  width: 24px;
}

/* Color/shape of close button cross */
.bm-cross {
  background: #bdc3c7;
}

/* General sidebar styles */
.bm-menu {
  background: #373a47;
  padding: 2.5em 1.5em 0;
  font-size: 1.15em;
}

/* Morph shape necessary with bubble or elastic */
.bm-morph-shape {
  fill: #373a47;
}

/* Wrapper for item list */
.bm-item-list {
  color: #b8b7ad;
  padding: 0.8em;
}

/* Styling of overlay */
.bm-overlay {
  background: rgba(0, 0, 0, 0.3);
}
</code>```

Why is the button for the toggle appearing to the left of the actual menu and why doesn't the actual menu hide? If I click the toggle, the menu just shifts right even more...

答:
Add this to your CSS:

```<code>.bm-menu-wrap {
  bottom: 0;
  left: 0;
}
</code>```

This will position the menu to the left of the screen.

The button appearing on the left side of the screen is intentional, if you want it to stick to the page instead of following you when you scroll, change

```<code>.bm-burger-button {
   position:fixed;
}
</code>```

to

```<code>.bm-burger-button {
   position:absolute;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to follow this guide (https://github.com/negomi/react-burger-menu) to implement react-burger-menu with react-router

Specifically this part https://github.com/negomi/react-burger-menu/wiki/FAQ#why-doesnt-the-link-component-from-react-router-work.

The issue I'm having is that the menu button seems to be placed on the left of the menu and the menu does not seem to hide. Here's a screenshot of what that looks like.

My code looks like this:

app.js

// This component handles the App template used on every page.
import React, {PropTypes} from 'react';
import SideBar from './common/Header';

class App extends React.Component {
    render() {
        return (

                        <SideBar />
                        {this.props.children}

        );
    }
}

App.propTypes = {
    children: PropTypes.object.isRequired
};

export default App;

header.js

import React, {PropTypes} from 'react';
import { Link, IndexLink } from 'react-router';
import {slide as Menu} from 'react-burger-menu';
import Radium from 'radium';

let RadiumLink = Radium(Link);
let RadiumIndexLink = Radium(IndexLink);

const SideBar = () => {
    return (

    <Menu className="bm-menu">
        <RadiumIndexLink className="bm-item-list" to="/" activeClassName="active">Home</RadiumIndexLink>
        <RadiumLink className="bm-item-list" to="/courses" activeClassName="active">Courses</RadiumLink>
        <RadiumLink className="bm-item-list" to="/about" activeClassName="active">About</RadiumLink>
    </Menu>

    );
};

export default SideBar;

style.css

#app {
    font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
    color: #4d4d4d;
    min-width: 550px;
    max-width: 850px;
    margin: 0 auto;
}

a.active {
    color: orange;
}

nav {
    padding-top: 20px;
    padding-bottom: 20px;
}

/* Position and sizing of burger button */
.bm-burger-button {
  position: fixed;
  width: 36px;
  height: 30px;
  left: 36px;
  top: 36px;
}

/* Color/shape of burger icon bars */
.bm-burger-bars {
  background: #373a47;
}

/* Position and sizing of clickable cross button */
.bm-cross-button {
  height: 24px;
  width: 24px;
}

/* Color/shape of close button cross */
.bm-cross {
  background: #bdc3c7;
}

/* General sidebar styles */
.bm-menu {
  background: #373a47;
  padding: 2.5em 1.5em 0;
  font-size: 1.15em;
}

/* Morph shape necessary with bubble or elastic */
.bm-morph-shape {
  fill: #373a47;
}

/* Wrapper for item list */
.bm-item-list {
  color: #b8b7ad;
  padding: 0.8em;
}

/* Styling of overlay */
.bm-overlay {
  background: rgba(0, 0, 0, 0.3);
}

Why is the button for the toggle appearing to the left of the actual menu and why doesn't the actual menu hide? If I click the toggle, the menu just shifts right even more...

Body:
Add this to your CSS:

.bm-menu-wrap {
  bottom: 0;
  left: 0;
}

This will position the menu to the left of the screen.

The button appearing on the left side of the screen is intentional, if you want it to stick to the page instead of following you when you scroll, change

.bm-burger-button {
   position:fixed;
}

to

.bm-burger-button {
   position:absolute;
}


问:
Find all customers who have both an account and a loan at the Perryridge branch
I have some tables:

"branch" table(branch_name, branch_city, assets)

"customer" table(customer_name, customer_street, customer_city)

"account" table (account_number, branch_name, balance)

"loan"table (loan_number, branch_name, amount)

"depositor"table (customer_name, account_number)

"borrower" table (customer_name, loan_number)

Now I want to find all customers who have both an account and a loan at the Perryridge branch.

the SQL query that I wrote is

```<code>SELECT distinct customer_name
FROM borrower, loan
WHERE borrower.loan_number = loan.loan_number
      AND branch_name = 'Perryridge'
      AND (branch_name, customer_name )
          IN (SELECT branch_name, customer_name
             FROM depositor, account
             WHERE depositor.account_number = account.account_number )
</code>```

I want to know is there any other simpler SQL query can complete the same question, such as using TABLE UNION.

答:
```<code>try this updated script

SELECT DISTINCT
  customer_name
FROM customer c
INNER JOIN depositor d
  ON d.customer_name=c.customer_name
inner join accounts a on d.account_number = a.account_number
 INNER JOIN borrower b
  ON b.customer_name = c.customer_name
INNER JOIN loan l
  ON l.loan_number = b.loan_number
WHERE l.branch_name = a.branch_name
AND l.branch_name = 'Perryridge'
</code>```

Body:
I have some tables:

"branch" table(branch_name, branch_city, assets)

"customer" table(customer_name, customer_street, customer_city)

"account" table (account_number, branch_name, balance)

"loan"table (loan_number, branch_name, amount)

"depositor"table (customer_name, account_number)

"borrower" table (customer_name, loan_number)

Now I want to find all customers who have both an account and a loan at the Perryridge branch.

the SQL query that I wrote is

SELECT distinct customer_name
FROM borrower, loan
WHERE borrower.loan_number = loan.loan_number
      AND branch_name = 'Perryridge'
      AND (branch_name, customer_name )
          IN (SELECT branch_name, customer_name
             FROM depositor, account
             WHERE depositor.account_number = account.account_number )

I want to know is there any other simpler SQL query can complete the same question, such as using TABLE UNION.


问:
Is there an open source C visual debugger for windows?
Is there an open source C visual debugger for windows?
I have heard about the visual C++ express free edition, but does it have a visual debugger?

Thanks.

答: Eclipse CDT is a good alternative. It also has some nifty features such as refactoring and a preprocessor macro explorer.</p>

OwnerDisplayName: linkedlist

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: splattne

OwnerDisplayName: JesperE


问:
Force Scrollbars Images CSS
How would I accomplish the following without the use of tables?

If I don't wrap the imgs in tds the scroll bars aren't forced.

The imgs are pushed down like regular text with out the tds.

I have tried setting the imgs to display:block, inline-block and a couple other ideas but I'm clueless.

http://jsfiddle.net/zjews/

Edit: I could apply inline-table to the wrapped "a" links but unfortunately internet explorer doesn't support this property.  Does anyone know of a way to emulate inline-table in internet explorer.

答:
is this what you mean?: http://jsfiddle.net/SebastianPataneMasuelli/zjews/1/

i wrapped the links and images in a container div,
and then simply gave the div the style white-space:nowrap;,
which i'm pretty sure is read by all browsers.

Title: Force Scrollbars Images CSS


问:
Transforming a series of tuples into a series of the nth element of each tuple
Is there a clean way to transform a Series of tuples into another Series consisting of first (or nth) element in each tuple? For example,

```<code>ser = pd.Series([ (0,1,2), (3,4,5) ])
</code>```

Should be transform into a series consisting of 0 and 3:

```<code>0  0
1  3
</code>```

(where the 0,1 is the index). Thanks.

答:
Use .str accessor:

```<code>In [90]: ser.str[0]
Out[90]:
0    0
1    3
dtype: int64
</code>```

which is AFAIK a short form of vectorized Series.str.get(N) method:

```<code>In [92]: ser.str.get(0)
Out[92]:
0    0
1    3
dtype: int64
</code>```

Body:
Is there a clean way to transform a Series of tuples into another Series consisting of first (or nth) element in each tuple? For example,

ser = pd.Series([ (0,1,2), (3,4,5) ])

Should be transform into a series consisting of 0 and 3:

0  0
1  3

(where the 0,1 is the index). Thanks.

Body:
Use .str accessor:

In [90]: ser.str[0]
Out[90]:
0    0
1    3
dtype: int64

which is AFAIK a short form of vectorized Series.str.get(N) method:

In [92]: ser.str.get(0)
Out[92]:
0    0
1    3
dtype: int64


问:
Best approach to replace iframes
Have an open ended question.
I have a html form which contains multiple iframes with various urls as their sources (src attribute).
My question is -
1. are there any risks in general to have iframes in a web page? Like I heard that MS edge doesn't support iframes as such - is that true?
2. What's the best approach( and why?) to replace these iframes considering the urls used as sources are not having their own API to be used?

P.S:- all the urls return html streams which are rendered within these iframes.

Looking for some directions here as I am pretty lost in here.  Thanks in advance!

Arka

答:
Re: replacing the iframes, you could possibly load the urls via AJAX or script tags or whatever you want and then bind them to divs. That's heavily dependent on what your frames are doing...

Edit: pasted from my comment below, for example, if you wanted to do this with jQuery, just put this script in your page someplace that makes sense:

```<code>$.ajax(url).done(function(data) {
    $("#divId").html(data);
});
</code>```

Title: Best approach to replace iframes

Body:
Re: replacing the iframes, you could possibly load the urls via AJAX or script tags or whatever you want and then bind them to divs. That's heavily dependent on what your frames are doing...

Edit: pasted from my comment below, for example, if you wanted to do this with jQuery, just put this script in your page someplace that makes sense:

$.ajax(url).done(function(data) {
    $("#divId").html(data);
});


问:
fmap and "flat map" in Haskell
All this time, when any Haskell lecture spoke of "flat map", usually in relation to Monads, I thought it was called "flat" for a reason, i.e. it flattens out the container. So

```<code>[[1,2],[3,4]]
</code>```

would be processed just as if it were

```<code>[1,2,3,4]
</code>```

But now I discover that fmap and map are basically the same thing, the only difference being the application of one for functors and the other for just lists. And that was only done, in the end, to avoid confusing error messages when using map.

Is that true? And if so why did f in fmap come to mean "flat", why not "functor map"?

答:
Here are some explicit equivalent examples of how to do flatMap in Haskell.

```<code>Prelude> map (replicate 3) [1..4]
[[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
Prelude> fmap (replicate 3) [1..4]
[[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
Prelude> concat [[1,2],[3,4]]
[1,2,3,4]
Prelude> concat (map (replicate 3) [1..4])
[1,1,1,2,2,2,3,3,3,4,4,4]
Prelude> concat $ map (replicate 3) [1..4]
[1,1,1,2,2,2,3,3,3,4,4,4]
Prelude> concatMap (replicate 3) [1..4]
[1,1,1,2,2,2,3,3,3,4,4,4]
Prelude> replicate 3 `concatMap` [1..4]
[1,1,1,2,2,2,3,3,3,4,4,4]
Prelude> [1..4] >>= replicate 3
[1,1,1,2,2,2,3,3,3,4,4,4]
</code>```

It should be clear that flatMap is map first and then flat, you flatten the output of the map, as opposed to flattening the input list you are about to process (this isn't flatMap, this has no name, it is just a flat and then map).

Title: fmap and "flat map" in Haskell

Body:
All this time, when any Haskell lecture spoke of "flat map", usually in relation to Monads, I thought it was called "flat" for a reason, i.e. it flattens out the container. So

[[1,2],[3,4]]

would be processed just as if it were

[1,2,3,4]

But now I discover that fmap and map are basically the same thing, the only difference being the application of one for functors and the other for just lists. And that was only done, in the end, to avoid confusing error messages when using map.

Is that true? And if so why did f in fmap come to mean "flat", why not "functor map"?

Body:
Here are some explicit equivalent examples of how to do flatMap in Haskell.

Prelude> map (replicate 3) [1..4]
[[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
Prelude> fmap (replicate 3) [1..4]
[[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
Prelude> concat [[1,2],[3,4]]
[1,2,3,4]
Prelude> concat (map (replicate 3) [1..4])
[1,1,1,2,2,2,3,3,3,4,4,4]
Prelude> concat $ map (replicate 3) [1..4]
[1,1,1,2,2,2,3,3,3,4,4,4]
Prelude> concatMap (replicate 3) [1..4]
[1,1,1,2,2,2,3,3,3,4,4,4]
Prelude> replicate 3 `concatMap` [1..4]
[1,1,1,2,2,2,3,3,3,4,4,4]
Prelude> [1..4] >>= replicate 3
[1,1,1,2,2,2,3,3,3,4,4,4]

It should be clear that flatMap is map first and then flat, you flatten the output of the map, as opposed to flattening the input list you are about to process (this isn't flatMap, this has no name, it is just a flat and then map).


问:
SAS - Survey Select - Selecting Different Sample Size per Stratum
I have a list of financial advisors and I need to pull 4 samples per advisor but catch is in those 4 samples I need to force 2 mortgages, 1 loan, 1 credit card lets say.

Is there a way in the Survey select statement to set the specific number of samples to pull per stratum? I know you can stratify on 1 category and set it as a equal number. I was hoping I could use a mapping of employee names + the number of samples left to pull for each category and have survey select utilize that to pull in a dynamic way.

I'm using this as an example but this only stratifies on employee first and gives me 4 per employee. I would need to further stratify on Product type and set that to a specific sample size per product.

```<code>proc surveyselect data=work.Emp_Table_Final
   method=srs n=4 out=work.testsample SELECTALL;
   strata Employee_No;
run;
</code>```

Thanks i know it might sound complicated, but if i know its possible then i can google the rest

答:
Yes, you can have a dataset be the target of the n option.  That dataset must:

Contain the strata variables as well as a variable SAMPSIZE or _NSIZE_ with the number to select

Have the same type and length as the strata variables

Be sorted by the strata variables

Have an entry for every strata variable value

See the documentation for more details.

```<code>data sample_counts;
length sex $1;
input sex $ _NSIZE_;
datalines;
F 5
M 3
;;;;
run;

proc sort data=sashelp.class out=class;
by sex;
run;

proc surveyselect n=sample_counts method=srs out=samples data=class;
strata sex;
run;
</code>```

For two variables it's the same, you just need two variables in the sample_counts.  Of course it makes it a lot more complicated, and you may want to produce this in an automated fashion.

```<code>proc sort data=sashelp.class out=class;
by sex age;
run;

data sample_counts;
length sex $1;
input sex $ age _NSIZE_;
datalines;
F 11 1
F 12 1
F 13 1
F 14 1
F 15 1
M 11 1
M 12 1
M 13 1
M 14 1
M 15 1
M 16 0
;;;;
run;

/* or do it in an automated way*/

data sample_counts;
  set class;
  by sex age;            *your strata;
  if first.age then do;  *do this once per stratum level;
    if age le 15 then _NSIZE_ = 1;  *whatever your logic is for defining _NSIZE_;
    else _NSIZE_=0;
    output;
  end;
run;

proc surveyselect n=sample_counts method=srs out=samples data=class;
strata sex age;
run;
</code>```

Body:
I have a list of financial advisors and I need to pull 4 samples per advisor but catch is in those 4 samples I need to force 2 mortgages, 1 loan, 1 credit card lets say.

Is there a way in the Survey select statement to set the specific number of samples to pull per stratum? I know you can stratify on 1 category and set it as a equal number. I was hoping I could use a mapping of employee names + the number of samples left to pull for each category and have survey select utilize that to pull in a dynamic way.

I'm using this as an example but this only stratifies on employee first and gives me 4 per employee. I would need to further stratify on Product type and set that to a specific sample size per product.

proc surveyselect data=work.Emp_Table_Final
   method=srs n=4 out=work.testsample SELECTALL;
   strata Employee_No;
run;

Thanks i know it might sound complicated, but if i know its possible then i can google the rest

Body:
Yes, you can have a dataset be the target of the n option.  That dataset must:

Contain the strata variables as well as a variable SAMPSIZE or _NSIZE_ with the number to select

Have the same type and length as the strata variables

Be sorted by the strata variables

Have an entry for every strata variable value

See the documentation for more details.

data sample_counts;
length sex $1;
input sex $ _NSIZE_;
datalines;
F 5
M 3
;;;;
run;

proc sort data=sashelp.class out=class;
by sex;
run;

proc surveyselect n=sample_counts method=srs out=samples data=class;
strata sex;
run;

For two variables it's the same, you just need two variables in the sample_counts.  Of course it makes it a lot more complicated, and you may want to produce this in an automated fashion.

proc sort data=sashelp.class out=class;
by sex age;
run;

data sample_counts;
length sex $1;
input sex $ age _NSIZE_;
datalines;
F 11 1
F 12 1
F 13 1
F 14 1
F 15 1
M 11 1
M 12 1
M 13 1
M 14 1
M 15 1
M 16 0
;;;;
run;

/* or do it in an automated way*/

data sample_counts;
  set class;
  by sex age;            *your strata;
  if first.age then do;  *do this once per stratum level;
    if age le 15 then _NSIZE_ = 1;  *whatever your logic is for defining _NSIZE_;
    else _NSIZE_=0;
    output;
  end;
run;

proc surveyselect n=sample_counts method=srs out=samples data=class;
strata sex age;
run;


问:
How to set single objects in Angularfire2 - Firebase3
As there is a very poor documentation of Angularfire2, I really cannot figure out how to set single Objects in Angularfire2.
My Database structure is very simple:

```<code>{
  "mode" : 0
}
</code>```

The "mode" is an integer value.

Before, I was using pure Javascript and Firebase's Web Version but now want to start with hybrid Ionic Apps.
Everywhere are examples and tutorials about database.list but I dont want to work with lists, but only .set or .update the "mode" value.

[Lists work perfectly fine. There is no problem with the general setup.]

My Code Structure:

```<code>import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

import {AngularFire, FirebaseListObservable} from 'angularfire2';

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

  constructor(public navCtrl: NavController, af: AngularFire) {

  }
}
</code>```

So what would the code be for a simple .set of "mode" to for example integer 2 ?

An answer would be really helpful, I just need to get the hang of the general AngularFire system..

Thanks!

Little Side Question:

If I want to call a function from the html by an event. Example button->

```<code>(click)="setMode(0)"
</code>```

where do I put the actual function in the related typescript code?
Constructor, Component, After?

答:
You can do it as shown below.Hope below code is self-explanatory.</p>

```<code>        export class YourPage {

          // Ref
          mode: FirebaseObjectObservable<any>;

          constructor(public navCtrl: NavController, public af: AngularFire) {

            this.mode = this.af.database.object('/mode');//ref

          }

       setValue(data: any) {
        this.mode.set(data);//set
       }

      updateValue(data: any) {
        this.mode.update(data);//update
      }

     //This is the answer for your 2nd question
     setMode(data):void{
       //method body
     }
 }
</code>```

Body:
As there is a very poor documentation of Angularfire2, I really cannot figure out how to set single Objects in Angularfire2.
My Database structure is very simple:

{
  "mode" : 0
}

The "mode" is an integer value.

Before, I was using pure Javascript and Firebase's Web Version but now want to start with hybrid Ionic Apps.
Everywhere are examples and tutorials about database.list but I dont want to work with lists, but only .set or .update the "mode" value.

[Lists work perfectly fine. There is no problem with the general setup.]

My Code Structure:

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

import {AngularFire, FirebaseListObservable} from 'angularfire2';

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

  constructor(public navCtrl: NavController, af: AngularFire) {

  }
}

So what would the code be for a simple .set of "mode" to for example integer 2 ?

An answer would be really helpful, I just need to get the hang of the general AngularFire system..

Thanks!

Little Side Question:

If I want to call a function from the html by an event. Example button->

(click)="setMode(0)"

where do I put the actual function in the related typescript code?
Constructor, Component, After?

Body:
You can do it as shown below.Hope below code is self-explanatory.

        export class YourPage {

          // Ref
          mode: FirebaseObjectObservable<any>;

          constructor(public navCtrl: NavController, public af: AngularFire) {

            this.mode = this.af.database.object('/mode');//ref

          }

       setValue(data: any) {
        this.mode.set(data);//set
       }

      updateValue(data: any) {
        this.mode.update(data);//update
      }

     //This is the answer for your 2nd question
     setMode(data):void{
       //method body
     }
 }


问:
JAVA- Returning an Array to main
In the program I'm working on, I created a loop to receive 20 individual characters as user input, convert to char, store in array2, and return array2 to main.  When I ran the program I wrote, it seems that the code I wrote didn't store the chars in array2 properly.

In main:

```<code>// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);
</code>```

In getAnswers():

```<code>// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
   String input;  // Holds user input.

   Scanner keyboard = new Scanner(System.in);

   // Request user input.
   System.out.println("Enter the answers for the the multiple choice exam.");

   // Loop to receive input into array.
   for (int index = 0; index < 20; index++)
   {
      System.out.print("Enter number " + (index + 1) +": ");
      input = keyboard.nextLine();
      array2 = input.toCharArray();
   }
   return array2;
}
</code>```

答:
Right now you're creating a new array2 with each input and thereby destroying any previous input with the previous array2 that you created.

If you absolutely need to create a char array, why not append the String answers into a StringBuffer object, and then when done, call toString().toCharArray() on the StringBuffer.

Myself, I'd create an ArrayList and just append the response to the ArrayList and at the end return the ArrayList.

Title: JAVA- Returning an Array to main

Body:
In the program I'm working on, I created a loop to receive 20 individual characters as user input, convert to char, store in array2, and return array2 to main.  When I ran the program I wrote, it seems that the code I wrote didn't store the chars in array2 properly.

In main:

// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);

In getAnswers():

// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
   String input;  // Holds user input.

   Scanner keyboard = new Scanner(System.in);

   // Request user input.
   System.out.println("Enter the answers for the the multiple choice exam.");

   // Loop to receive input into array.
   for (int index = 0; index < 20; index++)
   {
      System.out.print("Enter number " + (index + 1) +": ");
      input = keyboard.nextLine();
      array2 = input.toCharArray();
   }
   return array2;
}


问:
Passing down all attributes in AngularJS component
Is it possible to pass all attributes down from a component instance to one of the elements in the component template?

For example, let's say I have a very simple component:

```<code>angular.module('...').component('customInput', {
  templateUrl: '<input ng-minlength="8">',
  controller: function () { },
  bindings: { }
});
</code>```

Is there any way that I can do something like this:

```<code><custom-input arbitrary-directive></custom-input>
</code>```

and get back

```<code><input ng-min-length="8" arbitrary-directive></input>
</code>```

without specifying arbitraryDirective as a binding specifically? I just want to pass down all unspecified attributes to an inner element.

答:
The solution I got was more imperative than declarative. It's also kind of hacky and brittle. So I'm not terribly happy about it, but it works.

In the controller, add a $postLink hook that looks something like this:

```<code>this.$postLink = function () {
  var input = $element.find('input'); // from the controller's second parameter, $element
  // copy directives and stuff over to inner input element
  angular.forEach($attrs, function (value, key) {
    if (key[0] === '$') {
      return;
    }

    var attr = $attrs.$attr[key];
    input.attr(attr, value);
  });
}
</code>```

Body:
Is it possible to pass all attributes down from a component instance to one of the elements in the component template?

For example, let's say I have a very simple component:

angular.module('...').component('customInput', {
  templateUrl: '<input ng-minlength="8">',
  controller: function () { },
  bindings: { }
});

Is there any way that I can do something like this:

<custom-input arbitrary-directive></custom-input>

and get back

<input ng-min-length="8" arbitrary-directive></input>

without specifying arbitraryDirective as a binding specifically? I just want to pass down all unspecified attributes to an inner element.

Body:
The solution I got was more imperative than declarative. It's also kind of hacky and brittle. So I'm not terribly happy about it, but it works.

In the controller, add a $postLink hook that looks something like this:

this.$postLink = function () {
  var input = $element.find('input'); // from the controller's second parameter, $element
  // copy directives and stuff over to inner input element
  angular.forEach($attrs, function (value, key) {
    if (key[0] === '$') {
      return;
    }

    var attr = $attrs.$attr[key];
    input.attr(attr, value);
  });
}


问:
Android Studio: "cannot resolve symbol" error in my R.java file
When I try to run my Android Studio project, the following error keeps popping up in my R.java file: "cannot resolve symbol 'speakers'"

Here's the specific code line that gave the error:

```<code>  public static final int fragment-speakers=0x7f0f00b3;
</code>```

It only shows up with I try to run it, and no errors are shown when I sync the project.

Things I  have tried to resolve this issue:

Clean Project

Rebuild Project

Invalidate Caches/Restart

The error still persists after trying those things.

答:
The problem is with your Java syntax. You can not use '-' symbol in variable's name.

Try renaming fragment-speakers to fragment_speakers:

```<code>public static final int fragment_speakers = 0x7f0f00b3;
</code>```

For proper variable naming convention and rules, check out https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html

Body:
When I try to run my Android Studio project, the following error keeps popping up in my R.java file: "cannot resolve symbol 'speakers'"

Here's the specific code line that gave the error:

  public static final int fragment-speakers=0x7f0f00b3;

It only shows up with I try to run it, and no errors are shown when I sync the project.

Things I  have tried to resolve this issue:

Clean Project

Rebuild Project

Invalidate Caches/Restart

The error still persists after trying those things.

Body:
The problem is with your Java syntax. You can not use '-' symbol in variable's name.

Try renaming fragment-speakers to fragment_speakers:

public static final int fragment_speakers = 0x7f0f00b3;

For proper variable naming convention and rules, check out https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html


问:
ExpressJS set/get/use cookies
Cannot get setted cookies within requests.

I set my cookie with

```<code>response.cookie('name', 'My name');
</code>```

I would like to get my cookie this way, and it worked before, but I changed express configuration, and I don't know what seems to be the problem now.

```<code>request.cookies is and empty Object
</code>```

My express configuration:

```<code>var express = require('express'),
    api = require('./routes/api');

var app = express();

app.configure(function () {
   app.set('port', process.env.PORT || 3000);
   app.use(express.favicon());
   app.use(express.logger('dev'));
   app.use(express.json());
   //app.use(express.bodyParser());
   app.use(express.compress()); // New call to compress content
   app.use(express.cookieParser());
   app.use(express.session({secret: 'secret'}));
   app.use(app.router);
   app.use(express.methodOverride());
   //app.use(express.static(__dirname + '/public'));
});

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
    next();
});

app.configure('development', function () {
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function () {
    app.use(express.errorHandler());
});
</code>```

Setting Cookie:

```<code>exports.singIn = function (req, res) {
    var mail = req.query.mail,
        password = req.query.password;

    return user.find({
        mail: mail
    }).then(function (d) {
        var user = usersData(u);

        res.cookie('mail', user.mail, { maxAge: 900000});
        res.cookie('password', crypted, { maxAge: 900000});
        res.json({ user: user });
        return { user: user }
    }).catch(function () {
        res.json(400, {"error-tag": "error-sing-in"});
        return {"error-tag": "error-sing-in"};
    });
};
</code>```

Getting Cookie:

```<code>exports.account = function (req, res) {
    var mail = req.cookies.mail,
        password = req.cookies.password;
    //here req.cookies is an empty object. I don't know why?
};
</code>```

答:
An answer for 2017 ..

```<code>const cookieParser = require('cookie-parser');
const express = require('express');
const app = express();
app.use(cookieParser());
</code>```

to get a cookie from an incoming request ..

```<code>let cookie = req.cookies['cookiename'];
</code>```

to set a response cookie (this cookie will be sent on all future incoming requests until deletion or expiration) ..

```<code>res.cookie('cookiename', 'cookievalue', {
    maxAge: 86400 * 1000, // 24 hours
    httpOnly: true, // http only, prevents JavaScript cookie access
    secure: true // cookie must be sent over https / ssl
});
</code>```

to delete a response cookie ..

```<code>res.cookie('cookiename', 'cookievalue', {
    maxAge: 0
});
</code>```

Title: ExpressJS set/get/use cookies

Body:
Cannot get setted cookies within requests.

I set my cookie with

response.cookie('name', 'My name');

I would like to get my cookie this way, and it worked before, but I changed express configuration, and I don't know what seems to be the problem now.

request.cookies is and empty Object

My express configuration:

var express = require('express'),
    api = require('./routes/api');

var app = express();

app.configure(function () {
   app.set('port', process.env.PORT || 3000);
   app.use(express.favicon());
   app.use(express.logger('dev'));
   app.use(express.json());
   //app.use(express.bodyParser());
   app.use(express.compress()); // New call to compress content
   app.use(express.cookieParser());
   app.use(express.session({secret: 'secret'}));
   app.use(app.router);
   app.use(express.methodOverride());
   //app.use(express.static(__dirname + '/public'));
});

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
    next();
});

app.configure('development', function () {
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function () {
    app.use(express.errorHandler());
});

Setting Cookie:

exports.singIn = function (req, res) {
    var mail = req.query.mail,
        password = req.query.password;

    return user.find({
        mail: mail
    }).then(function (d) {
        var user = usersData(u);

        res.cookie('mail', user.mail, { maxAge: 900000});
        res.cookie('password', crypted, { maxAge: 900000});
        res.json({ user: user });
        return { user: user }
    }).catch(function () {
        res.json(400, {"error-tag": "error-sing-in"});
        return {"error-tag": "error-sing-in"};
    });
};

Getting Cookie:

exports.account = function (req, res) {
    var mail = req.cookies.mail,
        password = req.cookies.password;
    //here req.cookies is an empty object. I don't know why?
};

Body:
An answer for 2017 ..

const cookieParser = require('cookie-parser');
const express = require('express');
const app = express();
app.use(cookieParser());

to get a cookie from an incoming request ..

let cookie = req.cookies['cookiename'];

to set a response cookie (this cookie will be sent on all future incoming requests until deletion or expiration) ..

res.cookie('cookiename', 'cookievalue', {
    maxAge: 86400 * 1000, // 24 hours
    httpOnly: true, // http only, prevents JavaScript cookie access
    secure: true // cookie must be sent over https / ssl
});

to delete a response cookie ..

res.cookie('cookiename', 'cookievalue', {
    maxAge: 0
});


问:
Laravel 5.0 Undefined variable result
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:

Routes

```<code>Route::get('/shopsales', 'shopsalescontroller@index');
</code>```

Controller

```<code>class shopsalescontroller extends Controller
</code>```

{

```<code> public function index()
{
    $storeNum = request('storeNum');

   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}
</code>```

}

shopsales view

```<code><section>
  <center><h1><STRONG>Query Data</STRONG></h1></center>
    <ul>
      @foreach ($result as $results)
        <li>Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
            Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}
        </li>
        <br>
      @endforeach
    </ul>

</section>
</code>```

I have used the exact code for the query that is working, struggling to understand why this is not.

答:
in action index
change var $result to $results

in view index
    @foreach ($results as $result)
    @endforeach

Title: Laravel 5.0 Undefined variable result

Body:
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:

Routes

Route::get('/shopsales', 'shopsalescontroller@index');

Controller

class shopsalescontroller extends Controller

{

 public function index()
{
    $storeNum = request('storeNum');

   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}

}

shopsales view

Query Data

      @foreach ($result as $results)

Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
            Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}

      @endforeach

I have used the exact code for the query that is working, struggling to understand why this is not.


问:
JS onunload event won't always work
I want to count how much time visitors spend on a certain page and store it in my MySQL DB.

I thought of just starting a timer on window.onload like this:

```<code>window.onload= startCount;
window.onunload= sendCount;

var b=0;
var y;
function startCount() {
    document.getElementById('livecount').innerHTML=b;
    b=b+1;
    y=setTimeout("startCount()",1000);
}
</code>```

and after the visitor leaves the page (window.onunload), I'm sending the time through an XMLHttpRequest to a PHP file, which will store it in my DB:

```<code>function sendCount() {
    clearTimeout(y);
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","count.php?q="+b,true);
xmlhttp.send();
}
</code>```

The problem is it doesn't always work. I would say it works like 3 out of 10 times I try it.
Could it be that there is not enough time left for the PHP and SQL to be completely executed?

答: by the time the onload handler runs, the page is in the process of being taken down.  I'm not sure what guarantees you have for the state of the DOM or other services, but you certainly can't expect asynch events or timeouts to fire.  Though not part of the standard, most (all?) browsers today provide an onbeforeunload hook which works much the same way as other event handlers, except that you can also return false to cancel the unload if you choose.</p>

Title: JS onunload event won't always work

Body:
I want to count how much time visitors spend on a certain page and store it in my MySQL DB.

I thought of just starting a timer on window.onload like this:

window.onload= startCount;
window.onunload= sendCount;

var b=0;
var y;
function startCount() {
    document.getElementById('livecount').innerHTML=b;
    b=b+1;
    y=setTimeout("startCount()",1000);
}

and after the visitor leaves the page (window.onunload), I'm sending the time through an XMLHttpRequest to a PHP file, which will store it in my DB:

function sendCount() {
    clearTimeout(y);
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","count.php?q="+b,true);
xmlhttp.send();
}

The problem is it doesn't always work. I would say it works like 3 out of 10 times I try it.
Could it be that there is not enough time left for the PHP and SQL to be completely executed?


问:
What is "git pack-redundant -all" actually doing?
The documentation of pack-redundant has no information which pack is actually meant as redundant. And also it recommended to delete only packs containing unreachable objects.

Can I remove all redundant packs from repository, is it safe? Where is no any information actually. Our repositories are about 300GB on disk, and redundant packs are about 150GB. So, that's why I ask this question. If I  remove some required packs, it will be not very good.

答:
The man page of git pack-redundant says

The output is suitable for piping to xargs rm if you are in the root of the repository.

which really suggest the output list files that are not necessary. I have just run

```<code>~ git pack-redundant --all | xargs rm
</code>```

on a repository I have (size similar to yours), and git fsck seems to be happy after that.

I think you could just clone on the same machine, keep the new repository and test the above command on the old one. I think git clone does hard links when cloning local repositories (i.e. using a file path, specifying localhost:stuff doesn't work), so the clone shouldn't take much more space.

Body:
The man page of git pack-redundant says

The output is suitable for piping to xargs rm if you are in the root of the repository.

which really suggest the output list files that are not necessary. I have just run

~ git pack-redundant --all | xargs rm

on a repository I have (size similar to yours), and git fsck seems to be happy after that.

I think you could just clone on the same machine, keep the new repository and test the above command on the old one. I think git clone does hard links when cloning local repositories (i.e. using a file path, specifying localhost:stuff doesn't work), so the clone shouldn't take much more space.


问:
Android Studio build error - Multiple dex files define Landroid/support/v4/
I am unable to build my project in Android Studio.  I get the following error:

```<code>Error:Android Dex: [RaditazAndroid] Unable to execute DX
Error:Android Dex: [RaditazAndroid] com.android.dx.util.DexException: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl;
Error:Android Dex: [RaditazAndroid] at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:592)
Error:Android Dex: [RaditazAndroid] at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:550)
Error:Android Dex: [RaditazAndroid] at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:531)
Error:Android Dex: [RaditazAndroid] at com.android.dx.merge.DexMerger.mergeDexBuffers(DexMerger.java:168)
Error:Android Dex: [RaditazAndroid] at com.android.dx.merge.DexMerger.merge(DexMerger.java:186)
Error:Android Dex: [RaditazAndroid] at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:300)
Error:Android Dex: [RaditazAndroid] at com.android.dx.command.dexer.Main.run(Main.java:232)
Error:Android Dex: [RaditazAndroid] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Error:Android Dex: [RaditazAndroid] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
Error:Android Dex: [RaditazAndroid] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
Error:Android Dex: [RaditazAndroid] at java.lang.reflect.Method.invoke(Method.java:597)
Error:Android Dex: [RaditazAndroid] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:147)
Error:Android Dex: [RaditazAndroid] at org.jetbrains.android.compiler.tools.AndroidDxRunner.main(AndroidDxRunner.java:276)
Error:Android Dex: [RaditazAndroid] at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:121)
</code>```

However, this error means nothing to me.  It does not provide clues as to where I should begin fixing my project.  Has anybody encountered something similar?

答:
I had same issue in Android Studio 2.3, in my case I had a mixture of version numbers which threw the build out, I changed:

```<code>dependencies {
    compile 'com.google.android.gms:play-services-wearable:7.5.0'
    compile 'com.google.android.gms:play-services-analytics:7.5.0'
    compile 'com.google.android.gms:play-services-drive:8.4.0'
}
</code>```

to

```<code>dependencies {
    compile 'com.google.android.gms:play-services-wearable:8.4.0'
    compile 'com.google.android.gms:play-services-analytics:8.4.0'
    compile 'com.google.android.gms:play-services-drive:8.4.0'
}
</code>```

Body:
I am unable to build my project in Android Studio.  I get the following error:

Error:Android Dex: [RaditazAndroid] Unable to execute DX
Error:Android Dex: [RaditazAndroid] com.android.dx.util.DexException: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl;
Error:Android Dex: [RaditazAndroid] at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:592)
Error:Android Dex: [RaditazAndroid] at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:550)
Error:Android Dex: [RaditazAndroid] at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:531)
Error:Android Dex: [RaditazAndroid] at com.android.dx.merge.DexMerger.mergeDexBuffers(DexMerger.java:168)
Error:Android Dex: [RaditazAndroid] at com.android.dx.merge.DexMerger.merge(DexMerger.java:186)
Error:Android Dex: [RaditazAndroid] at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:300)
Error:Android Dex: [RaditazAndroid] at com.android.dx.command.dexer.Main.run(Main.java:232)
Error:Android Dex: [RaditazAndroid] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Error:Android Dex: [RaditazAndroid] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
Error:Android Dex: [RaditazAndroid] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
Error:Android Dex: [RaditazAndroid] at java.lang.reflect.Method.invoke(Method.java:597)
Error:Android Dex: [RaditazAndroid] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:147)
Error:Android Dex: [RaditazAndroid] at org.jetbrains.android.compiler.tools.AndroidDxRunner.main(AndroidDxRunner.java:276)
Error:Android Dex: [RaditazAndroid] at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:121)

However, this error means nothing to me.  It does not provide clues as to where I should begin fixing my project.  Has anybody encountered something similar?

Body:
I had same issue in Android Studio 2.3, in my case I had a mixture of version numbers which threw the build out, I changed:

dependencies {
    compile 'com.google.android.gms:play-services-wearable:7.5.0'
    compile 'com.google.android.gms:play-services-analytics:7.5.0'
    compile 'com.google.android.gms:play-services-drive:8.4.0'
}

to

dependencies {
    compile 'com.google.android.gms:play-services-wearable:8.4.0'
    compile 'com.google.android.gms:play-services-analytics:8.4.0'
    compile 'com.google.android.gms:play-services-drive:8.4.0'
}


问:
Java - HashMap Iteration - Exception
I want to iterate a HashMap like:

```<code>        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            map.replace(entry.getKey(), entry.getValue()-1);
            if (entry.getValue() == 0) {
                map.remove(entry.getKey(), 0);
            }
        }
</code>```

This ends in an Exception: java.util.ConcurrentModificationException

Any solutions?

Kind regards

答:
You can't remove elements from an existing Set without using Iterator, otherwise, it will throw ConcurrentModificationException

So, place values to a new Map object if(value-1 !=0) as shown below:

```<code>        Map<Integer, Integer> map = new HashMap<>();
        Map<Integer, Integer> newMap = new HashMap<>();
        Iterator<Integer> iterator =map.keySet().iterator();
        while(iterator.hasNext()) {
            int key = iterator.next();
            int value = map.get(key);
            if(value-1 !=0) {
                newMap.put(key, value-1);
            }
        }
</code>```

Title: Java - HashMap Iteration - Exception

Body:
I want to iterate a HashMap like:

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            map.replace(entry.getKey(), entry.getValue()-1);
            if (entry.getValue() == 0) {
                map.remove(entry.getKey(), 0);
            }
        }

This ends in an Exception: java.util.ConcurrentModificationException

Any solutions?

Kind regards

Body:
You can't remove elements from an existing Set without using Iterator, otherwise, it will throw ConcurrentModificationException

So, place values to a new Map object if(value-1 !=0) as shown below:

        Map<Integer, Integer> map = new HashMap<>();
        Map<Integer, Integer> newMap = new HashMap<>();
        Iterator<Integer> iterator =map.keySet().iterator();
        while(iterator.hasNext()) {
            int key = iterator.next();
            int value = map.get(key);
            if(value-1 !=0) {
                newMap.put(key, value-1);
            }
        }


问:
Insert blank row into a Quickbooks purchase order using ItemAggregate
I'm looking to automate the generation of purchase orders (POs) in Quickbooks.

We're using the CData ADO.NET provider for Quickbooks (desktop), but since we're using ItemAggregate to add lines to POs, I'm not sure the specific adapter makes a difference.

For readability, our POs have blank rows between certain sections. I'm struggling to replicate this in ItemAggregate. I've tried:

adding <Row/> (QB ignores this)

adding <Row><ItemDescription/></Row> (QB ignores this)

as #2, but with a single space in the ItemDescription (QB ignores this)

as #2, but with a tab in the ItemDescription (QB ignores this)

as #2, but with   in the ItemDescription (QB prints " ")

as #5, but change   to a single space after saving the PO (causes an exception: "There was an error when modifying a PurchaseOrder. QuickBooks error message: You have no items or one or more of your amounts is not associated with an item. Please enter an item.")

Does anyone know of a programmatic way to get QB to add a blank line to a purchase order?

答:
The CData ADO.NET Provider has been updated to support this functionality.

You will need to add a new hidden connection property to your connection string. Add PreserveAggregateWhitespace=true to your connection string. Now when you insert or update transactions, your XML elements will retain their whitespace:

```<code><Row><ItemDescription> </ItemDescription></Row>
</code>```

Your INSERT statement for a new SalesOrder could look like:

```<code>INSERT INTO
  SalesOrders (CustomerName, ItemAggregate)
VALUES
  ('Doe, John','<SalesOrderLineItems><Row><ItemName>Repairs</ItemName><ItemQuantity>1</ItemQuantity></Row><Row><ItemDescription> </ItemDescription></Row><Row><ItemName>Removal</ItemName><ItemQuantity>2</ItemQuantity></Row></SalesOrderLineItems>')
</code>```

Notice the blank space in the ItemDescription.

You can contact the CData Software Support Team if you need the updated build.

Body:
The CData ADO.NET Provider has been updated to support this functionality.

You will need to add a new hidden connection property to your connection string. Add PreserveAggregateWhitespace=true to your connection string. Now when you insert or update transactions, your XML elements will retain their whitespace:

<Row><ItemDescription> </ItemDescription></Row>

Your INSERT statement for a new SalesOrder could look like:

INSERT INTO
  SalesOrders (CustomerName, ItemAggregate)
VALUES
  ('Doe, John','<SalesOrderLineItems><Row><ItemName>Repairs</ItemName><ItemQuantity>1</ItemQuantity></Row><Row><ItemDescription> </ItemDescription></Row><Row><ItemName>Removal</ItemName><ItemQuantity>2</ItemQuantity></Row></SalesOrderLineItems>')

Notice the blank space in the ItemDescription.

You can contact the CData Software Support Team if you need the updated build.


问:
loop through a filtered range excel vba
I want to highlight cells when there are 3 or more with the same value, I have the bellow code but it isn't working right because it loop twice into each range. Can someone tell me what is wrong?

```<code>Sub HighlightCells()
Dim k As Integer, myCounter As Integer, firstRow As Integer
Dim myClientExport As Worksheet, myTemplate As Variant
Dim vRange As Range, myRange As Range
Dim myAddr As String

Set myClientExport = Excel.ActiveSheet
Set vRange = myClientExport.UsedRange.SpecialCells(xlCellTypeVisible)

firstRow = vRange.Areas(2).Rows(1).Row
myAddr = Cells(firstRow, 4).Value
myCounter = 0
For Each myRange In vRange.Rows
    k = myRange.Row

    If k > firstRow Then
        If myAddr = Cells(k, 4).Value Then
            myCounter = myCounter + 1
        Else
            myAddr = Cells(k, 4).Value
            myCounter = 0
        End If
        Select Case myCounter
            Case 3

                For i = 0 To 2
                    OId = Cells(k - i, 1).Value
                 Next i
                Cells(k, 4).Interior.ColorIndex = 27
                Cells(k - 1, 4).Interior.ColorIndex = 27
                Cells(k - 2, 4).Interior.ColorIndex = 27
            Case Is > 3
                Cells(k, 4).Interior.ColorIndex = 27
        End Select
    End If
Next myRange
End Sub
</code>```

My data unfiltered look like:

My data filtered look like

I want to highlight all Address with 3 or more Active order status.

答:
You may try something like this to see if that works for you.
The code will place a CountIFs formula in column F and delete it in the end.
You may tweak the code as per your requirement.</p>

```<code>Sub HighlightFilteredCells()
Dim sws As Worksheet
Dim lr As Long
Dim cell As Range
Set sws = Sheets("Sheet1")
If sws.FilterMode Then sws.ShowAllData
lr = Cells(Rows.Count, 1).End(xlUp).Row
sws.Range("F2:F" & lr).Formula = "=COUNTIFS($D$2:$D$" & lr & ",D2,$E$2:$E$" & lr & ",""Active"")"
sws.Columns(5).Interior.ColorIndex = xlNone
With sws.Rows(1)
    .AutoFilter field:=5, Criteria1:="Active"
    If sws.Range("A1").CurrentRegion.SpecialCells(xlCellTypeVisible).Rows.Count > 1 Then
        For Each cell In sws.Range("F2:F" & lr).SpecialCells(xlCellTypeVisible)
            If cell.Value >= 3 Then cell.Offset(0, -1).Interior.Color = vbYellow
        Next cell
    End If
End With
sws.Columns(6).Clear
End Sub
</code>```

Title: loop through a filtered range excel vba

Body:
I want to highlight cells when there are 3 or more with the same value, I have the bellow code but it isn't working right because it loop twice into each range. Can someone tell me what is wrong?

Sub HighlightCells()
Dim k As Integer, myCounter As Integer, firstRow As Integer
Dim myClientExport As Worksheet, myTemplate As Variant
Dim vRange As Range, myRange As Range
Dim myAddr As String

Set myClientExport = Excel.ActiveSheet
Set vRange = myClientExport.UsedRange.SpecialCells(xlCellTypeVisible)

firstRow = vRange.Areas(2).Rows(1).Row
myAddr = Cells(firstRow, 4).Value
myCounter = 0
For Each myRange In vRange.Rows
    k = myRange.Row

    If k > firstRow Then
        If myAddr = Cells(k, 4).Value Then
            myCounter = myCounter + 1
        Else
            myAddr = Cells(k, 4).Value
            myCounter = 0
        End If
        Select Case myCounter
            Case 3

                For i = 0 To 2
                    OId = Cells(k - i, 1).Value
                 Next i
                Cells(k, 4).Interior.ColorIndex = 27
                Cells(k - 1, 4).Interior.ColorIndex = 27
                Cells(k - 2, 4).Interior.ColorIndex = 27
            Case Is > 3
                Cells(k, 4).Interior.ColorIndex = 27
        End Select
    End If
Next myRange
End Sub

My data unfiltered look like:

My data filtered look like

I want to highlight all Address with 3 or more Active order status.

Body:
You may try something like this to see if that works for you.
The code will place a CountIFs formula in column F and delete it in the end.
You may tweak the code as per your requirement.

Sub HighlightFilteredCells()
Dim sws As Worksheet
Dim lr As Long
Dim cell As Range
Set sws = Sheets("Sheet1")
If sws.FilterMode Then sws.ShowAllData
lr = Cells(Rows.Count, 1).End(xlUp).Row
sws.Range("F2:F" & lr).Formula = "=COUNTIFS($D$2:$D$" & lr & ",D2,$E$2:$E$" & lr & ",""Active"")"
sws.Columns(5).Interior.ColorIndex = xlNone
With sws.Rows(1)
    .AutoFilter field:=5, Criteria1:="Active"
    If sws.Range("A1").CurrentRegion.SpecialCells(xlCellTypeVisible).Rows.Count > 1 Then
        For Each cell In sws.Range("F2:F" & lr).SpecialCells(xlCellTypeVisible)
            If cell.Value >= 3 Then cell.Offset(0, -1).Interior.Color = vbYellow
        Next cell
    End If
End With
sws.Columns(6).Clear
End Sub


问:
How to remove missing files warning in XCode 8?
I created 2 files in wrong location. Then I move them in finder and delete their reference in the project. After that I receive "Missing file" warning.

How to remove those references and remove the warning?

答:
I had this problem when I deleted files from my project and chose "Remove Reference Only" but later manually deleted the files using Finder.  I think the Source Control system got confused and I kept getting these warnings for a bunch of files.

I was able to fix it by creating a new branch in Source Control, merging the files from master and switching to that branch.  After that all the warnings disappeared.  It seemed to understand that the files are now deleted so no more warnings.

I was then able to switch back to the main branch and the warnings were still gone so I deleted the new branch and everything is back to normal now.


问:
Calculating the Sum of values in a linked list
I got a programming question at an interview recently.

There are 2 linked lists. Each node stores a value from 1 through 9 (indicating one index of the number). Hence 123 would be a linked list 1->2->3

The task was to create a function:

static LinkedListNode getSum(LinkedListNode a, LinkedListNode b)

that would return the sum of the values in the 2 linked list arguements.

If the array a is: 1->2->3->4

And the array b is: 5->6->7->8

The answer should be: 6->9->1->2

Here is my algorithm:

Go through each node in a and b, get the values as an integer and add them. Create a new linked list with the those values.

Here is the code: It runs with a complexity of O(n) roughly I assume. Once through each of the array inputs and once to create the output array.

Any improvements? Better algorithms... or code improvements

```<code>public class LinkedListNode {
        LinkedListNode next;
        int value;

    public LinkedListNode(int value) {
        this.value = value;
        this.next = null;
    }

    static int getValue(LinkedListNode node) {
        int value = node.value;
        while (node.next != null) {
            node = node.next;
            value = value * 10 + node.value;
        }
        return value;
    }

    static LinkedListNode getSum(LinkedListNode a, LinkedListNode b) {
        LinkedListNode answer = new LinkedListNode(0);
        LinkedListNode ans = answer;
        int aval = getValue(a);
        int bval = getValue(b);
        int result = aval + bval;
        while (result > 0) {
            int len = (int) Math.pow((double) 10,
                    (double) String.valueOf(result).length() - 1);
            int val = result / len;
            ans.next = new LinkedListNode(val);
            ans = ans.next;
            result = result - val*len;
            }
        return answer.next;
    }
}
</code>```

答:
You can do it by reversing the linkedlists. This is a c# implementation and
it's O(n).</p>

```<code>    public LinkedList ElementSum(LinkedList other)
    {
        LinkedList linkedListSum = new LinkedList();
        this.Reverse();
        other.Reverse();
        Node n1 = this.head, n2 = other.head;
        int toAdd = 0, carryOver = 0;
        while ((n1 != null) || (n2 != null))
        {
            int num1 = (int) (n1 == null ? 0 : n1.NodeContent);
            int num2 = (int) (n2 == null ? 0 : n2.NodeContent);
            toAdd = (num1 + num2 + carryOver) % 10;
            carryOver = (int)(num1 + num2 + carryOver) / 10;
            linkedListSum.Add(toAdd);
            n1 = (n1 == null ? null : n1.Next);
            n2 = (n2 == null ? null : n2.Next);
        }
        this.Reverse();
        other.Reverse();
        linkedListSum.Reverse();
        return linkedListSum;
    }
</code>```

Body:
I got a programming question at an interview recently.

There are 2 linked lists. Each node stores a value from 1 through 9 (indicating one index of the number). Hence 123 would be a linked list 1->2->3

The task was to create a function:

static LinkedListNode getSum(LinkedListNode a, LinkedListNode b)

that would return the sum of the values in the 2 linked list arguements.

If the array a is: 1->2->3->4

And the array b is: 5->6->7->8

The answer should be: 6->9->1->2

Here is my algorithm:

Go through each node in a and b, get the values as an integer and add them. Create a new linked list with the those values.

Here is the code: It runs with a complexity of O(n) roughly I assume. Once through each of the array inputs and once to create the output array.

Any improvements? Better algorithms... or code improvements

public class LinkedListNode {
        LinkedListNode next;
        int value;

    public LinkedListNode(int value) {
        this.value = value;
        this.next = null;
    }

    static int getValue(LinkedListNode node) {
        int value = node.value;
        while (node.next != null) {
            node = node.next;
            value = value * 10 + node.value;
        }
        return value;
    }

    static LinkedListNode getSum(LinkedListNode a, LinkedListNode b) {
        LinkedListNode answer = new LinkedListNode(0);
        LinkedListNode ans = answer;
        int aval = getValue(a);
        int bval = getValue(b);
        int result = aval + bval;
        while (result > 0) {
            int len = (int) Math.pow((double) 10,
                    (double) String.valueOf(result).length() - 1);
            int val = result / len;
            ans.next = new LinkedListNode(val);
            ans = ans.next;
            result = result - val*len;
            }
        return answer.next;
    }
}

Body:
You can do it by reversing the linkedlists. This is a c# implementation and
it's O(n).

    public LinkedList ElementSum(LinkedList other)
    {
        LinkedList linkedListSum = new LinkedList();
        this.Reverse();
        other.Reverse();
        Node n1 = this.head, n2 = other.head;
        int toAdd = 0, carryOver = 0;
        while ((n1 != null) || (n2 != null))
        {
            int num1 = (int) (n1 == null ? 0 : n1.NodeContent);
            int num2 = (int) (n2 == null ? 0 : n2.NodeContent);
            toAdd = (num1 + num2 + carryOver) % 10;
            carryOver = (int)(num1 + num2 + carryOver) / 10;
            linkedListSum.Add(toAdd);
            n1 = (n1 == null ? null : n1.Next);
            n2 = (n2 == null ? null : n2.Next);
        }
        this.Reverse();
        other.Reverse();
        linkedListSum.Reverse();
        return linkedListSum;
    }