问:
Code::Blocks does not parse header #define
Code::Blocks has a surprising shortcoming — its editor is unable to parse multiple source files correctly to do #ifdef / #ifndef style code path highlighting correctly. It only works for the file where you define macros directly in but not on any other related project file. For example:

MyHeader.h

```<code>#define MRAA__
</code>```

MyProgram.c

```<code>#include "MyHeader.h"
#ifndef MRAA__
#define FOO() Foo_Bcm2835()
#else
#define FOO() Foo_Mraa()
#endif
</code>```

The #ifndef MRAA__ evaluates as true although you have defined MRAA__ in your header file. Now the compiler handles this just fine but visually in editor it's wrong.

Yes, you can turn off the graying-out entirely but it's pretty handy feature to have around... Is there really no plugin / patch to fix this functionality? I could find people complaining about it in 2012.

答:
This post is not intended as an answer, just a clarification.
An image is included to highlight the problem discussed in the
original post, and hopefully draw the attention of Code::Blocks
developers to an existing bug registered at least 5 years ago - and similar.

As of today I am not aware of any patches or fixes or revisions to address this problem...

The following image was captured in Code::Blocks version 13.12 in a
C project, and illustrates the OP syntax highlighting problem. (Note:
OP version is even newer: 16.01)

Although Code::Blocks (and GCC) correctly executes only the "true"
branches of an #ifdef (or #ifndef) directive, syntax highlighting is reveresed for
symbols defined in any file other than the one it is being used.

For example, MRAA__ is defined in a file other than this .c file,
and when it is used here, the "true" branch of the #ifdef is greyed out.
But for ABCD__, which is defined in this file, the "false" branch is greyed out.

Body:
Code::Blocks has a surprising shortcoming — its editor is unable to parse multiple source files correctly to do #ifdef / #ifndef style code path highlighting correctly. It only works for the file where you define macros directly in but not on any other related project file. For example:

MyHeader.h

#define MRAA__

MyProgram.c

#include "MyHeader.h"
#ifndef MRAA__
#define FOO() Foo_Bcm2835()
#else
#define FOO() Foo_Mraa()
#endif

The #ifndef MRAA__ evaluates as true although you have defined MRAA__ in your header file. Now the compiler handles this just fine but visually in editor it's wrong.

Yes, you can turn off the graying-out entirely but it's pretty handy feature to have around... Is there really no plugin / patch to fix this functionality? I could find people complaining about it in 2012.


来源: stackexchange

问:
Pointer code smell C++
I'm using the gsl library in C++. I have declared a gsl_vector pointer mesh as a private member of the class.

```<code>private:
    gsl_vector * mesh;
</code>```

I also have a method, MeshBuilder, that declares a gsl_vector, pointer mesh (over-riding the original mesh variable) and returns mesh.

```<code>gsl_vector * ThinFilm::LinearMesh(...){
    gsl_vector * mesh = gsl_vector_alloc(numberofcells);
    ...
    return mesh;
}
</code>```

I then assign the result of the method to the variable mesh as:

```<code>mesh = MeshBuilder(...);
</code>```

It compiles and runs just fine (no warnings either, with -Wall). Stepping through the program I noticed that the variable mesh is assigned an address, and then the MeshBuilder overwrites that. Which is exactly what I programmed to do.

But is it good practice? After all, shouldn't I not assign a value to the pointer address?

Shouldn't I instead not declare a the mesh pointer in the MeshBuilder method and therefore directly use the pointer declared in the private section of the class?

I'm guessing the only reason this works is because the address value I'm assigning to mesh is in fact valid having been declared.

答:
Simple answer is no, in your current code, you are leaking a resource.
The problem is gsl_vector_alloc does not return a value, but indeed an address, which point to a struct that contain the value you except to see. In this context, gsl_vector_alloc is behaving similar to using new, as it allocating a vector struct, and initializing it.

The function gsl_vector_alloc, as it name suggest allocate a vector. This mean you need to free it with gsl_vector_free before you are overriding it.
Also allocation can fail, in such a case gsl_vector_alloc will return NULL and you will have to check for it, before using mesh.

Side note: In the function you are providing you call your local variable mesh, which has the same name as a private member, this is a bad practice as the local variable will hide the private member.

ContentLicense: CC BY-SA 3.0

Title: Pointer code smell C++

Body:
I'm using the gsl library in C++. I have declared a gsl_vector pointer mesh as a private member of the class.

private:
    gsl_vector * mesh;

I also have a method, MeshBuilder, that declares a gsl_vector, pointer mesh (over-riding the original mesh variable) and returns mesh.

gsl_vector * ThinFilm::LinearMesh(...){
    gsl_vector * mesh = gsl_vector_alloc(numberofcells);
    ...
    return mesh;
}

I then assign the result of the method to the variable mesh as:

mesh = MeshBuilder(...);

It compiles and runs just fine (no warnings either, with -Wall). Stepping through the program I noticed that the variable mesh is assigned an address, and then the MeshBuilder overwrites that. Which is exactly what I programmed to do.

But is it good practice? After all, shouldn't I not assign a value to the pointer address?

Shouldn't I instead not declare a the mesh pointer in the MeshBuilder method and therefore directly use the pointer declared in the private section of the class?

I'm guessing the only reason this works is because the address value I'm assigning to mesh is in fact valid having been declared.


问:
How to see list of #TODO-s in Spyder?
I use '#TODO: xxx' format for marking todo-s in Spyder. Is there any way to see full list of TODO-s in a file, in Spyder?</p>

答:
You have to go to the menu

Source > Show todo list

to get the full list of TODO's in your file.

Title: How to see list of #TODO-s in Spyder?


问:
Homebrew link python to /usr/local/bin/ on Mac
I would like to ask how to install python on Mac through Homebrew.
Homebrew is a package manager for Mac.

Specifically I would like to link python to /usr/local/bin/ and not to /usr/bin/ where it is linked by default.

The reason to do this is that I want then to install a virtual environment which will provide me the libraries of python (see: https://www.learnopencv.com/install-opencv3-on-macos/). Otherwise the virtual environment cannot be installed as source /usr/local/bin/virtualenvwrapper.sh in the bash_profile cannot be read.

Do you have any idea how can I do this?

In brief, I want the output to which python at terminal to be /usr/local/bin/python and not /usr/bin/python as it is by default.

UPDATE:
I applied the changes that TomD described below (I hope correctly!) but now which python has not output: is not /usr/local/bin/python as I would like (not even /usr/bin/python).
So why finally python from 'cellar' is not linked to /usr/local/bin/python?

答:
Just to give a few basics first.  Homebrew installs everything in the "cellar".  That's where the "kegs" (packages) go.

Homebrew then creates symlinks to their files into /usr/local/.

For example, python is installed in /usr/local/Cellar/python

So I would suggest after installation, remove the symlink to /usr/bin and make one to /usr/local/bin.

remove symlink:

```<code>unlink /usr/bin/python
</code>```

make symlink:

```<code>ln -s /usr/local/Cellar/python /usr/bin/python
</code>```

also make sure that your $PATH is correct and /usr/local/bin is before usr/bin

Body:
Just to give a few basics first.  Homebrew installs everything in the "cellar".  That's where the "kegs" (packages) go.

Homebrew then creates symlinks to their files into /usr/local/.

For example, python is installed in /usr/local/Cellar/python

So I would suggest after installation, remove the symlink to /usr/bin and make one to /usr/local/bin.

remove symlink:

unlink /usr/bin/python

make symlink:

ln -s /usr/local/Cellar/python /usr/bin/python

also make sure that your $PATH is correct and /usr/local/bin is before usr/bin


问:
Transforming data from one form to another
I have the following list:

```<code>l = [
        %{id: 1, name: "aash", possess: "car"},
        %{id: 1, name: "aash", possess: "bike"},
        %{id: 2, name: "rahul", possess: "scooter"}
]
</code>```

I want to convert this into the following format:

```<code>ans = [
        %{id: 1, name: "aash", possess: ["car", "bike"]},
        %{id: 2, name: "rahul", possess: ["scooter"]}
]
</code>```

Any idea on how to do this in elixir? Since all the variables are immutable, I don't know how to achieve the above transformation.

答:
I'd use Enum.group_by/3 with the mapper function (third argument) returning only the possess field.

```<code>[
  %{id: 1, name: "aash", possess: "car"},
  %{id: 1, name: "aash", possess: "bike"},
  %{id: 2, name: "rahul", possess: "scooter"}
]
|> Enum.group_by(&{&1.id, &1.name}, & &1.possess)
|> Enum.map(fn {{id, name}, possess} ->
  %{id: id, name: name, possess: possess}
end)
|> IO.inspect
</code>```

Output:

```<code>[%{id: 1, name: "aash", possess: ["car", "bike"]},
 %{id: 2, name: "rahul", possess: ["scooter"]}]
</code>```

Body:
I have the following list:

l = [
        %{id: 1, name: "aash", possess: "car"},
        %{id: 1, name: "aash", possess: "bike"},
        %{id: 2, name: "rahul", possess: "scooter"}
]

I want to convert this into the following format:

ans = [
        %{id: 1, name: "aash", possess: ["car", "bike"]},
        %{id: 2, name: "rahul", possess: ["scooter"]}
]

Any idea on how to do this in elixir? Since all the variables are immutable, I don't know how to achieve the above transformation.

Body:
I'd use Enum.group_by/3 with the mapper function (third argument) returning only the possess field.

[
  %{id: 1, name: "aash", possess: "car"},
  %{id: 1, name: "aash", possess: "bike"},
  %{id: 2, name: "rahul", possess: "scooter"}
]
|> Enum.group_by(&{&1.id, &1.name}, & &1.possess)
|> Enum.map(fn {{id, name}, possess} ->
  %{id: id, name: name, possess: possess}
end)
|> IO.inspect

Output:

[%{id: 1, name: "aash", possess: ["car", "bike"]},
 %{id: 2, name: "rahul", possess: ["scooter"]}]


问:
openjdk 8: error - No public or protected classes found to document
I'm on Debian, and have already installed OpenJDK 8 along with the packages openjdk-8-doc and default-jdk-doc; However I can't view any documentation for the classes of JDK 8 API, whenever I specify the class or package name to the javadoc utility, which fails to show the doc throwing the following errors:

ArrayList case:

```<code>kais@debian:~$ javadoc ArrayList
Loading source files for package ArrayList...
javadoc: warning - No source files for package ArrayList
Constructing Javadoc information...
javadoc: warning - No source files for package ArrayList
javadoc: error - No public or protected classes found to document.
1 error
2 warnings
kais@debian:~$ javadoc java.lang.ArrayList
Loading source files for package java.lang.ArrayList...
javadoc: warning - No source files for package java.lang.ArrayList
Constructing Javadoc information...
javadoc: warning - No source files for package java.lang.ArrayList
javadoc: error - No public or protected classes found to document.
1 error
2 warnings
</code>```

JPanel case:

```<code>kais@debian:~$ javadoc JPanel
Loading source files for package JPanel...
javadoc: warning - No source files for package JPanel
Constructing Javadoc information...
javadoc: warning - No source files for package JPanel
javadoc: error - No public or protected classes found to document.
1 error
2 warnings
kais@debian:~$ javadoc javax.swing.JPanel
Loading source files for package javax.swing.JPanel...
javadoc: warning - No source files for package javax.swing.JPanel
Constructing Javadoc information...
javadoc: warning - No source files for package javax.swing.JPanel
javadoc: error - No public or protected classes found to document.
1 error
2 warnings
kais@debian:~$ javadoc javax.swing
Loading source files for package javax.swing...
javadoc: warning - No source files for package javax.swing
Constructing Javadoc information...
javadoc: warning - No source files for package javax.swing
javadoc: error - No public or protected classes found to document.
1 error
2 warnings
</code>```

This seems to me weird, as the installed package openjdk-8-doc is supposed to contain the doc required by the javadoc ..

Any thoughts?

答:
The Javadoc tool is supposed to create Javadoc out of Java source. It's not a tool to show the javadoc of a particular class. The Javadocs of the classes in the JVM is available for download at Oracle or can be browsed online.

As you said in your question, you "installed" the docs for your corresponding JDK, so instead of downloading it again or browsing it online, you can change to the "installation directory" of the doc-package and open the index-html file that should be there at its root.

Body:
I'm on Debian, and have already installed OpenJDK 8 along with the packages openjdk-8-doc and default-jdk-doc; However I can't view any documentation for the classes of JDK 8 API, whenever I specify the class or package name to the javadoc utility, which fails to show the doc throwing the following errors:

ArrayList case:

kais@debian:~$ javadoc ArrayList
Loading source files for package ArrayList...
javadoc: warning - No source files for package ArrayList
Constructing Javadoc information...
javadoc: warning - No source files for package ArrayList
javadoc: error - No public or protected classes found to document.
1 error
2 warnings
kais@debian:~$ javadoc java.lang.ArrayList
Loading source files for package java.lang.ArrayList...
javadoc: warning - No source files for package java.lang.ArrayList
Constructing Javadoc information...
javadoc: warning - No source files for package java.lang.ArrayList
javadoc: error - No public or protected classes found to document.
1 error
2 warnings

JPanel case:

kais@debian:~$ javadoc JPanel
Loading source files for package JPanel...
javadoc: warning - No source files for package JPanel
Constructing Javadoc information...
javadoc: warning - No source files for package JPanel
javadoc: error - No public or protected classes found to document.
1 error
2 warnings
kais@debian:~$ javadoc javax.swing.JPanel
Loading source files for package javax.swing.JPanel...
javadoc: warning - No source files for package javax.swing.JPanel
Constructing Javadoc information...
javadoc: warning - No source files for package javax.swing.JPanel
javadoc: error - No public or protected classes found to document.
1 error
2 warnings
kais@debian:~$ javadoc javax.swing
Loading source files for package javax.swing...
javadoc: warning - No source files for package javax.swing
Constructing Javadoc information...
javadoc: warning - No source files for package javax.swing
javadoc: error - No public or protected classes found to document.
1 error
2 warnings

This seems to me weird, as the installed package openjdk-8-doc is supposed to contain the doc required by the javadoc ..

Any thoughts?


问:
How to add time to a timestamp in sqlite
I have two fields in my table : last_service_date and the next_service_date. The last_service_date has a default timestamp. What I want is to add 3 months to the next_service_date. Is that possible?

答:
You can use SQLite Date and Time Functions

Example of usage:

```<code>UPDATE tablename SET next_service_date=DATETIME(last_service_date , '+3 months');
</code>```

Body:
You can use SQLite Date and Time Functions

Example of usage:

UPDATE tablename SET next_service_date=DATETIME(last_service_date , '+3 months');


问:
how can I test text that is put in to input elements?
I have a web page that pulls some data from my database when someone types an integer into a text box. The data ends up in some text input controls. Straightforward. The selenium that fires the ajax is:

```<code><tr>
    <td>fireEvent</td>
    <td>ctl00_ContentPlaceHolder1_Wiz1_Control1_TextBox1</td>
    <td>blur</td>
</tr>
</code>```

After the blur event, there are 6 inputs on the page that now have text in them. I want to wait for the text to be present in the inputs and assert that they are present. What's an effective way to do this?

I've tried:

waitForExpression with a jquery call
($('...').val() != '' but doubtful
that this works because of the
jquery, even though jquery is loaded
on the page); also tried xpath, but that didn't work either

waitForText ( locator, pattern ), which seems like the most obvious one, but it really won't work, i suspect since the fields are inputs

Do I need a different approach here because the elements that I'm querying are input controls?

答:
Something like this I would do; This will wait for an value in all TextBoxes up to 60 seconds.. When there is a value in all of them, you check them etc and break out of the loop. Otherwise it will fail after 60 seconds.</p>

```<code>for (int second = 0;; second++) {
  if (second >= 60) fail("timeout");
  try {
    if (selenium.getValue("TextBox1") != "" && selenium.getValue("TextBox2") !="" ))
      { Your Logic here..
         break;
       }
   } catch (Exception e) {}
  Thread.sleep(1000);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a web page that pulls some data from my database when someone types an integer into a text box. The data ends up in some text input controls. Straightforward. The selenium that fires the ajax is:

    fireEvent
    ctl00_ContentPlaceHolder1_Wiz1_Control1_TextBox1
    blur

After the blur event, there are 6 inputs on the page that now have text in them. I want to wait for the text to be present in the inputs and assert that they are present. What's an effective way to do this?

I've tried:

waitForExpression with a jquery call
($('...').val() != '' but doubtful
that this works because of the
jquery, even though jquery is loaded
on the page); also tried xpath, but that didn't work either

waitForText ( locator, pattern ), which seems like the most obvious one, but it really won't work, i suspect since the fields are inputs

Do I need a different approach here because the elements that I'm querying are input controls?

Body:
Something like this I would do; This will wait for an value in all TextBoxes up to 60 seconds.. When there is a value in all of them, you check them etc and break out of the loop. Otherwise it will fail after 60 seconds.

for (int second = 0;; second++) {
  if (second >= 60) fail("timeout");
  try {
    if (selenium.getValue("TextBox1") != "" && selenium.getValue("TextBox2") !="" ))
      { Your Logic here..
         break;
       }
   } catch (Exception e) {}
  Thread.sleep(1000);
}


问:
Directly access methods from another Class
I want to be able to use a method from another class directly.

```<code>import package.dialog;

public class Class1 {
    public static void main(String[] args) {
        dialog.dialog("This is a dialog");
    }
}

import javax.swing.JOptionPane
public class dialog {
    public static void dialog(String message) {
        JOptionPane.showMessageDialog(null, message);
    }

}
</code>```

This code works excactly as it's supposed to, but as you can see I'm using dialog.dialog(). I was wondering wether there is a way to use just use dialog() directly?

答:
Firstly, your example doesn't compile because you cannot name your package "package". "package" is a Java keyword and not allowed to use as an identifier.

So we call it "mypackage". And according to Java conventions you should name classes with first letter uppercase. So I will use Dialog instead of dialog for the class name in my example below.

Then you can use a static import to call the method dialog() without prefix.

```<code>import static mypackage.Dialog.*;

public class Class1 {
  public static void main(String[] args) {
    dialog("This is dialog");
  }
}
</code>```

Body:
I want to be able to use a method from another class directly.

import package.dialog;

public class Class1 {
    public static void main(String[] args) {
        dialog.dialog("This is a dialog");
    }
}

import javax.swing.JOptionPane
public class dialog {
    public static void dialog(String message) {
        JOptionPane.showMessageDialog(null, message);
    }

}

This code works excactly as it's supposed to, but as you can see I'm using dialog.dialog(). I was wondering wether there is a way to use just use dialog() directly?

Body:
Firstly, your example doesn't compile because you cannot name your package "package". "package" is a Java keyword and not allowed to use as an identifier.

So we call it "mypackage". And according to Java conventions you should name classes with first letter uppercase. So I will use Dialog instead of dialog for the class name in my example below.

Then you can use a static import to call the method dialog() without prefix.

import static mypackage.Dialog.*;

public class Class1 {
  public static void main(String[] args) {
    dialog("This is dialog");
  }
}


问:
@HostBinding disabling class from child component Angular 4
I have an angular app which has user login and logout. I am showing up a welcome page as the home page before a user logs in. I want to enable a background image only on the welcome page. Once the user logs in, the background image must disappear. When the user logs out, he will be redirected to welcome page which must show up the background image again.

I have tried using @HostBinding in the app.component.ts by renaming the selector to 'body'.

```<code>app.component.ts

import {Component, HostBinding, Input} from '@angular/core';
import {InputMask} from "primeng/primeng";

@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  path = '../assets/img/AvayaHome.jpg';
  title = 'app';
  toggleClass = true;
  @HostBinding('class.bodyClass') isWelcomePage = this.toggleClass;
}
</code>```

Here is my CSS.

```<code>app.component.css

.bodyClass  {
    background-image: url("../assets/img/AvayaHome.jpg");
}
</code>```

Here is my index.html

```<code><!doctype html>
<html lang="en">
<head>
 <title> Something </title>
</head>
<body class="bodyClass">

    <app-welcome-page></app-welcome-page>

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

I am enabling the css style for bodyClass by assigning toggleClass as true. Once the user logs in, I am changing the value of toggleClass (which is in the app.component.ts) from the child component.

Here is my login.component.ts

```<code>onLogin() {
    console.log('onLogin() invoked:', this._email, ':' , this.password);
    if (this._email == null || this.password == null) {
      this.errorMessage = 'All fields are required';
      return;
    }
    this.errorMessage = null;
    this.loginservice.authenticate(this._email, this.password);
    this.appComponent.toggleClass = true;
    this.router.navigate(['/dashboard']);
  }
</code>```

The value of the toggleClass changes when the user logs in to FALSE. But I am still seeing the background image. Not sure what I am doing wrong. Any help will be appreciated.

答:
If you want to dynamically display and hide a background you should use a conditional class with ngClass

You can read more about it here NgClass

In your case it would be

```<code><div [ngClass]="{'bodyClass': isWelcomePage}">
    ...
</div>
</code>```

Then bodyClass css class will only apply IF isWelcomePage is true, if it's false it won't apply and the image won't show.

Edit:

As requested, a working example: Plunkr

Body:
I have an angular app which has user login and logout. I am showing up a welcome page as the home page before a user logs in. I want to enable a background image only on the welcome page. Once the user logs in, the background image must disappear. When the user logs out, he will be redirected to welcome page which must show up the background image again.

I have tried using @HostBinding in the app.component.ts by renaming the selector to 'body'.

app.component.ts

import {Component, HostBinding, Input} from '@angular/core';
import {InputMask} from "primeng/primeng";

@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  path = '../assets/img/AvayaHome.jpg';
  title = 'app';
  toggleClass = true;
  @HostBinding('class.bodyClass') isWelcomePage = this.toggleClass;
}

Here is my CSS.

app.component.css

.bodyClass  {
    background-image: url("../assets/img/AvayaHome.jpg");
}

Here is my index.html

<!doctype html>

 <title> Something </title>

    <app-welcome-page></app-welcome-page>

I am enabling the css style for bodyClass by assigning toggleClass as true. Once the user logs in, I am changing the value of toggleClass (which is in the app.component.ts) from the child component.

Here is my login.component.ts

onLogin() {
    console.log('onLogin() invoked:', this._email, ':' , this.password);
    if (this._email == null || this.password == null) {
      this.errorMessage = 'All fields are required';
      return;
    }
    this.errorMessage = null;
    this.loginservice.authenticate(this._email, this.password);
    this.appComponent.toggleClass = true;
    this.router.navigate(['/dashboard']);
  }

The value of the toggleClass changes when the user logs in to FALSE. But I am still seeing the background image. Not sure what I am doing wrong. Any help will be appreciated.

Body:
If you want to dynamically display and hide a background you should use a conditional class with ngClass

You can read more about it here NgClass

In your case it would be

<div [ngClass]="{'bodyClass': isWelcomePage}">
    ...
</div>

Then bodyClass css class will only apply IF isWelcomePage is true, if it's false it won't apply and the image won't show.

Edit:

As requested, a working example: Plunkr


问:
How to draw a virtual framebuffer in Swing?
Suppose I have an array fb that is large enough to hold each 32-bit color pixel for a 128x128 display. It's laid out like a framebuffer would be.

How can I efficiently draw this on the display?

My current method loops over every pixel but that seems rather slow and cumbersome. Is there no way to convert this to an Image?

EDIT: I want to do this using the Java Swing APIs. I do not want any platform-specific code. However, if there is a library that uses the Swing APIs, that is fine.

答:
My current method loops over every pixel but that seems rather slow and cumbersome. Is there no way to convert this to an Image?

You can paint it onto a BufferedImage.

Then you can use the BufferedImage to create an ImageIcon and use the Icon to create a JLabel and add the label to your GUI.

Edit:

I want to convert the int array to a BufferedImage

How about the setRGB(...) method of the BufferedImage?


问:
String Array for with n elements
I want to make a array of strings, like this one, numel(A) = 4:

A = ['a' 'a' 'a' 'a']

A = aaaa

For I could make easy changes in like this:

A(2) = 't'

A = ataa

But, I want to make something like this for an array size n.

答:
There isn't much of a question here.  But if you are just asking how to make a 1xN array of the char 'a'.  Then it is just this:</p>

```<code>N = 10;
A(1:N) = 'a'
</code>```

Title: String Array for with n elements

Body:
There isn't much of a question here.  But if you are just asking how to make a 1xN array of the char 'a'.  Then it is just this:

N = 10;
A(1:N) = 'a'


问:
how to get full servername and port running in mvc 2 by codebehind
hi every body i have a question

example if i have url : http://localhost:8512/bookuser/Create

how to get "http://localhost:8512" by code behind in mvc2 ??

thanks regard

答:
Look for the first "/" after the "http://" - here's a piece of code:</p>

```<code>public class SName {

    private String  absUrlStr;

    private final static String slash = "/", htMarker = "http://";

    public SName (String s) throws Exception {
            if (s.startsWith (htMarker)) {
                    int slIndex = s.substring(htMarker.length()).indexOf(slash);
                    absUrlStr = (slIndex < 0) ? s : s.substring (0, slIndex + htMarker.length());
            } else {
                    throw new Exception ("[SName] Invalid URL: " + s);
    }}

    public String toString () {
            return "[SName:" + absUrlStr + "]";
    }

    public static void main (String[] args) {
            try {
                    System.out.println (new SName ("http://localhost:8512/bookuser/Create"));
            } catch (Exception ex) {
                    ex.printStackTrace();
}}}
</code>```

Body:
Look for the first "/" after the "http://" - here's a piece of code:

public class SName {

    private String  absUrlStr;

    private final static String slash = "/", htMarker = "http://";

    public SName (String s) throws Exception {
            if (s.startsWith (htMarker)) {
                    int slIndex = s.substring(htMarker.length()).indexOf(slash);
                    absUrlStr = (slIndex < 0) ? s : s.substring (0, slIndex + htMarker.length());
            } else {
                    throw new Exception ("[SName] Invalid URL: " + s);
    }}

    public String toString () {
            return "[SName:" + absUrlStr + "]";
    }

    public static void main (String[] args) {
            try {
                    System.out.println (new SName ("http://localhost:8512/bookuser/Create"));
            } catch (Exception ex) {
                    ex.printStackTrace();
}}}


问:
How to get reference to clarity datagrid from typescript
This might be more of an angular question, but I'm trying to resize the clarity datagrid after loading data (and dynamically showing/hiding columns) but I keep getting the error

Uncaught TypeError: Cannot read property 'resize' of undefined

component.html

```<code><clr-datagrid #contactsGrid>
[...]
</clr-datagrid>
</code>```

component.ts

```<code>import { Component, OnInit, ViewChild } from '@angular/core';
import { Datagrid } from "clarity-angular";

export class GridComponent implements OnInit {
    @ViewChild('contactsGrid') datagrid: Datagrid;
    //@ViewChild('Datagrid') datagrid: Datagrid; //This doesn't work either

    constructor( ) { }

    ngOnInit() {
        [...]
        this.datagrid.resize(); //this.datagrid is undefined
    }
}
</code>```

答:
It appears your sample code above is correct, perhaps there is more going on? Do you have a more complete example to share that demonstrates the actual issue live?

You can see a demo here of getting the reference for a datagrid. https://stackblitz.com/edit/clarity-datagrid-brfwx9?file=app/launches/launches.component.ts

The template has:

```<code><clr-datagrid [(clrDgSelected)]="selected" #datagridRef>
</code>```

Then the controller has:

```<code>export class LaunchesComponent  {
  @ViewChild('datagridRef') datagrid: Datagrid;

  ngOnInit() {
    console.log(this.datagrid); // Defined
  }
</code>```

If you only have one Datagrid, you don't need to add a hook in the HTML

```<code>export class LaunchesComponent  {
  @ViewChild(Datagrid) datagrid: Datagrid;

  ngOnInit() {
    console.log(this.datagrid); // Defined
  }
</code>```

It looks like your code was passing 'Datagrid' (a string) instead of Datagrid(a reference to the constructor)

Body:
This might be more of an angular question, but I'm trying to resize the clarity datagrid after loading data (and dynamically showing/hiding columns) but I keep getting the error

Uncaught TypeError: Cannot read property 'resize' of undefined

component.html

<clr-datagrid #contactsGrid>
[...]
</clr-datagrid>

component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { Datagrid } from "clarity-angular";

export class GridComponent implements OnInit {
    @ViewChild('contactsGrid') datagrid: Datagrid;
    //@ViewChild('Datagrid') datagrid: Datagrid; //This doesn't work either

    constructor( ) { }

    ngOnInit() {
        [...]
        this.datagrid.resize(); //this.datagrid is undefined
    }
}

Body:
It appears your sample code above is correct, perhaps there is more going on? Do you have a more complete example to share that demonstrates the actual issue live?

You can see a demo here of getting the reference for a datagrid. https://stackblitz.com/edit/clarity-datagrid-brfwx9?file=app/launches/launches.component.ts

The template has:

<clr-datagrid [(clrDgSelected)]="selected" #datagridRef>

Then the controller has:

export class LaunchesComponent  {
  @ViewChild('datagridRef') datagrid: Datagrid;

  ngOnInit() {
    console.log(this.datagrid); // Defined
  }

If you only have one Datagrid, you don't need to add a hook in the HTML

export class LaunchesComponent  {
  @ViewChild(Datagrid) datagrid: Datagrid;

  ngOnInit() {
    console.log(this.datagrid); // Defined
  }

It looks like your code was passing 'Datagrid' (a string) instead of Datagrid(a reference to the constructor)


问:
d3plus: how to flip order of drawn boxplots?
I am using this code for a d3 viz (Box Plot and Whiskers):

```<code>var ODGCostsChart = d3plus.viz()
    .container("#my_viz")
    .data(dataNoMinMax)
    .type("box")
    .id("measure")
    .x("provider")
    .y("deviation")
    .draw();
</code>```

where each row of my data is either:

```<code>{deviation: round(d.value,2), provider: 'This', measure: d.metric}
</code>```

or:

```<code>{deviation: round(d.value_others,2), provider: 'All', measure: d.metric}
</code>```

I would like the resulting visualization to have two boxplots side-by-side, one for "This" provider, and another for "All" providers right next to it. No matter how I try, though, I keep getting the boxplots with "All" preceding "This":

For the life of me I don't know how to flip the order of the boxplots in the drawing. I have gone through the documentation but I am not sure whether it's even possible.

答:
Have you tried to use the order function on your viz like bellow ?

```<code>var ODGCostsChart = d3plus.viz()
    .container("#my_viz")
    .data(dataNoMinMax)
    .order({sort: 'asc' }) // or {sort: 'desc'}
    .type("box")
    .id("measure")
    .x("provider")
    .y("deviation")
    .draw();
</code>```

You can see other options for this order function here

Body:
I am using this code for a d3 viz (Box Plot and Whiskers):

var ODGCostsChart = d3plus.viz()
    .container("#my_viz")
    .data(dataNoMinMax)
    .type("box")
    .id("measure")
    .x("provider")
    .y("deviation")
    .draw();

where each row of my data is either:

{deviation: round(d.value,2), provider: 'This', measure: d.metric}

or:

{deviation: round(d.value_others,2), provider: 'All', measure: d.metric}

I would like the resulting visualization to have two boxplots side-by-side, one for "This" provider, and another for "All" providers right next to it. No matter how I try, though, I keep getting the boxplots with "All" preceding "This":

For the life of me I don't know how to flip the order of the boxplots in the drawing. I have gone through the documentation but I am not sure whether it's even possible.

Body:
Have you tried to use the order function on your viz like bellow ?

var ODGCostsChart = d3plus.viz()
    .container("#my_viz")
    .data(dataNoMinMax)
    .order({sort: 'asc' }) // or {sort: 'desc'}
    .type("box")
    .id("measure")
    .x("provider")
    .y("deviation")
    .draw();

You can see other options for this order function here


问:
String Benchmarks in C# - Refactoring for Speed/Maintainability
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

```<code>private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }
</code>```

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```

However, it changes drastically over the longhaul:

With 10,000 Iterations:

```
MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks
```

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

```
MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486
```

Here's the code after Refactor #1:

```<code>private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }
</code>```

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

```<code>static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }
</code>```

This results in the following Benchmark:

```
MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder
```

Changing the for loop to a foreach loop resulted in the following benchmark result:

```<code>static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }
</code>```

```
RefactoredForEachMakeNiceString    Took:  45163 Ticks
```

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

```<code>static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }
</code>```

Final Benchmark Results:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```0

Or, if you prefer milliseconds:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```1

So the percentage gains are:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```2

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

```<code>       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }
</code>```

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

答:
You might want to try instantiating a Regex object as a class member and using the RegexOptions.Compiled option when you create it.

Currently, you're using the static Split member of Regex, and that doesn't cache the regular expression. Using an instanced member object instead of the static method should improve your performance even more (over the long run).

OwnerDisplayName: Gortok

Body:
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks

However, it changes drastically over the longhaul:

With 10,000 Iterations:

MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486

Here's the code after Refactor #1:

private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }

This results in the following Benchmark:

MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder

Changing the for loop to a foreach loop resulted in the following benchmark result:

static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }

RefactoredForEachMakeNiceString    Took:  45163 Ticks

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }

Final Benchmark Results:

MakeNiceString Took                   139363 Ticks
SplitCamelCase Took                   489174 Ticks
ImprovedMakeNiceString Took           115478 Ticks
RefactoredMakeNiceString Took          38819 Ticks
RefactoredForEachMakeNiceString Took   44700 Ticks
CompiledRegex Took                    227021 Ticks

Or, if you prefer milliseconds:

MakeNiceString Took                  38 ms
SplitCamelCase Took                 123 ms
ImprovedMakeNiceString Took          33 ms
RefactoredMakeNiceString Took        11 ms
RefactoredForEachMakeNiceString Took 12 ms
CompiledRegex Took                   63 ms

So the percentage gains are:

MakeNiceString                   38 ms   Baseline
SplitCamelCase                  123 ms   223% slower
ImprovedMakeNiceString           33 ms   13.15% faster
RefactoredMakeNiceString         11 ms   71.05% faster
RefactoredForEachMakeNiceString  12 ms   68.42% faster
CompiledRegex                    63 ms   65.79% slower

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

LastEditorDisplayName: Gortok

OwnerDisplayName: Andrew Rollings


问:
Reading specific section of App.config
I'm trying to get the values from the oracle.manageddataaccess.client section in my App.config file. This section looks like this:

```<code><oracle.manageddataaccess.client>
    <version number="*">
        <dataSources>
            <dataSource alias="alias1" descriptor="connection string 1" />
            <dataSource alias="alias2" descriptor="connection string 2" />
        </dataSources>
    </version>
</oracle.manageddataaccess.client>
</code>```

I've tried using the ConfigurationManager API to read the values, but I haven't had any luck.

With:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings["oracle.manageddataaccess.client"]

just returns an empty string.

config.Sections seems to only work for tags that are explicitly a section tag.

I just need to be able to read the dataSource values in this section.

Update:
config.Sections["oracle.manageddataaccess.client"].SectionInformation returns information about the section, and the GetRawXml() is getting closer to what I want, but I'm trying to get a specific subset of this.

答:
I didn't find exactly what I was looking for, but I found a way around it.
If anyone else has the same issue, you can use XDocument and Linq to filter for what you need. You need to include your using statements: System.Linq and System.Xml.Linq

```<code>XDocument doc = XDocument.Parse(config.Sections["oracle.manageddataaccess.client"].SectionInformation.GetRawXml());
var value = from node in doc.Descendants("dataSource")
            where node.Attribute("alias").Value == whatever
            select node.Attribute("descriptor").Value;
</code>```

Title: Reading specific section of App.config

Body:
I'm trying to get the values from the oracle.manageddataaccess.client section in my App.config file. This section looks like this:

<oracle.manageddataaccess.client>
    <version number="*">
        <dataSources>
            <dataSource alias="alias1" descriptor="connection string 1" />
            <dataSource alias="alias2" descriptor="connection string 2" />
        </dataSources>
    </version>
</oracle.manageddataaccess.client>

I've tried using the ConfigurationManager API to read the values, but I haven't had any luck.

With:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings["oracle.manageddataaccess.client"]

just returns an empty string.

config.Sections seems to only work for tags that are explicitly a section tag.

I just need to be able to read the dataSource values in this section.

Update:
config.Sections["oracle.manageddataaccess.client"].SectionInformation returns information about the section, and the GetRawXml() is getting closer to what I want, but I'm trying to get a specific subset of this.

Body:
I didn't find exactly what I was looking for, but I found a way around it.
If anyone else has the same issue, you can use XDocument and Linq to filter for what you need. You need to include your using statements: System.Linq and System.Xml.Linq

XDocument doc = XDocument.Parse(config.Sections["oracle.manageddataaccess.client"].SectionInformation.GetRawXml());
var value = from node in doc.Descendants("dataSource")
            where node.Attribute("alias").Value == whatever
            select node.Attribute("descriptor").Value;


问:
Calling a function on ng-click while not submitting a form with ng-submit
Consider my (simplified) form:

```<code><form ng-submit="save()">
    ...
    <button type="submit">Save</button>
    <button ng-click="cancel()">Cancel</button>
</form>
</code>```

After pressing "Save", it calls ng-submit on my form, whereas after pressing "Cancel", it calls a separate function (that re-directs me to another page)

The problem is that after pressing "Cancel" it also calls a function on ng-submit. I want it to just call its own function on ng-click. How can I solve this?

An obvious solution:

```<code><form>
    ...
    <button ng-click="save()">Save</button>
    <button ng-click="cancel()">Cancel</button>
</form>
</code>```

But I want an ability to submit the form by pressing Enter, which is why ng-submit was used.

答:
Just add type="button" for cancel button
so it is

<button type="button" ng-click="cancel()">Cancel</button>

or use  tag instead, like:

Cancel

Body:
Consider my (simplified) form:

<form ng-submit="save()">
    ...
    <button type="submit">Save</button>
    <button ng-click="cancel()">Cancel</button>
</form>

After pressing "Save", it calls ng-submit on my form, whereas after pressing "Cancel", it calls a separate function (that re-directs me to another page)

The problem is that after pressing "Cancel" it also calls a function on ng-submit. I want it to just call its own function on ng-click. How can I solve this?

An obvious solution:

<form>
    ...
    <button ng-click="save()">Save</button>
    <button ng-click="cancel()">Cancel</button>
</form>

But I want an ability to submit the form by pressing Enter, which is why ng-submit was used.

Body:
Just add type="button" for cancel button
so it is

<button type="button" ng-click="cancel()">Cancel</button>

or use <a> tag instead, like:

<a ng-click="$event.preventDefault(); cancel()">Cancel</a>


问:
How to Convert IPv4 Addresses to/from Long in Scala
I was looking for a basic utility with 2 functions to convert IPv4 Addresses to/from Long in Scala, such as "10.10.10.10" to its Long representation of 168430090 and back. A basic utility such as this exists in many languages (such as python), but appears to require re-writing the same code for everyone for the JVM.

What is the recommended approach on unifying IPv4ToLong and LongToIPv4 functions?

答:
Try the ipaddr scala library. Create an IpAddress and get its long value like this:</p>

```<code>val ip1: IpAddress = IpAddress("192.168.0.1")
val ip1Long = ip1.numerical // returns 3232235521L
</code>```

Body:
Try the ipaddr scala library. Create an IpAddress and get its long value like this:

val ip1: IpAddress = IpAddress("192.168.0.1")
val ip1Long = ip1.numerical // returns 3232235521L

ContentLicense: CC BY-SA 4.0


问:
TypeError: msg.trim is not a function in Ionic project
I am trying to start my first Ionic project following theses steps : Ionic framework get started page

But when I am writing in the terminal ionic serve (step 3) I have got this error message even if I run the Development server at http://localhost:8100 (my app is running but I still got this error message):

```<code>TypeError: msg.trim is not a function
at Logger.log (/usr/local/lib/node_modules/ionic/node_modules/@ionic/cli-utils/lib/utils/logger.js:78:21)
at Logger.error (/usr/local/lib/node_modules/ionic/node_modules/@ionic/cli-utils/lib/utils/logger.js:35:14)
at Object.<anonymous> (/usr/local/lib/node_modules/ionic/dist/index.js:261:22)
at throw (native)
at rejected (/usr/local/lib/node_modules/ionic/node_modules/tslib/tslib.js:94:69)
</code>```

Also during the setup when I write the command sudo ionic start myApp tabs I have got this : Running command - failed! [ERROR] An error occurred while running npm install (exit code 1):

Complete Error message in the the terminal (I am on macOS) is:

```<code>    npm WARN deprecated babili@0.1.2: babili has been renamed to
    babel-minify. Please update to babel-minify
    npm WARN deprecated babel-preset-babili@0.1.4: babili has been renamed
    to babel-minify. Please update to babel-preset-minify
    npm WARN deprecated object-keys@0.2.0: Please update to the latest
    object-keys

    > fsevents@1.1.2 install
    /Users/emilio/TestIonic/myApp/node_modules/fsevents
    > node install

    [fsevents] Success:
    "/Users/emilio/TestIonic/myApp/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x64/fse.node"
    already installed
    Pass --update-binary to reinstall or --build-from-source to recompile

    > node-sass@4.5.3 install
    /Users/emilio/TestIonic/myApp/node_modules/node-sass
    > node scripts/install.js

    Unable to save binary
    /Users/emilio/TestIonic/myApp/node_modules/node-sass/vendor/darwin-x64-48
    : { Error: EACCES: permission denied, mkdir
    '/Users/emilio/TestIonic/myApp/node_modules/node-sass/vendor'
         at Error (native)
         at Object.fs.mkdirSync (fs.js:924:18)
         at sync
    (/Users/emilio/TestIonic/myApp/node_modules/mkdirp/index.js:71:13)
         at Function.sync
    (/Users/emilio/TestIonic/myApp/node_modules/mkdirp/index.js:77:24)
         at checkAndDownloadBinary
    (/Users/emilio/TestIonic/myApp/node_modules/node-sass/scripts/install.js:111:11)
         at Object.<anonymous>
    (/Users/emilio/TestIonic/myApp/node_modules/node-sass/scripts/install.js:154:1)
         at Module._compile (module.js:570:32)
         at Object.Module._extensions..js (module.js:579:10)
         at Module.load (module.js:487:32)
         at tryModuleLoad (module.js:446:12)
       errno: -13,
       code: 'EACCES',
       syscall: 'mkdir',
       path: '/Users/emilio/TestIonic/myApp/node_modules/node-sass/vendor' }

    > uglifyjs-webpack-plugin@0.4.6 postinstall
    /Users/emilio/TestIonic/myApp/node_modules/uglifyjs-webpack-plugin
    > node lib/post_install.js

    > node-sass@4.5.3 postinstall
    /Users/emilio/TestIonic/myApp/node_modules/node-sass
    > node scripts/build.js

    Building: /usr/local/bin/node
    /Users/emilio/TestIonic/myApp/node_modules/node-gyp/bin/node-gyp.js
    rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags=
    --libsass_library=
    gyp info it worked if it ends with ok
    gyp verb cli [ '/usr/local/bin/node',
    gyp verb cli
    '/Users/emilio/TestIonic/myApp/node_modules/node-gyp/bin/node-gyp.js',
    gyp verb cli   'rebuild',
    gyp verb cli   '--verbose',
    gyp verb cli   '--libsass_ext=',
    gyp verb cli   '--libsass_cflags=',
    gyp verb cli   '--libsass_ldflags=',
    gyp verb cli   '--libsass_library=' ]
    gyp info using node-gyp@3.6.2
    gyp info using node@6.11.3 | darwin | x64
    gyp verb command rebuild []
    gyp verb command clean []
    gyp verb clean removing "build" directory
    gyp verb command configure []
    gyp verb check python checking for Python executable "python2" in the
    PATH
    gyp verb `which` failed Error: not found: python2
    gyp verb `which` failed     at getNotFoundError
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:13:12)
    gyp verb `which` failed     at F
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:68:19)
    gyp verb `which` failed     at E
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:80:29)
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/which/which.js:89:16
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/isexe/index.js:42:5
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/isexe/mode.js:8:5
    gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:123:15)
    gyp verb `which` failed  python2 { Error: not found: python2
    gyp verb `which` failed     at getNotFoundError
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:13:12)
    gyp verb `which` failed     at F
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:68:19)
    gyp verb `which` failed     at E
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:80:29)
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/which/which.js:89:16
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/isexe/index.js:42:5
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/isexe/mode.js:8:5
    gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:123:15)
    gyp verb `which` failed   stack: 'Error: not found: python2\n    at
    getNotFoundError
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:13:12)\n
    at F (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:68:19)\n
       at E
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:80:29)\n
    at /Users/emilio/TestIonic/myApp/node_modules/which/which.js:89:16\n
    at /Users/emilio/TestIonic/myApp/node_modules/isexe/index.js:42:5\n
    at /Users/emilio/TestIonic/myApp/node_modules/isexe/mode.js:8:5\n    at
    FSReqWrap.oncomplete (fs.js:123:15)',
    gyp verb `which` failed   code: 'ENOENT' }
    gyp verb check python checking for Python executable "python" in the
    PATH
    gyp verb `which` succeeded python /usr/bin/python
    gyp verb check python version `/usr/bin/python -c "import platform;
    print(platform.python_version());"` returned: "2.7.10\n"
    gyp verb get node dir no --target version specified, falling back to
    host node version: 6.11.3
    gyp verb command install [ '6.11.3' ]
    gyp verb install input version string "6.11.3"
    gyp verb install installing version: 6.11.3
    gyp verb install --ensure was passed, so won't reinstall if already
    installed
    gyp verb install version is already installed, need to check
    "installVersion"
    gyp verb got "installVersion" 9
    gyp verb needs "installVersion" 9
    gyp verb install version is good
    gyp verb get node dir target node version installed: 6.11.3
    gyp verb build dir attempting to create "build" dir:
    /Users/emilio/TestIonic/myApp/node_modules/node-sass/build
    gyp ERR! configure error
    gyp ERR! stack Error: EACCES: permission denied, mkdir
    '/Users/emilio/TestIonic/myApp/node_modules/node-sass/build'
    gyp ERR! stack     at Error (native)
    gyp ERR! System Darwin 16.7.0
    gyp ERR! command "/usr/local/bin/node"
    "/Users/emilio/TestIonic/myApp/node_modules/node-gyp/bin/node-gyp.js"
    "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags="
    "--libsass_ldflags=" "--libsass_library="
    gyp ERR! cwd /Users/emilio/TestIonic/myApp/node_modules/node-sass
    gyp ERR! node -v v6.11.3
    gyp ERR! node-gyp -v v3.6.2
    gyp ERR! not ok
    Build failed with error code: 1
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! node-sass@4.5.3 postinstall: `node scripts/build.js`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the node-sass@4.5.3 postinstall script.
    npm ERR! This is probably not a problem with npm. There is likely
    additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR!     /Users/emilio/.npm/_logs/2017-09-25T08_05_30_711Z-debug.log
</code>```

Thanks in advance

答:
Try this it worked for me. Having Ionic Pro helps as well</p>

```<code>npm install ionic-angular@latest --save
npm install @ionic/app-scripts@latest --save-dev
</code>```

Body:
I am trying to start my first Ionic project following theses steps : Ionic framework get started page

But when I am writing in the terminal ionic serve (step 3) I have got this error message even if I run the Development server at http://localhost:8100 (my app is running but I still got this error message):

TypeError: msg.trim is not a function
at Logger.log (/usr/local/lib/node_modules/ionic/node_modules/@ionic/cli-utils/lib/utils/logger.js:78:21)
at Logger.error (/usr/local/lib/node_modules/ionic/node_modules/@ionic/cli-utils/lib/utils/logger.js:35:14)
at Object.<anonymous> (/usr/local/lib/node_modules/ionic/dist/index.js:261:22)
at throw (native)
at rejected (/usr/local/lib/node_modules/ionic/node_modules/tslib/tslib.js:94:69)

Also during the setup when I write the command sudo ionic start myApp tabs I have got this : Running command - failed! [ERROR] An error occurred while running npm install (exit code 1):

Complete Error message in the the terminal (I am on macOS) is:

    npm WARN deprecated babili@0.1.2: babili has been renamed to
    babel-minify. Please update to babel-minify
    npm WARN deprecated babel-preset-babili@0.1.4: babili has been renamed
    to babel-minify. Please update to babel-preset-minify
    npm WARN deprecated object-keys@0.2.0: Please update to the latest
    object-keys

    > fsevents@1.1.2 install
    /Users/emilio/TestIonic/myApp/node_modules/fsevents
    > node install

    [fsevents] Success:
    "/Users/emilio/TestIonic/myApp/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x64/fse.node"
    already installed
    Pass --update-binary to reinstall or --build-from-source to recompile

    > node-sass@4.5.3 install
    /Users/emilio/TestIonic/myApp/node_modules/node-sass
    > node scripts/install.js

    Unable to save binary
    /Users/emilio/TestIonic/myApp/node_modules/node-sass/vendor/darwin-x64-48
    : { Error: EACCES: permission denied, mkdir
    '/Users/emilio/TestIonic/myApp/node_modules/node-sass/vendor'
         at Error (native)
         at Object.fs.mkdirSync (fs.js:924:18)
         at sync
    (/Users/emilio/TestIonic/myApp/node_modules/mkdirp/index.js:71:13)
         at Function.sync
    (/Users/emilio/TestIonic/myApp/node_modules/mkdirp/index.js:77:24)
         at checkAndDownloadBinary
    (/Users/emilio/TestIonic/myApp/node_modules/node-sass/scripts/install.js:111:11)
         at Object.<anonymous>
    (/Users/emilio/TestIonic/myApp/node_modules/node-sass/scripts/install.js:154:1)
         at Module._compile (module.js:570:32)
         at Object.Module._extensions..js (module.js:579:10)
         at Module.load (module.js:487:32)
         at tryModuleLoad (module.js:446:12)
       errno: -13,
       code: 'EACCES',
       syscall: 'mkdir',
       path: '/Users/emilio/TestIonic/myApp/node_modules/node-sass/vendor' }

    > uglifyjs-webpack-plugin@0.4.6 postinstall
    /Users/emilio/TestIonic/myApp/node_modules/uglifyjs-webpack-plugin
    > node lib/post_install.js

    > node-sass@4.5.3 postinstall
    /Users/emilio/TestIonic/myApp/node_modules/node-sass
    > node scripts/build.js

    Building: /usr/local/bin/node
    /Users/emilio/TestIonic/myApp/node_modules/node-gyp/bin/node-gyp.js
    rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags=
    --libsass_library=
    gyp info it worked if it ends with ok
    gyp verb cli [ '/usr/local/bin/node',
    gyp verb cli
    '/Users/emilio/TestIonic/myApp/node_modules/node-gyp/bin/node-gyp.js',
    gyp verb cli   'rebuild',
    gyp verb cli   '--verbose',
    gyp verb cli   '--libsass_ext=',
    gyp verb cli   '--libsass_cflags=',
    gyp verb cli   '--libsass_ldflags=',
    gyp verb cli   '--libsass_library=' ]
    gyp info using node-gyp@3.6.2
    gyp info using node@6.11.3 | darwin | x64
    gyp verb command rebuild []
    gyp verb command clean []
    gyp verb clean removing "build" directory
    gyp verb command configure []
    gyp verb check python checking for Python executable "python2" in the
    PATH
    gyp verb `which` failed Error: not found: python2
    gyp verb `which` failed     at getNotFoundError
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:13:12)
    gyp verb `which` failed     at F
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:68:19)
    gyp verb `which` failed     at E
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:80:29)
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/which/which.js:89:16
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/isexe/index.js:42:5
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/isexe/mode.js:8:5
    gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:123:15)
    gyp verb `which` failed  python2 { Error: not found: python2
    gyp verb `which` failed     at getNotFoundError
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:13:12)
    gyp verb `which` failed     at F
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:68:19)
    gyp verb `which` failed     at E
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:80:29)
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/which/which.js:89:16
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/isexe/index.js:42:5
    gyp verb `which` failed     at
    /Users/emilio/TestIonic/myApp/node_modules/isexe/mode.js:8:5
    gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:123:15)
    gyp verb `which` failed   stack: 'Error: not found: python2\n    at
    getNotFoundError
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:13:12)\n
    at F (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:68:19)\n
       at E
    (/Users/emilio/TestIonic/myApp/node_modules/which/which.js:80:29)\n
    at /Users/emilio/TestIonic/myApp/node_modules/which/which.js:89:16\n
    at /Users/emilio/TestIonic/myApp/node_modules/isexe/index.js:42:5\n
    at /Users/emilio/TestIonic/myApp/node_modules/isexe/mode.js:8:5\n    at
    FSReqWrap.oncomplete (fs.js:123:15)',
    gyp verb `which` failed   code: 'ENOENT' }
    gyp verb check python checking for Python executable "python" in the
    PATH
    gyp verb `which` succeeded python /usr/bin/python
    gyp verb check python version `/usr/bin/python -c "import platform;
    print(platform.python_version());"` returned: "2.7.10\n"
    gyp verb get node dir no --target version specified, falling back to
    host node version: 6.11.3
    gyp verb command install [ '6.11.3' ]
    gyp verb install input version string "6.11.3"
    gyp verb install installing version: 6.11.3
    gyp verb install --ensure was passed, so won't reinstall if already
    installed
    gyp verb install version is already installed, need to check
    "installVersion"
    gyp verb got "installVersion" 9
    gyp verb needs "installVersion" 9
    gyp verb install version is good
    gyp verb get node dir target node version installed: 6.11.3
    gyp verb build dir attempting to create "build" dir:
    /Users/emilio/TestIonic/myApp/node_modules/node-sass/build
    gyp ERR! configure error
    gyp ERR! stack Error: EACCES: permission denied, mkdir
    '/Users/emilio/TestIonic/myApp/node_modules/node-sass/build'
    gyp ERR! stack     at Error (native)
    gyp ERR! System Darwin 16.7.0
    gyp ERR! command "/usr/local/bin/node"
    "/Users/emilio/TestIonic/myApp/node_modules/node-gyp/bin/node-gyp.js"
    "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags="
    "--libsass_ldflags=" "--libsass_library="
    gyp ERR! cwd /Users/emilio/TestIonic/myApp/node_modules/node-sass
    gyp ERR! node -v v6.11.3
    gyp ERR! node-gyp -v v3.6.2
    gyp ERR! not ok
    Build failed with error code: 1
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! node-sass@4.5.3 postinstall: `node scripts/build.js`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the node-sass@4.5.3 postinstall script.
    npm ERR! This is probably not a problem with npm. There is likely
    additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR!     /Users/emilio/.npm/_logs/2017-09-25T08_05_30_711Z-debug.log

Thanks in advance

Body:
Try this it worked for me. Having Ionic Pro helps as well

npm install ionic-angular@latest --save
npm install @ionic/app-scripts@latest --save-dev


问:
Consistent application of filters to embedded documents
I am new in mongodb/

I need to get a document using mongo shell if its first emdedded document, which matches condition A, mathes codition B.

For examle, I have only one doc in collection:

```<code>{
"_id": "life",
"docs": [{
    "_id": "sex",
    "p": 2,
    "c": 2
}, {
    "_id": "drugs",
    "p": 1,
    "c ": 2
}, {
    "_id": "rock'n'roll",
    "p": 1,
    "c": 4
}]
</code>```

}

If A condition is p=1, then

---- if B condition is с=2, I get "life" (embedded doc "drugs" matches the condtitions)

---- if B condition is c=4, I get empty result.

If A condition is c=2, then

---- if B condition is p=2, I get "life" (emdedded doc "sex" matches the conditions)

---- if B condition is p=1, I get empty result (

Tnx

Added:

The task is to filter the collection and get whole documents according to condtitions applied to emdedded document in specific way, so the question is not a duplicate I think.

But with help of that question I got the solution:

```<code>db.test.aggregation([
{
    $project:
    {
        docs:
        {
            $filter:
            {
                input:"$docs",
                as:"doc",
                cond:{$eq:['$$doc.p',1]}
            }
        }
    }
},
{
    $project:
    {
        docs:{$slice:["$docs",1]}
    }
},
{
    $project:
    {
        docs:
        {
            $filter:
            {
                input:"$docs",
                as:"doc",
                cond:{$eq:['$$doc.c',2]}
            }
        }
    }
},
{
    $project:
    {
        "docs":1,
        "n":{"$size":"$docs"}
    }
},
{
    $match:{"n":{$gt:0}}
}])
</code>```

Another solution:

```<code>db.c.aggregate([
{
    $project:
    {
        docs:
        {
            $filter:
            {
                input:"$docs",
                as:"doc",
                cond:{$eq:['$$doc.p',1]}
            }
        }
    },
},
{
    "$unwind":"$docs"
},
{
    "$group":
    {
        "_id": "$_id",
        "doc": { "$first": "$docs" }
    }
},
{
    $match:{"doc.c":2}
}])
</code>```

答:
So you mean you want to extract the values from an array and present it in a "flat" structure?

If this is what you mean you'd need something like this:

```<code>db.collectionName.aggregate([
{
  $match: {
    "docs.p": 1,
    "docs.c": 2
  }
},
{ $unwind: "$docs"},
{
  $match: {
    "docs.p": 1,
    "docs.c": 2
  }
}
])
</code>```

So basically I would $match twice. In the first one you match all documents that contain these values. Then you $unwind to "flatten" your array structure. And last step I'd use $match again to only take the set that you actually need.

Body:
I am new in mongodb/

I need to get a document using mongo shell if its first emdedded document, which matches condition A, mathes codition B.

For examle, I have only one doc in collection:

{
"_id": "life",
"docs": [{
    "_id": "sex",
    "p": 2,
    "c": 2
}, {
    "_id": "drugs",
    "p": 1,
    "c ": 2
}, {
    "_id": "rock'n'roll",
    "p": 1,
    "c": 4
}]

}

If A condition is p=1, then

---- if B condition is с=2, I get "life" (embedded doc "drugs" matches the condtitions)

---- if B condition is c=4, I get empty result.

If A condition is c=2, then

---- if B condition is p=2, I get "life" (emdedded doc "sex" matches the conditions)

---- if B condition is p=1, I get empty result (

Tnx

Added:

The task is to filter the collection and get whole documents according to condtitions applied to emdedded document in specific way, so the question is not a duplicate I think.

But with help of that question I got the solution:

db.test.aggregation([
{
    $project:
    {
        docs:
        {
            $filter:
            {
                input:"$docs",
                as:"doc",
                cond:{$eq:['$$doc.p',1]}
            }
        }
    }
},
{
    $project:
    {
        docs:{$slice:["$docs",1]}
    }
},
{
    $project:
    {
        docs:
        {
            $filter:
            {
                input:"$docs",
                as:"doc",
                cond:{$eq:['$$doc.c',2]}
            }
        }
    }
},
{
    $project:
    {
        "docs":1,
        "n":{"$size":"$docs"}
    }
},
{
    $match:{"n":{$gt:0}}
}])

Another solution:

db.c.aggregate([
{
    $project:
    {
        docs:
        {
            $filter:
            {
                input:"$docs",
                as:"doc",
                cond:{$eq:['$$doc.p',1]}
            }
        }
    },
},
{
    "$unwind":"$docs"
},
{
    "$group":
    {
        "_id": "$_id",
        "doc": { "$first": "$docs" }
    }
},
{
    $match:{"doc.c":2}
}])

Body:
So you mean you want to extract the values from an array and present it in a "flat" structure?

If this is what you mean you'd need something like this:

db.collectionName.aggregate([
{
  $match: {
    "docs.p": 1,
    "docs.c": 2
  }
},
{ $unwind: "$docs"},
{
  $match: {
    "docs.p": 1,
    "docs.c": 2
  }
}
])

So basically I would $match twice. In the first one you match all documents that contain these values. Then you $unwind to "flatten" your array structure. And last step I'd use $match again to only take the set that you actually need.


问:
css make tbody same size as table
I can't get the tbody element to fully fill the table element:

```<code><table>
  <tbody>
    <tr>
      ...
    </tr>
  </tbody>
</table>
</code>```

The CSS is:

```<code>table {
  width: 100%;
  margin: 0 0;
  padding: 0 0;
}

tbody {
  margin: 0 0;
  padding: 0 0;
}
</code>```

Resulting table dimensions (in firefox 56):

Resulting tbody dimensions (in firefox 56):

This leaves a 2 pixel white border surrounding the contents of the table, that I want to get rid of. Is there some other CSS property that I need to zero out?

答:
This is because of built in borders and border spacing.

To correct the issue add the border-collapse: collapse; style to the table.

Title: css make tbody same size as table

Body:
I can't get the tbody element to fully fill the table element:

      ...

The CSS is:

table {
  width: 100%;
  margin: 0 0;
  padding: 0 0;
}

tbody {
  margin: 0 0;
  padding: 0 0;
}

Resulting table dimensions (in firefox 56):

Resulting tbody dimensions (in firefox 56):

This leaves a 2 pixel white border surrounding the contents of the table, that I want to get rid of. Is there some other CSS property that I need to zero out?


问:
Is Luigi suited for building a pipeline around lots of small files (100k+)
My first gut reaction is that Luigi isn't suited for this sort of thing, but I would like the "pipeline" functionality and everything keeps pointing me back to Luigi/Airflow. I can't use Airflow as it is a Windows environment.

My use-case:

So currently from my “source” folder we have 20 or so machines that produce XML data. Over time, some process puts these files into a folder continually on each machine (its log data). On any given day these machines could have 0 files in the folder or it could have 100k+ files (each machine). Eventually someone will go delete all of the files.

One part of this process is to to watch all of these directories on all of these machines, and copy the files down to an archive folder if they are new.

My current process makes a listing of all the files on each machine every 5 minutes, grabs a listing of the files and loops over the source checking if the file is available at the destination. Copies if it doesn't exist at destination, skips if it does.

It seems that Luigi wants to work with only "a" (singular) file in its output and/or target. The issue is, I could have 1 new file, or several thousand files that shows up.

This same exact issue happens through the entire process. As the next step in my pipeline is to add the files and its metadata information (size, filename, directory location) to a db record. At that point another process reads all of the metadata record rows and puts them into a content extracted table of the XML log data.

Is Luigi even suited for something like this? Luigi seems to want to deal with one thing, do some work on it, and then emit that information out to another single file.

答: I can tell you that mine workflow works with 10K log files every day without any glitches. The main good stuff here that I have created one task for work with each file.</p>


问:
Why do these links exceed the width?
How can we explain that these links exceed the 200px width:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo
</div></code>```

whereas, if we add a newline after each , it doesn't:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
</div></code>```

What is the usual good practice to not be trapped in such corner cases?

答:
If you add

```<code>width:100%;
display:inline-block;
</code>```

to your .tag class, the links will stay within the bounds of the .small parent div.

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;width:100%;display:inline-block;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo
</div></code>```

Title: Why do these links exceed the width?

Body:
How can we explain that these links exceed the 200px width:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo

whereas, if we add a newline after each , it doesn't:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

2 January 2017
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo

What is the usual good practice to not be trapped in such corner cases?

Body:
If you add

width:100%;
display:inline-block;

to your .tag class, the links will stay within the bounds of the .small parent div.

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;width:100%;display:inline-block;  }

<div class="small">
<a class="date" href="blah">2 January 2017</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a>
</div>


问:
Python: why appending to a list results in same values
This is my code:

```<code>a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a)
print(res)
</code>```

The result is:

```<code>[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
</code>```

But I want the result to be:

```<code>[[0], [0, 1], [0, 1, 2]]
</code>```

I know the solution is using the shallow copy: res.append(a[:]). But can somebody tell me why?

答:
when you append the object "a", python actually appends a pointer that points to the original list "a". In the next iteration of the loop you change the original object, so all of the pointers to that object show the latest state of the object.
you can add print the lists in every iteration to see that in action.
What you want is to create a copy of "a", that would remain unchanged, and append the copy to "res". Like you said, using the syntax a[:] would do the job.</p>

Body:
This is my code:

a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a)
print(res)

The result is:

[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

But I want the result to be:

[[0], [0, 1], [0, 1, 2]]

I know the solution is using the shallow copy: res.append(a[:]). But can somebody tell me why?


问:
MVC5 File Upload and Display
I am currently having an issue with an MVC application that uploads a image to a file server.

```<code> public ActionResult UploadFile(HttpPostedFileBase file, string newFileName)
    {

        try
        {
            if (file.ContentLength > 0)
            {
                Bitmap bm = new Bitmap(file.InputStream);
                Bitmap final = new Bitmap(bm, 150, 150);
                final.SetResolution(72.0F, 72.0F);

                string _FileName = newFileName + ".jpg";
                string _path = Path.Combine(ConfigurationManager.AppSettings["imageDirectory"], _FileName);
                final.Save(_path,System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            ViewBag.Message = "File Uploaded Successfully!!";
            return RedirectToAction("Index");
        }
        catch
        {
            ViewBag.Message = "File upload failed!!";
            return RedirectToAction("Error");
        }
    }
</code>```

So the user chooses a file and uploads it to the to the Windows share.  This code works on my machine using IISExpress and on our Test server.  When deployed to our Production server, it appears to be working in that it redirects to Index but the file never changes on the File Server.

IISExpress, the Test server, and the Production Server all point to the same file directory too.

Another issue I ran into while troubleshooting this is that the image from the file server does not display when using the FQDN of the application.  So http://[appName].[domain].[com] cannot display pictures, but http://[appName] does display the image.  Just another weird issue, that did not show up in testing at all.

答:
Here is the problem and solution;

If it works on your development system then the problem is that you did not give readwrite access to app_data folder. HttpPostedFileBase always upload file temporarily into App_Store and its from there that your Save() method takes the file from. If you don't have App_Data folder, create it. You must give full ReadWrite access to IIS_USERS on your server

Title: MVC5 File Upload and Display

Body:
I am currently having an issue with an MVC application that uploads a image to a file server.

 public ActionResult UploadFile(HttpPostedFileBase file, string newFileName)
    {

        try
        {
            if (file.ContentLength > 0)
            {
                Bitmap bm = new Bitmap(file.InputStream);
                Bitmap final = new Bitmap(bm, 150, 150);
                final.SetResolution(72.0F, 72.0F);

                string _FileName = newFileName + ".jpg";
                string _path = Path.Combine(ConfigurationManager.AppSettings["imageDirectory"], _FileName);
                final.Save(_path,System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            ViewBag.Message = "File Uploaded Successfully!!";
            return RedirectToAction("Index");
        }
        catch
        {
            ViewBag.Message = "File upload failed!!";
            return RedirectToAction("Error");
        }
    }

So the user chooses a file and uploads it to the to the Windows share.  This code works on my machine using IISExpress and on our Test server.  When deployed to our Production server, it appears to be working in that it redirects to Index but the file never changes on the File Server.

IISExpress, the Test server, and the Production Server all point to the same file directory too.

Another issue I ran into while troubleshooting this is that the image from the file server does not display when using the FQDN of the application.  So http://[appName].[domain].[com] cannot display pictures, but http://[appName] does display the image.  Just another weird issue, that did not show up in testing at all.